2 /************************************************************************
3 * MXChange v0.2.1 Start: 04/04/2009 *
4 * =============== Last change: 04/04/2009 *
6 * -------------------------------------------------------------------- *
7 * File : wrapper-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Wrapper functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Wrapper-Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
45 function readFromFile ($FQFN, $sqlPrepare = false) {
46 // Sanity-check if file is there (should be there, but just to make it sure)
47 if (!isFileReadable($FQFN)) {
48 // This should not happen
49 debug_report_bug(__FUNCTION__.': File ' . basename($FQFN) . ' is not readable!');
53 if (function_exists('file_get_contents')) {
55 $content = file_get_contents($FQFN);
57 // Fall-back to implode-file chain
58 $content = implode('', file($FQFN));
61 // Prepare SQL queries?
62 if ($sqlPrepare === true) {
63 // Remove some unwanted chars
64 $content = str_replace("\r", '', $content);
65 $content = str_replace("\n\n", "\n", $content);
72 // Writes content to a file
73 function writeToFile ($FQFN, $content, $aquireLock = false) {
74 // Is the file writeable?
75 if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!changeMode($FQFN, 0644))) {
77 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
83 // By default all is failed...
86 // Is the function there?
87 if (function_exists('file_put_contents')) {
89 if ($aquireLock === true) {
90 // Write it directly with lock
91 $return = file_put_contents($FQFN, $content, LOCK_EX);
94 $return = file_put_contents($FQFN, $content);
97 // Write it with fopen
98 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
101 if ($aquireLock === true) flock($fp, LOCK_EX);
104 fwrite($fp, $content);
110 // Mark it as readable
111 $GLOBALS['file_readable'][$FQFN] = true;
114 return changeMode($FQFN, 0644);
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()) {
122 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
127 // @TODO Implement $compress
128 function encodeString ($str, $compress = true) {
129 $str = urlencode(base64_encode(compileUriCode($str)));
133 // Decode strings encoded with encodeString()
134 // @TODO Implement $decompress
135 function decodeString ($str, $decompress = true) {
136 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
140 // Smartly adds slashes
141 function smartAddSlashes ($unquoted) {
143 if (!isset($GLOBALS['smart_addslashes'][$unquoted])) {
145 $unquoted = str_replace("\\", '', $unquoted);
147 // Put it in cache and add slashes
148 $GLOBALS['smart_addslashes'][$unquoted] = addslashes($unquoted);
152 return $GLOBALS['smart_addslashes'][$unquoted];
155 // Decode entities in a nicer way
156 function decodeEntities ($str) {
157 // Decode the entities to UTF-8 now
158 $decodedString = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
160 // Return decoded string
161 return $decodedString;
164 // Merges an array together but only if both are arrays
165 function merge_array ($array1, $array2) {
166 // Are both an array?
167 if ((!is_array($array1)) && (!is_array($array2))) {
168 // Both are not arrays
169 debug_report_bug(__FUNCTION__ . ': No arrays provided!');
170 } elseif (!is_array($array1)) {
171 // Left one is not an array
172 debug_report_bug(sprintf("[%s:%s] array1 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array1)));
173 } elseif (!is_array($array2)) {
174 // Right one is not an array
175 debug_report_bug(sprintf("[%s:%s] array2 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array2)));
178 // Merge all together
179 return array_merge($array1, $array2);
182 // Check if given FQFN is a readable file
183 function isFileReadable ($FQFN) {
185 if (!isset($GLOBALS['file_readable'][$FQFN])) {
187 $GLOBALS['file_readable'][$FQFN] = ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
191 return $GLOBALS['file_readable'][$FQFN];
194 // Checks wether the given FQFN is a directory and not ., .. or .svn
195 function isDirectory ($FQFN) {
197 if (!isset($GLOBALS['is_directory'][$FQFN])) {
199 $baseName = basename($FQFN);
202 $GLOBALS['is_directory'][$FQFN] = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
206 return $GLOBALS['is_directory'][$FQFN];
209 // "Getter" for remote IP number
210 function detectRemoteAddr () {
211 // Get remote ip from environment
212 $remoteAddr = determineRealRemoteAddress();
214 // Is removeip installed?
215 if (isExtensionActive('removeip')) {
217 $remoteAddr = getAnonymousRemoteAddress($remoteAddr);
224 // "Getter" for remote hostname
225 function detectRemoteHostname () {
226 // Get remote ip from environment
227 $remoteHost = getenv('REMOTE_HOST');
229 // Is removeip installed?
230 if (isExtensionActive('removeip')) {
232 $remoteHost = getAnonymousRemoteHost($remoteHost);
239 // "Getter" for user agent
240 function detectUserAgent () {
241 // Get remote ip from environment
242 $userAgent = getenv('HTTP_USER_AGENT');
244 // Is removeip installed?
245 if (isExtensionActive('removeip')) {
247 $userAgent = getAnonymousUserAgent($userAgent);
254 // "Getter" for referer
255 function detectReferer () {
256 // Get remote ip from environment
257 $referer = getenv('HTTP_REFERER');
259 // Is removeip installed?
260 if (isExtensionActive('removeip')) {
262 $referer = getAnonymousReferer($referer);
269 // Check wether we are installing
270 function isInstalling () {
271 // Determine wether we are installing
272 if (!isset($GLOBALS['mxchange_installing'])) {
273 // Check URL (css.php/js.php need this)
274 $GLOBALS['mxchange_installing'] = isGetRequestElementSet('installing');
278 return $GLOBALS['mxchange_installing'];
281 // Check wether this script is installed
282 function isInstalled () {
284 if (!isset($GLOBALS['is_installed'])) {
285 // Determine wether this script is installed
286 $GLOBALS['is_installed'] = (
291 isConfigEntrySet('MXCHANGE_INSTALLED')
293 getConfig('MXCHANGE_INSTALLED') == 'Y'
297 // New config file found and loaded
298 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
301 // New config file found, but not yet read
302 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
305 // Only new config file is found
306 !isIncludeReadable('inc/config.php')
308 // Is installation mode
315 // Then use the cache
316 return $GLOBALS['is_installed'];
319 // Check wether an admin is registered
320 function isAdminRegistered () {
321 return ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
324 // Checks wether the reset mode is active
325 function isResetModeEnabled () {
326 // Now simply check it
327 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
330 // Checks wether the debug mode is enabled
331 function isDebugModeEnabled () {
333 return ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
336 // Checks wether we shall debug regular expressions
337 function isDebugRegExpressionEnabled () {
339 return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
342 // Checks wether the cache instance is valid
343 function isCacheInstanceValid () {
344 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
347 // Copies a file from source to destination and verifies if that goes fine.
348 // This function should wrap the copy() command and make a nicer debug backtrace
349 // even if there is no xdebug extension installed.
350 function copyFileVerified ($source, $dest, $chmod = '') {
351 // Failed is the default
354 // Is the source file there?
355 if (!isFileReadable($source)) {
357 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
360 // Is the target directory there?
361 if (!isDirectory(dirname($dest))) {
363 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
366 // Now try to copy it
367 if (!copy($source, $dest)) {
368 // Something went wrong
369 debug_report_bug('copy() has failed to copy the file.');
372 $GLOBALS['file_readable'][$dest] = true;
375 // If there are chmod rights set, apply them
376 if (!empty($chmod)) {
378 $status = changeMode($dest, $chmod);
388 // Wrapper function for header()
389 // Send a header but checks before if we can do so
390 function sendHeader ($header) {
391 // Is the header already sent?
392 if (headers_sent()) {
394 debug_report_bug('Headers already sent!');
398 header(trim($header));
401 // Wrapper function for chmod()
402 // @TODO Do some more sanity check here
403 function changeMode ($FQFN, $mode) {
404 // Is the file/directory there?
405 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
406 // Neither, so abort here
407 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
414 // Wrapper for unlink()
415 function removeFile ($FQFN) {
416 // Is the file there?
417 if (isFileReadable($FQFN)) {
419 $GLOBALS['file_readable'][$FQFN] = false;
422 return unlink($FQFN);
425 // All fine if no file was removed. If we change this to 'false' or rewrite
426 // above if() block it would be to restrictive.
430 // Wrapper for $_POST['sel']
431 function countPostSelection () {
432 return countSelection(postRequestElement('sel'));
435 // Checks wether the config-local.php is loaded
436 function isConfigLocalLoaded () {
437 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
440 // Checks wether a nickname or userid was entered and caches the result
441 function isNicknameUsed ($userid) {
445 // Is the cache there
446 if (isset($GLOBALS['is_nickname_used'][$userid])) {
448 $isUsed = $GLOBALS['is_nickname_used'][$userid];
451 $isUsed = ((isExtensionActive('nickname')) && (('' . round($userid) . '') != $userid));
453 // And write it to the cache
454 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
461 // Getter for 'what' value
462 function getWhat () {
467 if (isWhatSet(true)) {
469 $what = $GLOBALS['what'];
476 // Setter for 'what' value
477 function setWhat ($newWhat) {
478 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
481 // Setter for 'what' from configuration
482 function setWhatFromConfig ($configEntry) {
483 // Get 'what' from config
484 $what = getConfig($configEntry);
490 // Checks wether what is set and optionally aborts on miss
491 function isWhatSet ($strict = false) {
493 $isset = (isset($GLOBALS['what']));
495 // Should we abort here?
496 if (($strict === true) && ($isset === false)) {
498 debug_report_bug('what is empty.');
505 // Getter for 'action' value
506 function getAction () {
511 if (isActionSet(true)) {
513 $action = $GLOBALS['action'];
520 // Setter for 'action' value
521 function setAction ($newAction) {
522 $GLOBALS['action'] = SQL_ESCAPE($newAction);
525 // Checks wether action is set and optionally aborts on miss
526 function isActionSet ($strict = false) {
528 $isset = (isset($GLOBALS['action']));
530 // Should we abort here?
531 if (($strict === true) && ($isset === false)) {
533 debug_report_bug('action is empty.');
540 // Getter for 'module' value
541 function getModule ($strict = true) {
546 if (isModuleSet($strict)) {
548 $module = $GLOBALS['module'];
555 // Setter for 'module' value
556 function setModule ($newModule) {
557 // Secure it and make all modules lower-case
558 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
561 // Checks wether module is set and optionally aborts on miss
562 function isModuleSet ($strict = false) {
564 $isset = (!empty($GLOBALS['module']));
566 // Should we abort here?
567 if (($strict === true) && ($isset === false)) {
569 print 'Module not set!<pre>';
570 debug_print_backtrace();
572 debug_report_bug('module is empty.');
579 // Getter for 'output_mode' value
580 function getOutputMode () {
585 if (isOutputModeSet(true)) {
587 $output_mode = $GLOBALS['output_mode'];
594 // Setter for 'output_mode' value
595 function setOutputMode ($newOutputMode) {
596 $GLOBALS['output_mode'] = (int) $newOutputMode;
599 // Checks wether output_mode is set and optionally aborts on miss
600 function isOutputModeSet ($strict = false) {
602 $isset = (isset($GLOBALS['output_mode']));
604 // Should we abort here?
605 if (($strict === true) && ($isset === false)) {
607 debug_report_bug('output_mode is empty.');
614 // Enables block-mode
615 function enableBlockMode ($enabled = true) {
616 $GLOBALS['block_mode'] = $enabled;
619 // Checks wether block-mode is enabled
620 function isBlockModeEnabled () {
622 if (!isset($GLOBALS['block_mode'])) {
624 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
628 return $GLOBALS['block_mode'];
631 // Wrapper function for addPointsThroughReferalSystem()
632 function addPointsDirectly ($subject, $userid, $points) {
634 unset($GLOBALS['ref_level']);
636 // Call more complicated method (due to more parameters)
637 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
640 // Wrapper function to redirect from member-only modules to index
641 function redirectToIndexMemberOnlyModule () {
642 // Do the redirect here
643 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
646 // Wrapper function for checking if extension is installed and newer or same version
647 function isExtensionInstalledAndNewer ($ext_name, $version) {
649 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
650 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
653 // Wrapper function for checking if extension is installed and older than given version
654 function isExtensionInstalledAndOlder ($ext_name, $version) {
656 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
657 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
661 function setUsername ($userName) {
662 $GLOBALS['username'] = (string) $userName;
666 function getUsername () {
667 return $GLOBALS['username'];
670 // Wrapper function for installation phase
671 function isInstallationPhase () {
673 if (!isset($GLOBALS['installation_phase'])) {
675 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
679 return $GLOBALS['installation_phase'];
682 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
683 function isDemoModeActive () {
684 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
687 // Wrapper function to redirect to de-refered URL
688 function redirectToDereferedUrl ($URL) {
690 $URL = generateDerefererUrl($URL);
696 // Getter for PHP caching value
697 function getPhpCaching () {
698 return $GLOBALS['php_caching'];
701 // Checks wether the admin hash is set
702 function isAdminHashSet ($admin) {
703 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
706 // Setter for admin hash
707 function setAdminHash ($admin, $hash) {
708 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
711 // Init user data array
712 function initUserData () {
713 // User id should not be zero
714 if (getCurrentUserId() == '0') debug_report_bug('User id is zero.');
717 $GLOBALS['user_data'][getCurrentUserId()] = array();
720 // Getter for user data
721 function getUserData ($column) {
722 // User id should not be zero
723 if (getCurrentUserId() == '0') debug_report_bug('User id is zero.');
726 return $GLOBALS['user_data'][getCurrentUserId()][$column];
729 // Geter for whole user data array
730 function getUserDataArray () {
731 // User id should not be zero
732 if (getCurrentUserId() == '0') debug_report_bug('User id is zero.');
734 // Get the whole array
735 return $GLOBALS['user_data'][getCurrentUserId()];
738 // Checks if the user data is valid, this may indicate that the user has logged
739 // in, but you should use isMember() if you want to find that out.
740 function isUserDataValid () {
741 // User id should not be zero
742 if (getCurrentUserId() == '0') debug_report_bug('User id is zero.');
744 // Is the array there and filled?
745 return ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
748 // Setter for current userid
749 function setCurrentUserId ($userid) {
750 $GLOBALS['current_userid'] = bigintval($userid);
753 // Getter for current userid
754 function getCurrentUserId () {
755 // Return zero if not set
756 if (!isset($GLOBALS['current_userid'])) return 0;
759 return $GLOBALS['current_userid'];