2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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) {
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 (!isset($GLOBALS['file_content'][$FQFN])) {
55 if (function_exists('file_get_contents')) {
57 $GLOBALS['file_content'][$FQFN] = file_get_contents($FQFN);
59 // Fall-back to implode-file chain
60 $GLOBALS['file_content'][$FQFN] = implode('', file($FQFN));
65 return $GLOBALS['file_content'][$FQFN];
68 // Writes content to a file
69 function writeToFile ($FQFN, $content, $aquireLock = false) {
70 // Is the file writeable?
71 if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!changeMode($FQFN, 0644))) {
73 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
79 // By default all is failed...
82 // Is the function there?
83 if (function_exists('file_put_contents')) {
85 if ($aquireLock === true) {
86 // Write it directly with lock
87 $return = file_put_contents($FQFN, $content, LOCK_EX);
90 $return = file_put_contents($FQFN, $content);
93 // Write it with fopen
94 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
97 if ($aquireLock === true) flock($fp, LOCK_EX);
100 fwrite($fp, $content);
106 // Mark it as readable
107 $GLOBALS['file_readable'][$FQFN] = true;
109 // Remember content in cache
110 $GLOBALS['file_content'][$FQFN] = $content;
113 return changeMode($FQFN, 0644);
116 // Clears the output buffer. This function does *NOT* backup sent content.
117 function clearOutputBuffer () {
118 // Trigger an error on failure
119 if (!ob_end_clean()) {
121 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
126 // @TODO Implement $compress
127 function encodeString ($str, $compress = true) {
128 $str = urlencode(base64_encode(compileUriCode($str)));
132 // Decode strings encoded with encodeString()
133 // @TODO Implement $decompress
134 function decodeString ($str, $decompress = true) {
135 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
139 // Decode entities in a nicer way
140 function decodeEntities ($str, $quote = ENT_NOQUOTES) {
141 // Decode the entities to UTF-8 now
142 $decodedString = html_entity_decode($str, $quote, 'UTF-8');
144 // Return decoded string
145 return $decodedString;
148 // Merges an array together but only if both are arrays
149 function merge_array ($array1, $array2) {
150 // Are both an array?
151 if ((!is_array($array1)) && (!is_array($array2))) {
152 // Both are not arrays
153 debug_report_bug(__FUNCTION__ . ': No arrays provided!');
154 } elseif (!is_array($array1)) {
155 // Left one is not an array
156 debug_report_bug(sprintf("[%s:%s] array1 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array1)));
157 } elseif (!is_array($array2)) {
158 // Right one is not an array
159 debug_report_bug(sprintf("[%s:%s] array2 is not an array. array != %s", __FUNCTION__, __LINE__, gettype($array2)));
162 // Merge all together
163 return array_merge($array1, $array2);
166 // Check if given FQFN is a readable file
167 function isFileReadable ($FQFN) {
169 if (!isset($GLOBALS['file_readable'][$FQFN])) {
171 $GLOBALS['file_readable'][$FQFN] = ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
174 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CHECK! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
177 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CACHE! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
181 return $GLOBALS['file_readable'][$FQFN];
184 // Checks wether the given FQFN is a directory and not ., .. or .svn
185 function isDirectory ($FQFN) {
187 if (!isset($GLOBALS['is_directory'][$FQFN])) {
189 $baseName = basename($FQFN);
192 $GLOBALS['is_directory'][$FQFN] = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
196 return $GLOBALS['is_directory'][$FQFN];
199 // "Getter" for remote IP number
200 function detectRemoteAddr () {
201 // Get remote ip from environment
202 $remoteAddr = determineRealRemoteAddress();
204 // Is removeip installed?
205 if (isExtensionActive('removeip')) {
207 $remoteAddr = getAnonymousRemoteAddress($remoteAddr);
214 // "Getter" for remote hostname
215 function detectRemoteHostname () {
216 // Get remote ip from environment
217 $remoteHost = getenv('REMOTE_HOST');
219 // Is removeip installed?
220 if (isExtensionActive('removeip')) {
222 $remoteHost = getAnonymousRemoteHost($remoteHost);
229 // "Getter" for user agent
230 function detectUserAgent ($alwaysReal = false) {
231 // Get remote ip from environment
232 $userAgent = getenv('HTTP_USER_AGENT');
234 // Is removeip installed?
235 if ((isExtensionActive('removeip')) && ($alwaysReal === false)) {
237 $userAgent = getAnonymousUserAgent($userAgent);
244 // "Getter" for referer
245 function detectReferer () {
246 // Get remote ip from environment
247 $referer = getenv('HTTP_REFERER');
249 // Is removeip installed?
250 if (isExtensionActive('removeip')) {
252 $referer = getAnonymousReferer($referer);
259 // "Getter" for request URI
260 function detectRequestUri () {
262 return (getenv('REQUEST_URI'));
265 // "Getter" for query string
266 function detectQueryString () {
267 return str_replace('&', '&', (getenv('QUERY_STRING')));
270 // "Getter" for SERVER_NAME
271 function detectServerName () {
273 return (getenv('SERVER_NAME'));
276 // Check wether we are installing
277 function isInstalling () {
278 // Determine wether we are installing
279 if (!isset($GLOBALS['mxchange_installing'])) {
280 // Check URL (css.php/js.php need this)
281 $GLOBALS['mxchange_installing'] = isGetRequestParameterSet('installing');
285 return $GLOBALS['mxchange_installing'];
288 // Check wether this script is installed
289 function isInstalled () {
291 if (!isset($GLOBALS['is_installed'])) {
292 // Determine wether this script is installed
293 $GLOBALS['is_installed'] = (
298 isConfigEntrySet('MXCHANGE_INSTALLED')
300 getConfig('MXCHANGE_INSTALLED') == 'Y'
304 // New config file found and loaded
305 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
308 // New config file found, but not yet read
309 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
312 // Only new config file is found
313 !isIncludeReadable('inc/config.php')
315 // Is installation mode
322 // Then use the cache
323 return $GLOBALS['is_installed'];
326 // Check wether an admin is registered
327 function isAdminRegistered () {
328 return ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
331 // Checks wether the reset mode is active
332 function isResetModeEnabled () {
333 // Now simply check it
334 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
337 // Checks wether the debug mode is enabled
338 function isDebugModeEnabled () {
340 return ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
343 // Checks wether we shall debug regular expressions
344 function isDebugRegExpressionEnabled () {
346 return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
349 // Checks wether the cache instance is valid
350 function isCacheInstanceValid () {
351 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
354 // Copies a file from source to destination and verifies if that goes fine.
355 // This function should wrap the copy() command and make a nicer debug backtrace
356 // even if there is no xdebug extension installed.
357 function copyFileVerified ($source, $dest, $chmod = '') {
358 // Failed is the default
361 // Is the source file there?
362 if (!isFileReadable($source)) {
364 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
367 // Is the target directory there?
368 if (!isDirectory(dirname($dest))) {
370 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
373 // Now try to copy it
374 if (!copy($source, $dest)) {
375 // Something went wrong
376 debug_report_bug('copy() has failed to copy the file.');
379 $GLOBALS['file_readable'][$dest] = true;
382 // If there are chmod rights set, apply them
383 if (!empty($chmod)) {
385 $status = changeMode($dest, $chmod);
395 // Wrapper function for header()
396 // Send a header but checks before if we can do so
397 function sendHeader ($header) {
399 $GLOBALS['header'][] = trim($header);
402 // Flushes all headers
403 function flushHeaders () {
404 // Is the header already sent?
405 if (headers_sent()) {
407 debug_report_bug('Headers already sent!');
411 foreach ($GLOBALS['header'] as $header) {
415 // Mark them as flushed
416 $GLOBALS['header'] = array();
419 // Wrapper function for chmod()
420 // @TODO Do some more sanity check here
421 function changeMode ($FQFN, $mode) {
422 // Is the file/directory there?
423 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
424 // Neither, so abort here
425 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
432 // Wrapper for unlink()
433 function removeFile ($FQFN) {
434 // Is the file there?
435 if (isFileReadable($FQFN)) {
437 $GLOBALS['file_readable'][$FQFN] = false;
440 return unlink($FQFN);
443 // All fine if no file was removed. If we change this to 'false' or rewrite
444 // above if() block it would be to restrictive.
448 // Wrapper for $_POST['sel']
449 function countPostSelection ($element = 'sel') {
451 if (isPostRequestParameterSet($element)) {
452 // Return counted elements
453 return countSelection(postRequestParameter($element));
455 // Return zero if not found
460 // Checks wether the config-local.php is loaded
461 function isConfigLocalLoaded () {
462 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
465 // Checks wether a nickname or userid was entered and caches the result
466 function isNicknameUsed ($userid) {
470 // Is the cache there
471 if (isset($GLOBALS['is_nickname_used'][$userid])) {
473 $isUsed = $GLOBALS['is_nickname_used'][$userid];
476 $isUsed = (('' . round($userid) . '') != $userid);
478 // And write it to the cache
479 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
486 // Getter for 'what' value
487 function getWhat () {
492 if (isWhatSet(true)) {
494 $what = $GLOBALS['what'];
501 // Setter for 'what' value
502 function setWhat ($newWhat) {
503 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
506 // Setter for 'what' from configuration
507 function setWhatFromConfig ($configEntry) {
508 // Get 'what' from config
509 $what = getConfig($configEntry);
515 // Checks wether what is set and optionally aborts on miss
516 function isWhatSet ($strict = false) {
518 $isset = isset($GLOBALS['what']);
520 // Should we abort here?
521 if (($strict === true) && ($isset === false)) {
523 debug_report_bug('what is empty.');
530 // Getter for 'action' value
531 function getAction () {
536 if (isActionSet(true)) {
538 $action = $GLOBALS['action'];
545 // Setter for 'action' value
546 function setAction ($newAction) {
547 $GLOBALS['action'] = SQL_ESCAPE($newAction);
550 // Checks wether action is set and optionally aborts on miss
551 function isActionSet ($strict = false) {
553 $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
555 // Should we abort here?
556 if (($strict === true) && ($isset === false)) {
558 debug_report_bug('action is empty.');
565 // Getter for 'module' value
566 function getModule ($strict = true) {
571 if (isModuleSet($strict)) {
573 $module = $GLOBALS['module'];
580 // Setter for 'module' value
581 function setModule ($newModule) {
582 // Secure it and make all modules lower-case
583 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
586 // Checks wether module is set and optionally aborts on miss
587 function isModuleSet ($strict = false) {
589 $isset = (!empty($GLOBALS['module']));
591 // Should we abort here?
592 if (($strict === true) && ($isset === false)) {
594 debug_report_bug('module is empty.');
598 return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
601 // Getter for 'output_mode' value
602 function getOutputMode () {
607 if (isOutputModeSet(true)) {
609 $output_mode = $GLOBALS['output_mode'];
616 // Setter for 'output_mode' value
617 function setOutputMode ($newOutputMode) {
618 $GLOBALS['output_mode'] = (int) $newOutputMode;
621 // Checks wether output_mode is set and optionally aborts on miss
622 function isOutputModeSet ($strict = false) {
624 $isset = (isset($GLOBALS['output_mode']));
626 // Should we abort here?
627 if (($strict === true) && ($isset === false)) {
629 debug_report_bug('output_mode is empty.');
636 // Enables block-mode
637 function enableBlockMode ($enabled = true) {
638 $GLOBALS['block_mode'] = $enabled;
641 // Checks wether block-mode is enabled
642 function isBlockModeEnabled () {
644 if (!isset($GLOBALS['block_mode'])) {
646 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
650 return $GLOBALS['block_mode'];
653 // Wrapper function for addPointsThroughReferalSystem()
654 function addPointsDirectly ($subject, $userid, $points) {
656 unset($GLOBALS['ref_level']);
658 // Call more complicated method (due to more parameters)
659 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
662 // Wrapper function to redirect from member-only modules to index
663 function redirectToIndexMemberOnlyModule () {
664 // Do the redirect here
665 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
668 // Wrapper function for checking if extension is installed and newer or same version
669 function isExtensionInstalledAndNewer ($ext_name, $version) {
671 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
672 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
675 // Wrapper function for checking if extension is installed and older than given version
676 function isExtensionInstalledAndOlder ($ext_name, $version) {
678 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
679 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
683 function setUsername ($userName) {
684 $GLOBALS['username'] = (string) $userName;
688 function getUsername () {
690 $username = getMessage('USERNAME_GUEST');
693 if (isset($GLOBALS['username'])) {
695 $username = $GLOBALS['username'];
702 // Wrapper function for installation phase
703 function isInstallationPhase () {
705 if (!isset($GLOBALS['installation_phase'])) {
707 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
711 return $GLOBALS['installation_phase'];
714 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
715 function isDemoModeActive () {
716 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
719 // Wrapper function to redirect to de-refered URL
720 function redirectToDereferedUrl ($URL) {
722 $URL = generateDerefererUrl($URL);
728 // Getter for PHP caching value
729 function getPhpCaching () {
730 return $GLOBALS['php_caching'];
733 // Checks wether the admin hash is set
734 function isAdminHashSet ($admin) {
735 if (!isset($GLOBALS['cache_array']['admin'])) debug_report_bug('Cache not set.');
736 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
739 // Setter for admin hash
740 function setAdminHash ($admin, $hash) {
741 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
744 // Init user data array
745 function initUserData () {
746 // User id should not be zero
747 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
750 $GLOBALS['user_data'][getCurrentUserId()] = array();
753 // Getter for user data
754 function getUserData ($column) {
755 // User id should not be zero
756 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
759 return $GLOBALS['user_data'][getCurrentUserId()][$column];
762 // Geter for whole user data array
763 function getUserDataArray () {
764 // User id should not be zero
765 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
767 // Get the whole array
768 return $GLOBALS['user_data'][getCurrentUserId()];
771 // Checks if the user data is valid, this may indicate that the user has logged
772 // in, but you should use isMember() if you want to find that out.
773 function isUserDataValid () {
774 // User id should not be zero so abort here
775 if (!isCurrentUserIdSet()) return false;
777 // Is the array there and filled?
778 return ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
781 // Setter for current userid
782 function setCurrentUserId ($userid) {
783 $GLOBALS['current_userid'] = bigintval($userid);
786 // Getter for current userid
787 function getCurrentUserId () {
788 // Userid must be set before it can be used
789 if (!isCurrentUserIdSet()) {
791 debug_report_bug('User id is not set.');
795 return $GLOBALS['current_userid'];
798 // Checks if current userid is set
799 function isCurrentUserIdSet () {
800 return isset($GLOBALS['current_userid']);
803 // Checks wether we are debugging template cache
804 function isDebuggingTemplateCache () {
805 return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
808 // Wrapper for fetchUserData() and getUserData() calls
809 function getFetchedUserData ($keyColumn, $userId, $valueColumn) {
810 // Default is 'guest'
811 $data = getMessage('USERNAME_GUEST');
813 // Can we fetch the user data?
814 if (($userId > 0) && (fetchUserData($userId, $keyColumn))) {
815 // Now get the data back
816 $data = getUserData($valueColumn);