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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
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. *
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. *
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, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
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!');
54 if (!isset($GLOBALS['file_content'][$FQFN])) {
56 if (function_exists('file_get_contents')) {
58 $GLOBALS['file_content'][$FQFN] = file_get_contents($FQFN);
60 // Fall-back to implode-file chain
61 $GLOBALS['file_content'][$FQFN] = implode('', file($FQFN));
66 return $GLOBALS['file_content'][$FQFN];
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))) {
74 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
80 // By default all is failed...
83 // Is the function there?
84 if (function_exists('file_put_contents')) {
86 if ($aquireLock === true) {
87 // Write it directly with lock
88 $return = file_put_contents($FQFN, $content, LOCK_EX);
91 $return = file_put_contents($FQFN, $content);
94 // Write it with fopen
95 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
98 if ($aquireLock === true) flock($fp, LOCK_EX);
101 fwrite($fp, $content);
107 // Mark it as readable
108 $GLOBALS['file_readable'][$FQFN] = true;
110 // Remember content in cache
111 $GLOBALS['file_content'][$FQFN] = $content;
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 // 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');
145 // Return decoded string
146 return $decodedString;
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)));
163 // Merge all together
164 return array_merge($array1, $array2);
167 // Check if given FQFN is a readable file
168 function isFileReadable ($FQFN) {
170 if (!isset($GLOBALS['file_readable'][$FQFN])) {
172 $GLOBALS['file_readable'][$FQFN] = ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
175 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CHECK! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CACHE! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
182 return $GLOBALS['file_readable'][$FQFN];
185 // Checks wether the given FQFN is a directory and not ., .. or .svn
186 function isDirectory ($FQFN) {
188 if (!isset($GLOBALS['is_directory'][$FQFN])) {
190 $baseName = basename($FQFN);
193 $GLOBALS['is_directory'][$FQFN] = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
197 return $GLOBALS['is_directory'][$FQFN];
200 // "Getter" for remote IP number
201 function detectRemoteAddr () {
202 // Get remote ip from environment
203 $remoteAddr = determineRealRemoteAddress();
205 // Is removeip installed?
206 if (isExtensionActive('removeip')) {
208 $remoteAddr = getAnonymousRemoteAddress($remoteAddr);
215 // "Getter" for remote hostname
216 function detectRemoteHostname () {
217 // Get remote ip from environment
218 $remoteHost = getenv('REMOTE_HOST');
220 // Is removeip installed?
221 if (isExtensionActive('removeip')) {
223 $remoteHost = getAnonymousRemoteHost($remoteHost);
230 // "Getter" for user agent
231 function detectUserAgent ($alwaysReal = false) {
232 // Get remote ip from environment
233 $userAgent = getenv('HTTP_USER_AGENT');
235 // Is removeip installed?
236 if ((isExtensionActive('removeip')) && ($alwaysReal === false)) {
238 $userAgent = getAnonymousUserAgent($userAgent);
245 // "Getter" for referer
246 function detectReferer () {
247 // Get remote ip from environment
248 $referer = getenv('HTTP_REFERER');
250 // Is removeip installed?
251 if (isExtensionActive('removeip')) {
253 $referer = getAnonymousReferer($referer);
260 // "Getter" for request URI
261 function detectRequestUri () {
263 return (getenv('REQUEST_URI'));
266 // "Getter" for query string
267 function detectQueryString () {
268 return str_replace('&', '&', (getenv('QUERY_STRING')));
271 // "Getter" for SERVER_NAME
272 function detectServerName () {
274 return (getenv('SERVER_NAME'));
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');
286 return $GLOBALS['mailer_installing'];
289 // Check wether this script is installed
290 function isInstalled () {
292 if (!isset($GLOBALS['is_installed'])) {
293 // Determine wether this script is installed
294 $GLOBALS['is_installed'] = (
299 isConfigEntrySet('MXCHANGE_INSTALLED')
301 getConfig('MXCHANGE_INSTALLED') == 'Y'
305 // New config file found and loaded
306 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
309 // New config file found, but not yet read
310 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
313 // Only new config file is found
314 !isIncludeReadable('inc/config.php')
316 // Is installation mode
323 // Then use the cache
324 return $GLOBALS['is_installed'];
327 // Check wether an admin is registered
328 function isAdminRegistered () {
330 if (!isset($GLOBALS['is_admin_registered'])) {
332 $GLOBALS['is_admin_registered'] = ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
336 return $GLOBALS['is_admin_registered'];
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));
345 // Checks wether the debug mode is enabled
346 function isDebugModeEnabled () {
348 if (!isset($GLOBALS['is_debugmode_enabled'])) {
350 $GLOBALS['is_debugmode_enabled'] = ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
354 return $GLOBALS['is_debugmode_enabled'];
357 // Checks wether SQL debugging is enabled
358 function isSqlDebuggingEnabled () {
359 return ((isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y'));
362 // Checks wether we shall debug regular expressions
363 function isDebugRegExpressionEnabled () {
365 return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
368 // Checks wether the cache instance is valid
369 function isCacheInstanceValid () {
370 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
373 // Copies a file from source to destination and verifies if that goes fine.
374 // This function should wrap the copy() command and make a nicer debug backtrace
375 // even if there is no xdebug extension installed.
376 function copyFileVerified ($source, $dest, $chmod = '') {
377 // Failed is the default
380 // Is the source file there?
381 if (!isFileReadable($source)) {
383 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
386 // Is the target directory there?
387 if (!isDirectory(dirname($dest))) {
389 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
392 // Now try to copy it
393 if (!copy($source, $dest)) {
394 // Something went wrong
395 debug_report_bug('copy() has failed to copy the file.');
398 $GLOBALS['file_readable'][$dest] = true;
401 // If there are chmod rights set, apply them
402 if (!empty($chmod)) {
404 $status = changeMode($dest, $chmod);
414 // Wrapper function for header()
415 // Send a header but checks before if we can do so
416 function sendHeader ($header) {
418 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
419 $GLOBALS['header'][] = trim($header);
422 // Flushes all headers
423 function flushHeaders () {
424 // Is the header already sent?
425 if (headers_sent()) {
427 debug_report_bug('Headers already sent!');
430 // Flush all headers if found
431 if ((isset($GLOBALS['header'])) && (is_array($GLOBALS['header']))) {
432 foreach ($GLOBALS['header'] as $header) {
437 // Mark them as flushed
438 $GLOBALS['header'] = array();
441 // Wrapper function for chmod()
442 // @TODO Do some more sanity check here
443 function changeMode ($FQFN, $mode) {
444 // Is the file/directory there?
445 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
446 // Neither, so abort here
447 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
454 // Wrapper for unlink()
455 function removeFile ($FQFN) {
456 // Is the file there?
457 if (isFileReadable($FQFN)) {
459 $GLOBALS['file_readable'][$FQFN] = false;
462 return unlink($FQFN);
465 // All fine if no file was removed. If we change this to 'false' or rewrite
466 // above if() block it would be to restrictive.
470 // Wrapper for $_POST['sel']
471 function countPostSelection ($element = 'sel') {
473 if (isPostRequestParameterSet($element)) {
474 // Return counted elements
475 return countSelection(postRequestParameter($element));
477 // Return zero if not found
482 // Checks wether the config-local.php is loaded
483 function isConfigLocalLoaded () {
484 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
487 // Checks wether a nickname or userid was entered and caches the result
488 function isNicknameUsed ($userid) {
492 // Is the cache there
493 if (isset($GLOBALS['is_nickname_used'][$userid])) {
495 $isUsed = $GLOBALS['is_nickname_used'][$userid];
498 $isUsed = (('' . round($userid) . '') != $userid);
500 // And write it to the cache
501 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
508 // Getter for 'what' value
509 function getWhat () {
514 if (isWhatSet(true)) {
516 $what = $GLOBALS['what'];
523 // Setter for 'what' value
524 function setWhat ($newWhat) {
525 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
528 // Setter for 'what' from configuration
529 function setWhatFromConfig ($configEntry) {
530 // Get 'what' from config
531 $what = getConfig($configEntry);
537 // Checks wether what is set and optionally aborts on miss
538 function isWhatSet ($strict = false) {
540 $isset = isset($GLOBALS['what']);
542 // Should we abort here?
543 if (($strict === true) && ($isset === false)) {
545 debug_report_bug('what is empty.');
552 // Getter for 'action' value
553 function getAction () {
558 if (isActionSet(true)) {
560 $action = $GLOBALS['action'];
567 // Setter for 'action' value
568 function setAction ($newAction) {
569 $GLOBALS['action'] = SQL_ESCAPE($newAction);
572 // Checks wether action is set and optionally aborts on miss
573 function isActionSet ($strict = false) {
575 $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
577 // Should we abort here?
578 if (($strict === true) && ($isset === false)) {
580 debug_report_bug('action is empty.');
587 // Getter for 'module' value
588 function getModule ($strict = true) {
593 if (isModuleSet($strict)) {
595 $module = $GLOBALS['module'];
602 // Setter for 'module' value
603 function setModule ($newModule) {
604 // Secure it and make all modules lower-case
605 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
608 // Checks wether module is set and optionally aborts on miss
609 function isModuleSet ($strict = false) {
611 $isset = (!empty($GLOBALS['module']));
613 // Should we abort here?
614 if (($strict === true) && ($isset === false)) {
616 debug_report_bug('module is empty.');
620 return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
623 // Getter for 'output_mode' value
624 function getOutputMode () {
629 if (isOutputModeSet(true)) {
631 $output_mode = $GLOBALS['output_mode'];
638 // Setter for 'output_mode' value
639 function setOutputMode ($newOutputMode) {
640 $GLOBALS['output_mode'] = (int) $newOutputMode;
643 // Checks wether output_mode is set and optionally aborts on miss
644 function isOutputModeSet ($strict = false) {
646 $isset = (isset($GLOBALS['output_mode']));
648 // Should we abort here?
649 if (($strict === true) && ($isset === false)) {
651 debug_report_bug('output_mode is empty.');
658 // Enables block-mode
659 function enableBlockMode ($enabled = true) {
660 $GLOBALS['block_mode'] = $enabled;
663 // Checks wether block-mode is enabled
664 function isBlockModeEnabled () {
666 if (!isset($GLOBALS['block_mode'])) {
668 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
672 return $GLOBALS['block_mode'];
675 // Wrapper function for addPointsThroughReferalSystem()
676 function addPointsDirectly ($subject, $userid, $points) {
678 unset($GLOBALS['ref_level']);
680 // Call more complicated method (due to more parameters)
681 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
684 // Wrapper function to redirect from member-only modules to index
685 function redirectToIndexMemberOnlyModule () {
686 // Do the redirect here
687 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
690 // Wrapper function to redirect to current URL
691 function redirectToRequestUri () {
692 redirectToUrl(basename(detectRequestUri()));
695 // Wrapper function to redirect to de-refered URL
696 function redirectToDereferedUrl ($URL) {
698 redirectToUrl(generateDerefererUrl($URL));
701 // Wrapper function for checking if extension is installed and newer or same version
702 function isExtensionInstalledAndNewer ($ext_name, $version) {
704 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
705 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
708 // Wrapper function for checking if extension is installed and older than given version
709 function isExtensionInstalledAndOlder ($ext_name, $version) {
711 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
712 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
716 function setUsername ($userName) {
717 $GLOBALS['username'] = (string) $userName;
721 function getUsername () {
723 if (!isset($GLOBALS['username'])) {
724 // No, so it has to be a guest
725 $GLOBALS['username'] = getMessage('USERNAME_GUEST');
729 return $GLOBALS['username'];
732 // Wrapper function for installation phase
733 function isInstallationPhase () {
735 if (!isset($GLOBALS['installation_phase'])) {
737 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
741 return $GLOBALS['installation_phase'];
744 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
745 function isDemoModeActive () {
746 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
749 // Getter for PHP caching value
750 function getPhpCaching () {
751 return $GLOBALS['php_caching'];
754 // Checks wether the admin hash is set
755 function isAdminHashSet ($admin) {
757 * @TODO Do we really need this check? If yes, try to fix this:
758 * 1.:functions.php:2504, debug_get_mailable_backtrace(0)
759 * 2.:wrapper-functions.php:744, debug_report_bug(1)
760 * 3.:mysql-manager.php:728, isAdminHashSet(1)
761 * 4.:filters.php:384, isAdmin(0)
762 * 5.:debug_get_mailable_backtrace:2457, FILTER_DETERMINE_USERNAME(1)
763 * 6.:filter-functions.php:280, call_user_func_array(2)
764 * 7.:load_cache.php:74, runFilterChain(1)
765 * 8.:inc-functions.php:131, include(1)
766 * 9.:inc-functions.php:145, loadInclude(1)
767 * 10.:mysql-connect.php:104, loadIncludeOnce(1)
768 * 11.:inc-functions.php:131, include(1)
769 * 12.:inc-functions.php:145, loadInclude(1)
770 * 13.:config-global.php:106, loadIncludeOnce(1)
771 * 14.:js.php:57, require(1)
773 if (!isset($GLOBALS['cache_array']['admin'])) {
774 debug_report_bug('Cache not set.');
777 // Check for admin hash
778 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
781 // Setter for admin hash
782 function setAdminHash ($admin, $hash) {
783 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
786 // Init user data array
787 function initUserData () {
788 // User id should not be zero
789 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
792 $GLOBALS['user_data'][getCurrentUserId()] = array();
795 // Getter for user data
796 function getUserData ($column) {
797 // User id should not be zero
798 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
801 return $GLOBALS['user_data'][getCurrentUserId()][$column];
804 // Geter for whole user data array
805 function getUserDataArray () {
807 $uid = getCurrentUserId();
809 // User id should not be zero
810 if ($uid < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
812 // Get the whole array if found
813 if (isset($GLOBALS['user_data'][$uid])) {
814 // Found, so return it
815 return $GLOBALS['user_data'][$uid];
817 // Return empty array
822 // Checks if the user data is valid, this may indicate that the user has logged
823 // in, but you should use isMember() if you want to find that out.
824 function isUserDataValid () {
825 // User id should not be zero so abort here
826 if (!isCurrentUserIdSet()) return false;
829 if (!isset($GLOBALS['is_userdata_valid'][getCurrentUserId()])) {
831 $GLOBALS['is_userdata_valid'][getCurrentUserId()] = ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
835 return $GLOBALS['is_userdata_valid'][getCurrentUserId()];
838 // Setter for current userid
839 function setCurrentUserId ($userid) {
840 $GLOBALS['current_userid'] = bigintval($userid);
843 // Getter for current userid
844 function getCurrentUserId () {
845 // Userid must be set before it can be used
846 if (!isCurrentUserIdSet()) {
848 debug_report_bug('User id is not set.');
852 return $GLOBALS['current_userid'];
855 // Checks if current userid is set
856 function isCurrentUserIdSet () {
857 return isset($GLOBALS['current_userid']);
860 // Checks wether we are debugging template cache
861 function isDebuggingTemplateCache () {
862 return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
865 // Wrapper for fetchUserData() and getUserData() calls
866 function getFetchedUserData ($keyColumn, $userId, $valueColumn) {
868 if (!isset($GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn])) {
869 // Default is 'guest'
870 $data = getMessage('USERNAME_GUEST');
872 // Can we fetch the user data?
873 if (($userId > 0) && (fetchUserData($userId, $keyColumn))) {
874 // Now get the data back
875 $data = getUserData($valueColumn);
879 $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn] = $data;
883 return $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn];
886 // Wrapper for strpos() to ease porting from deprecated ereg() function
887 function isInString ($needle, $haystack) {
888 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'needle=' . $needle . ', haystack=' . $haystack . ', returned=' . intval(strpos($haystack, $needle) !== false));
889 return (strpos($haystack, $needle) !== false);
892 // Wrapper for strpos() to ease porting from deprecated eregi() function
893 // This function is case-insensitive
894 function isInStringIgnoreCase ($needle, $haystack) {
895 return (isInString(strtolower($needle), strtolower($haystack)));
898 // Wrapper to check for if fatal errors where detected
899 function ifFatalErrorsDetected () {
900 // Just call the inner function
901 return (getTotalFatalErrors() > 0);