48db9bbc05b706263abad490660594bfce5b9fb4
[mailer.git] / inc / wrapper-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 04/04/2009 *
4  * ===================                          Last change: 04/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : wrapper-functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Wrapper functions                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Wrapper-Funktionen                               *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Read a given file
46 function readFromFile ($FQFN) {
47         // Sanity-check if file is there (should be there, but just to make it sure)
48         if (!isFileReadable($FQFN)) {
49                 // This should not happen
50                 debug_report_bug(__FUNCTION__.': File ' . basename($FQFN) . ' is not readable!');
51         } // END - if
52
53         // Is it cached?
54         if (!isset($GLOBALS['file_content'][$FQFN])) {
55                 // Load the file
56                 if (function_exists('file_get_contents')) {
57                         // Use new function
58                         $GLOBALS['file_content'][$FQFN] = file_get_contents($FQFN);
59                 } else {
60                         // Fall-back to implode-file chain
61                         $GLOBALS['file_content'][$FQFN] = implode('', file($FQFN));
62                 }
63         } // END - if
64
65         // Return the content
66         return $GLOBALS['file_content'][$FQFN];
67 }
68
69 // Writes content to a file
70 function writeToFile ($FQFN, $content, $aquireLock = false) {
71         // Is the file writeable?
72         if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!changeMode($FQFN, 0644))) {
73                 // Not writeable!
74                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
75
76                 // Failed! :(
77                 return false;
78         } // END - if
79
80         // By default all is failed...
81         $return = false;
82
83         // Is the function there?
84         if (function_exists('file_put_contents')) {
85                 // With lock?
86                 if ($aquireLock === true) {
87                         // Write it directly with lock
88                         $return = file_put_contents($FQFN, $content, LOCK_EX);
89                 } else {
90                         // Write it directly
91                         $return = file_put_contents($FQFN, $content);
92                 }
93         } else {
94                 // Write it with fopen
95                 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
96
97                 // Aquire lock
98                 if ($aquireLock === true) flock($fp, LOCK_EX);
99
100                 // Write content
101                 fwrite($fp, $content);
102
103                 // Close stream
104                 fclose($fp);
105         }
106
107         // Mark it as readable
108         $GLOBALS['file_readable'][$FQFN] = true;
109
110         // Remember content in cache
111         $GLOBALS['file_content'][$FQFN] = $content;
112
113         // Return status
114         return changeMode($FQFN, 0644);
115 }
116
117 // Clears the output buffer. This function does *NOT* backup sent content.
118 function clearOutputBuffer () {
119         // Trigger an error on failure
120         if (!ob_end_clean()) {
121                 // Failed!
122                 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
123         } // END - if
124 }
125
126 // Encode strings
127 // @TODO Implement $compress
128 function encodeString ($str, $compress = true) {
129         $str = urlencode(base64_encode(compileUriCode($str)));
130         return $str;
131 }
132
133 // Decode strings encoded with encodeString()
134 // @TODO Implement $decompress
135 function decodeString ($str, $decompress = true) {
136         $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
137         return $str;
138 }
139
140 // Decode entities in a nicer way
141 function decodeEntities ($str, $quote = ENT_NOQUOTES) {
142         // Decode the entities to UTF-8 now
143         $decodedString = html_entity_decode($str, $quote, 'UTF-8');
144
145         // Return decoded string
146         return $decodedString;
147 }
148
149 // Merges an array together but only if both are arrays
150 function merge_array ($array1, $array2) {
151         // Are both an array?
152         if ((!is_array($array1)) && (!is_array($array2))) {
153                 // Both are not arrays
154                 debug_report_bug(__FUNCTION__ . ': No arrays provided!');
155         } elseif (!is_array($array1)) {
156                 // Left one is not an array
157                 debug_report_bug(sprintf("[%s:%s] array1 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array1)));
158         } elseif (!is_array($array2)) {
159                 // Right one is not an array
160                 debug_report_bug(sprintf("[%s:%s] array2 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array2)));
161         }
162
163         // Merge all together
164         return array_merge($array1, $array2);
165 }
166
167 // Check if given FQFN is a readable file
168 function isFileReadable ($FQFN) {
169         // Do we have cache?
170         if (!isset($GLOBALS['file_readable'][$FQFN])) {
171                 // Check all...
172                 $GLOBALS['file_readable'][$FQFN] = ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
173
174                 // Debug message
175                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CHECK! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
176         } else {
177                 // Cache used
178                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CACHE! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
179         }
180
181         // Return result
182         return $GLOBALS['file_readable'][$FQFN];
183 }
184
185 // Checks wether the given FQFN is a directory and not ., .. or .svn
186 function isDirectory ($FQFN) {
187         // Do we have cache?
188         if (!isset($GLOBALS['is_directory'][$FQFN])) {
189                 // Generate baseName
190                 $baseName = basename($FQFN);
191
192                 // Check it
193                 $GLOBALS['is_directory'][$FQFN] = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
194         } // END - if
195
196         // Return the result
197         return $GLOBALS['is_directory'][$FQFN];
198 }
199
200 // "Getter" for remote IP number
201 function detectRemoteAddr () {
202         // Get remote ip from environment
203         $remoteAddr = determineRealRemoteAddress();
204
205         // Is removeip installed?
206         if (isExtensionActive('removeip')) {
207                 // Then anonymize it
208                 $remoteAddr = getAnonymousRemoteAddress($remoteAddr);
209         } // END - if
210
211         // Return it
212         return $remoteAddr;
213 }
214
215 // "Getter" for remote hostname
216 function detectRemoteHostname () {
217         // Get remote ip from environment
218         $remoteHost = getenv('REMOTE_HOST');
219
220         // Is removeip installed?
221         if (isExtensionActive('removeip')) {
222                 // Then anonymize it
223                 $remoteHost = getAnonymousRemoteHost($remoteHost);
224         } // END - if
225
226         // Return it
227         return $remoteHost;
228 }
229
230 // "Getter" for user agent
231 function detectUserAgent ($alwaysReal = false) {
232         // Get remote ip from environment
233         $userAgent = getenv('HTTP_USER_AGENT');
234
235         // Is removeip installed?
236         if ((isExtensionActive('removeip')) && ($alwaysReal === false)) {
237                 // Then anonymize it
238                 $userAgent = getAnonymousUserAgent($userAgent);
239         } // END - if
240
241         // Return it
242         return $userAgent;
243 }
244
245 // "Getter" for referer
246 function detectReferer () {
247         // Get remote ip from environment
248         $referer = getenv('HTTP_REFERER');
249
250         // Is removeip installed?
251         if (isExtensionActive('removeip')) {
252                 // Then anonymize it
253                 $referer = getAnonymousReferer($referer);
254         } // END - if
255
256         // Return it
257         return $referer;
258 }
259
260 // "Getter" for request URI
261 function detectRequestUri () {
262         // Return it
263         return (getenv('REQUEST_URI'));
264 }
265
266 // "Getter" for query string
267 function detectQueryString () {
268         return str_replace('&', '&amp;', (getenv('QUERY_STRING')));
269 }
270
271 // "Getter" for SERVER_NAME
272 function detectServerName () {
273         // Return it
274         return (getenv('SERVER_NAME'));
275 }
276
277 // Check wether we are installing
278 function isInstalling () {
279         // Determine wether we are installing
280         if (!isset($GLOBALS['mailer_installing'])) {
281                 // Check URL (css.php/js.php need this)
282                 $GLOBALS['mailer_installing'] = isGetRequestParameterSet('installing');
283         } // END - if
284
285         // Return result
286         return $GLOBALS['mailer_installing'];
287 }
288
289 // Check wether this script is installed
290 function isInstalled () {
291         // Do we have cache?
292         if (!isset($GLOBALS['is_installed'])) {
293                 // Determine wether this script is installed
294                 $GLOBALS['is_installed'] = (
295                 (
296                         // First is config
297                         (
298                                 (
299                                         isConfigEntrySet('MXCHANGE_INSTALLED')
300                                 ) && (
301                                         getConfig('MXCHANGE_INSTALLED') == 'Y'
302                                 )
303                         )
304                 ) || (
305                         // New config file found and loaded
306                         isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
307                 ) || (
308                         (
309                                 // New config file found, but not yet read
310                                 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
311                         ) && (
312                                 (
313                                         // Only new config file is found
314                                         !isIncludeReadable('inc/config.php')
315                                 ) || (
316                                         // Is installation mode
317                                         !isInstalling()
318                                 )
319                         )
320                 ));
321         } // END - if
322
323         // Then use the cache
324         return $GLOBALS['is_installed'];
325 }
326
327 // Check wether an admin is registered
328 function isAdminRegistered () {
329         // Is cache set?
330         if (!isset($GLOBALS['is_admin_registered'])) {
331                 // Simply check it
332                 $GLOBALS['is_admin_registered'] = ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
333         } // END - if
334
335         // Return it
336         return $GLOBALS['is_admin_registered'];
337 }
338
339 // Checks wether the reset mode is active
340 function isResetModeEnabled () {
341         // Now simply check it
342         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
343 }
344
345 // Checks wether the debug mode is enabled
346 function isDebugModeEnabled () {
347         // Is cache set?
348         if (!isset($GLOBALS['is_debugmode_enabled'])) {
349                 // Simply check it
350                 $GLOBALS['is_debugmode_enabled'] = ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
351         } // END - if
352
353         // Return it
354         return $GLOBALS['is_debugmode_enabled'];
355 }
356
357 // Checks wether SQL debugging is enabled
358 function isSqlDebuggingEnabled () {
359         // Is cache set?
360         if (!isset($GLOBALS['is_sql_debug_enabled'])) {
361                 // Determine if SQL debugging is enabled
362                 $GLOBALS['is_sql_debug_enabled'] = ((isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y'));
363         } // END - if
364
365         // Return it
366         return $GLOBALS['is_sql_debug_enabled'];
367 }
368
369 // Checks wether we shall debug regular expressions
370 function isDebugRegularExpressionEnabled () {
371         // Is cache set?
372         if (!isset($GLOBALS['is_regular_exp_debug_enabled'])) {
373                 // Simply check it
374                 $GLOBALS['is_regular_exp_debug_enabled'] = ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
375         } // END - if
376
377         // Return it
378         return $GLOBALS['is_regular_exp_debug_enabled'];
379 }
380
381 // Checks wether the cache instance is valid
382 function isCacheInstanceValid () {
383         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
384 }
385
386 // Copies a file from source to destination and verifies if that goes fine.
387 // This function should wrap the copy() command and make a nicer debug backtrace
388 // even if there is no xdebug extension installed.
389 function copyFileVerified ($source, $dest, $chmod = '') {
390         // Failed is the default
391         $status = false;
392
393         // Is the source file there?
394         if (!isFileReadable($source)) {
395                 // Then abort here
396                 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
397         } // END - if
398
399         // Is the target directory there?
400         if (!isDirectory(dirname($dest))) {
401                 // Then abort here
402                 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
403         } // END - if
404
405         // Now try to copy it
406         if (!copy($source, $dest)) {
407                 // Something went wrong
408                 debug_report_bug('copy() has failed to copy the file.');
409         } else {
410                 // Reset cache
411                 $GLOBALS['file_readable'][$dest] = true;
412         }
413
414         // If there are chmod rights set, apply them
415         if (!empty($chmod)) {
416                 // Try to apply them
417                 $status = changeMode($dest, $chmod);
418         } else {
419                 // All fine
420                 $status = true;
421         }
422
423         // All fine
424         return $status;
425 }
426
427 // Wrapper function for header()
428 // Send a header but checks before if we can do so
429 function sendHeader ($header) {
430         // Send the header
431         //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
432         $GLOBALS['header'][] = trim($header);
433 }
434
435 // Flushes all headers
436 function flushHeaders () {
437         // Is the header already sent?
438         if (headers_sent()) {
439                 // Then abort here
440                 debug_report_bug('Headers already sent!');
441         } // END - if
442
443         // Flush all headers if found
444         if ((isset($GLOBALS['header'])) && (is_array($GLOBALS['header']))) {
445                 foreach ($GLOBALS['header'] as $header) {
446                         header($header);
447                 } // END - foreach
448         } // END - if
449
450         // Mark them as flushed
451         $GLOBALS['header'] = array();
452 }
453
454 // Wrapper function for chmod()
455 // @TODO Do some more sanity check here
456 function changeMode ($FQFN, $mode) {
457         // Is the file/directory there?
458         if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
459                 // Neither, so abort here
460                 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
461         } // END - if
462
463         // Try to set them
464         chmod($FQFN, $mode);
465 }
466
467 // Wrapper for unlink()
468 function removeFile ($FQFN) {
469         // Is the file there?
470         if (isFileReadable($FQFN)) {
471                 // Reset cache first
472                 $GLOBALS['file_readable'][$FQFN] = false;
473
474                 // Yes, so remove it
475                 return unlink($FQFN);
476         } // END - if
477
478         // All fine if no file was removed. If we change this to 'false' or rewrite
479         // above if() block it would be to restrictive.
480         return true;
481 }
482
483 // Wrapper for $_POST['sel']
484 function countPostSelection ($element = 'sel') {
485         // Is it set?
486         if (isPostRequestParameterSet($element)) {
487                 // Return counted elements
488                 return countSelection(postRequestParameter($element));
489         } else {
490                 // Return zero if not found
491                 return 0;
492         }
493 }
494
495 // Checks wether the config-local.php is loaded
496 function isConfigLocalLoaded () {
497         return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
498 }
499
500 // Checks wether a nickname or userid was entered and caches the result
501 function isNicknameUsed ($userid) {
502         // Default is false
503         $isUsed = false;
504
505         // Is the cache there
506         if (isset($GLOBALS['is_nickname_used'][$userid])) {
507                 // Then use it
508                 $isUsed = $GLOBALS['is_nickname_used'][$userid];
509         } else {
510                 // Determine it
511                 $isUsed = (('' . round($userid) . '') != $userid);
512
513                 // And write it to the cache
514                 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
515         }
516
517         // Return the result
518         return $isUsed;
519 }
520
521 // Getter for 'what' value
522 function getWhat () {
523         // Default is null
524         $what = null;
525
526         // Is the value set?
527         if (isWhatSet(true)) {
528                 // Then use it
529                 $what = $GLOBALS['what'];
530         } // END - if
531
532         // Return it
533         return $what;
534 }
535
536 // Setter for 'what' value
537 function setWhat ($newWhat) {
538         $GLOBALS['what'] = SQL_ESCAPE($newWhat);
539 }
540
541 // Setter for 'what' from configuration
542 function setWhatFromConfig ($configEntry) {
543         // Get 'what' from config
544         $what = getConfig($configEntry);
545
546         // Set it
547         setWhat($what);
548 }
549
550 // Checks wether what is set and optionally aborts on miss
551 function isWhatSet ($strict =  false) {
552         // Check for it
553         $isset = isset($GLOBALS['what']);
554
555         // Should we abort here?
556         if (($strict === true) && ($isset === false)) {
557                 // Output backtrace
558                 debug_report_bug('what is empty.');
559         } // END - if
560
561         // Return it
562         return $isset;
563 }
564
565 // Getter for 'action' value
566 function getAction () {
567         // Default is null
568         $action = null;
569
570         // Is the value set?
571         if (isActionSet(true)) {
572                 // Then use it
573                 $action = $GLOBALS['action'];
574         } // END - if
575
576         // Return it
577         return $action;
578 }
579
580 // Setter for 'action' value
581 function setAction ($newAction) {
582         $GLOBALS['action'] = SQL_ESCAPE($newAction);
583 }
584
585 // Checks wether action is set and optionally aborts on miss
586 function isActionSet ($strict =  false) {
587         // Check for it
588         $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
589
590         // Should we abort here?
591         if (($strict === true) && ($isset === false)) {
592                 // Output backtrace
593                 debug_report_bug('action is empty.');
594         } // END - if
595
596         // Return it
597         return $isset;
598 }
599
600 // Getter for 'module' value
601 function getModule ($strict = true) {
602         // Default is null
603         $module = null;
604
605         // Is the value set?
606         if (isModuleSet($strict)) {
607                 // Then use it
608                 $module = $GLOBALS['module'];
609         } // END - if
610
611         // Return it
612         return $module;
613 }
614
615 // Setter for 'module' value
616 function setModule ($newModule) {
617         // Secure it and make all modules lower-case
618         $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
619 }
620
621 // Checks wether module is set and optionally aborts on miss
622 function isModuleSet ($strict =  false) {
623         // Check for it
624         $isset = (!empty($GLOBALS['module']));
625
626         // Should we abort here?
627         if (($strict === true) && ($isset === false)) {
628                 // Output backtrace
629                 debug_report_bug('module is empty.');
630         } // END - if
631
632         // Return it
633         return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
634 }
635
636 // Getter for 'output_mode' value
637 function getOutputMode () {
638         // Default is null
639         $output_mode = null;
640
641         // Is the value set?
642         if (isOutputModeSet(true)) {
643                 // Then use it
644                 $output_mode = $GLOBALS['output_mode'];
645         } // END - if
646
647         // Return it
648         return $output_mode;
649 }
650
651 // Setter for 'output_mode' value
652 function setOutputMode ($newOutputMode) {
653         $GLOBALS['output_mode'] = (int) $newOutputMode;
654 }
655
656 // Checks wether output_mode is set and optionally aborts on miss
657 function isOutputModeSet ($strict =  false) {
658         // Check for it
659         $isset = (isset($GLOBALS['output_mode']));
660
661         // Should we abort here?
662         if (($strict === true) && ($isset === false)) {
663                 // Output backtrace
664                 debug_report_bug('output_mode is empty.');
665         } // END - if
666
667         // Return it
668         return $isset;
669 }
670
671 // Enables block-mode
672 function enableBlockMode ($enabled = true) {
673         $GLOBALS['block_mode'] = $enabled;
674 }
675
676 // Checks wether block-mode is enabled
677 function isBlockModeEnabled () {
678         // Abort if not set
679         if (!isset($GLOBALS['block_mode'])) {
680                 // Needs to be fixed
681                 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
682         } // END - if
683
684         // Return it
685         return $GLOBALS['block_mode'];
686 }
687
688 // Wrapper function for addPointsThroughReferalSystem()
689 function addPointsDirectly ($subject, $userid, $points) {
690         // Reset level here
691         unset($GLOBALS['ref_level']);
692
693         // Call more complicated method (due to more parameters)
694         return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
695 }
696
697 // Wrapper function to redirect from member-only modules to index
698 function redirectToIndexMemberOnlyModule () {
699         // Do the redirect here
700         redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
701 }
702
703 // Wrapper function to redirect to current URL
704 function redirectToRequestUri () {
705         redirectToUrl(basename(detectRequestUri()));
706 }
707
708 // Wrapper function to redirect to de-refered URL
709 function redirectToDereferedUrl ($URL) {
710         // Redirect to to
711         redirectToUrl(generateDerefererUrl($URL));
712 }
713
714 // Wrapper function for checking if extension is installed and newer or same version
715 function isExtensionInstalledAndNewer ($ext_name, $version) {
716         // Is an cache entry found?
717         if (!isset($GLOBALS['ext_installed_newer'][$ext_name][$version])) {
718                 $GLOBALS['ext_installed_newer'][$ext_name][$version] = ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
719         } else {
720                 // Cache hits should be incremented twice
721                 incrementStatsEntry('cache_hits', 2);
722         }
723
724         // Return it
725         //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=&gt;'.$version.':'.intval($GLOBALS['ext_installed_newer'][$ext_name][$version]).'<br />';
726         return $GLOBALS['ext_installed_newer'][$ext_name][$version];
727 }
728
729 // Wrapper function for checking if extension is installed and older than given version
730 function isExtensionInstalledAndOlder ($ext_name, $version) {
731         // Is an cache entry found?
732         if (!isset($GLOBALS['ext_installed_older'][$ext_name][$version])) {
733                 $GLOBALS['ext_installed_older'][$ext_name][$version] = ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
734         } else {
735                 // Cache hits should be incremented twice
736                 incrementStatsEntry('cache_hits', 2);
737         }
738
739         // Return it
740         //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'&lt;'.$version.':'.intval($GLOBALS['ext_installed_older'][$ext_name][$version]).'<br />';
741         return $GLOBALS['ext_installed_older'][$ext_name][$version];
742 }
743
744 // Set username
745 function setUsername ($userName) {
746         $GLOBALS['username'] = (string) $userName;
747 }
748
749 // Get username
750 function getUsername () {
751         // User name set?
752         if (!isset($GLOBALS['username'])) {
753                 // No, so it has to be a guest
754                 $GLOBALS['username'] = getMessage('USERNAME_GUEST');
755         } // END - if
756
757         // Return it
758         return $GLOBALS['username'];
759 }
760
761 // Wrapper function for installation phase
762 function isInstallationPhase () {
763         // Do we have cache?
764         if (!isset($GLOBALS['installation_phase'])) {
765                 // Determine it
766                 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
767         } // END - if
768
769         // Return result
770         return $GLOBALS['installation_phase'];
771 }
772
773 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
774 function isDemoModeActive () {
775         // Is cache set?
776         if (!isset($GLOBALS['demo_mode_active'])) {
777                 // Simply check it
778                 $GLOBALS['demo_mode_active'] = ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
779         } // END - if
780
781         // Return it
782         return $GLOBALS['demo_mode_active'];
783 }
784
785 // Getter for PHP caching value
786 function getPhpCaching () {
787         return $GLOBALS['php_caching'];
788 }
789
790 // Checks wether the admin hash is set
791 function isAdminHashSet ($admin) {
792         /**
793          * @TODO Do we really need this check? If yes, try to fix this:
794          * 1.:functions.php:2504, debug_get_mailable_backtrace(0)
795          * 2.:wrapper-functions.php:744, debug_report_bug(1)
796          * 3.:mysql-manager.php:728, isAdminHashSet(1)
797          * 4.:filters.php:384, isAdmin(0)
798          * 5.:debug_get_mailable_backtrace:2457, FILTER_DETERMINE_USERNAME(1)
799          * 6.:filter-functions.php:280, call_user_func_array(2)
800          * 7.:load_cache.php:74, runFilterChain(1)
801          * 8.:inc-functions.php:131, include(1)
802          * 9.:inc-functions.php:145, loadInclude(1)
803          * 10.:mysql-connect.php:104, loadIncludeOnce(1)
804          * 11.:inc-functions.php:131, include(1)
805          * 12.:inc-functions.php:145, loadInclude(1)
806          * 13.:config-global.php:106, loadIncludeOnce(1)
807          * 14.:js.php:57, require(1)
808          */
809         if (!isset($GLOBALS['cache_array']['admin'])) {
810                 debug_report_bug('Cache not set.');
811         } // END - if
812
813         // Check for admin hash
814         return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
815 }
816
817 // Setter for admin hash
818 function setAdminHash ($admin, $hash) {
819         $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
820 }
821
822 // Init user data array
823 function initUserData () {
824         // User id should not be zero
825         if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
826
827         // Init the user
828         $GLOBALS['user_data'][getCurrentUserId()] = array();
829 }
830
831 // Getter for user data
832 function getUserData ($column) {
833         // User id should not be zero
834         if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
835
836         // Return the value
837         return $GLOBALS['user_data'][getCurrentUserId()][$column];
838 }
839
840 // Geter for whole user data array
841 function getUserDataArray () {
842         // Get user id
843         $uid = getCurrentUserId();
844
845         // User id should not be zero
846         if ($uid < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
847
848         // Get the whole array if found
849         if (isset($GLOBALS['user_data'][$uid])) {
850                 // Found, so return it
851                 return $GLOBALS['user_data'][$uid];
852         } else {
853                 // Return empty array
854                 return array();
855         }
856 }
857
858 // Checks if the user data is valid, this may indicate that the user has logged
859 // in, but you should use isMember() if you want to find that out.
860 function isUserDataValid () {
861         // User id should not be zero so abort here
862         if (!isCurrentUserIdSet()) return false;
863
864         // Is it cached?
865         if (!isset($GLOBALS['is_userdata_valid'][getCurrentUserId()])) {
866                 // Determine it
867                 $GLOBALS['is_userdata_valid'][getCurrentUserId()] = ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
868         } // END - if
869
870         // Return the result
871         return $GLOBALS['is_userdata_valid'][getCurrentUserId()];
872 }
873
874 // Setter for current userid
875 function setCurrentUserId ($userid) {
876         // Set userid
877         $GLOBALS['current_userid'] = bigintval($userid);
878
879         // Unset it to re-determine the actual state
880         unset($GLOBALS['is_userdata_valid'][$userid]);
881 }
882
883 // Getter for current userid
884 function getCurrentUserId () {
885         // Userid must be set before it can be used
886         if (!isCurrentUserIdSet()) {
887                 // Not set
888                 debug_report_bug('User id is not set.');
889         } // END - if
890
891         // Return the userid
892         return $GLOBALS['current_userid'];
893 }
894
895 // Checks if current userid is set
896 function isCurrentUserIdSet () {
897         return ((isset($GLOBALS['current_userid'])) && ($GLOBALS['current_userid'] > 0));
898 }
899
900 // Checks wether we are debugging template cache
901 function isDebuggingTemplateCache () {
902         return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
903 }
904
905 // Wrapper for fetchUserData() and getUserData() calls
906 function getFetchedUserData ($keyColumn, $userid, $valueColumn) {
907         // Is it cached?
908         if (!isset($GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn])) {
909                 // Default is 'guest'
910                 $data = getMessage('USERNAME_GUEST');
911
912                 // Can we fetch the user data?
913                 if (($userid > 0) && (fetchUserData($userid, $keyColumn))) {
914                         // Now get the data back
915                         $data = getUserData($valueColumn);
916                 } // END - if
917
918                 // Cache it
919                 $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn] = $data;
920         } // END - if
921
922         // Return it
923         return $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn];
924 }
925
926 // Wrapper for strpos() to ease porting from deprecated ereg() function
927 function isInString ($needle, $haystack) {
928         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'needle=' . $needle . ', haystack=' . $haystack . ', returned=' . intval(strpos($haystack, $needle) !== false));
929         return (strpos($haystack, $needle) !== false);
930 }
931
932 // Wrapper for strpos() to ease porting from deprecated eregi() function
933 // This function is case-insensitive
934 function isInStringIgnoreCase ($needle, $haystack) {
935         return (isInString(strtolower($needle), strtolower($haystack)));
936 }
937
938 // Wrapper to check for if fatal errors where detected
939 function ifFatalErrorsDetected () {
940         // Just call the inner function
941         return (getTotalFatalErrors() > 0);
942 }
943
944 // [EOF]
945 ?>