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['mxchange_installing'])) {
281 // Check URL (css.php/js.php need this)
282 $GLOBALS['mxchange_installing'] = isGetRequestParameterSet('installing');
286 return $GLOBALS['mxchange_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 () {
329 return ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
332 // Checks wether the reset mode is active
333 function isResetModeEnabled () {
334 // Now simply check it
335 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
338 // Checks wether the debug mode is enabled
339 function isDebugModeEnabled () {
341 return ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
344 // Checks wether SQL debugging is enabled
345 function isSqlDebuggingEnabled () {
346 return ((isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y'));
349 // Checks wether we shall debug regular expressions
350 function isDebugRegExpressionEnabled () {
352 return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
355 // Checks wether the cache instance is valid
356 function isCacheInstanceValid () {
357 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
360 // Copies a file from source to destination and verifies if that goes fine.
361 // This function should wrap the copy() command and make a nicer debug backtrace
362 // even if there is no xdebug extension installed.
363 function copyFileVerified ($source, $dest, $chmod = '') {
364 // Failed is the default
367 // Is the source file there?
368 if (!isFileReadable($source)) {
370 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
373 // Is the target directory there?
374 if (!isDirectory(dirname($dest))) {
376 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
379 // Now try to copy it
380 if (!copy($source, $dest)) {
381 // Something went wrong
382 debug_report_bug('copy() has failed to copy the file.');
385 $GLOBALS['file_readable'][$dest] = true;
388 // If there are chmod rights set, apply them
389 if (!empty($chmod)) {
391 $status = changeMode($dest, $chmod);
401 // Wrapper function for header()
402 // Send a header but checks before if we can do so
403 function sendHeader ($header) {
405 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
406 $GLOBALS['header'][] = trim($header);
409 // Flushes all headers
410 function flushHeaders () {
411 // Is the header already sent?
412 if (headers_sent()) {
414 debug_report_bug('Headers already sent!');
417 // Flush all headers if found
418 if ((isset($GLOBALS['header'])) && (is_array($GLOBALS['header']))) {
419 foreach ($GLOBALS['header'] as $header) {
424 // Mark them as flushed
425 $GLOBALS['header'] = array();
428 // Wrapper function for chmod()
429 // @TODO Do some more sanity check here
430 function changeMode ($FQFN, $mode) {
431 // Is the file/directory there?
432 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
433 // Neither, so abort here
434 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
441 // Wrapper for unlink()
442 function removeFile ($FQFN) {
443 // Is the file there?
444 if (isFileReadable($FQFN)) {
446 $GLOBALS['file_readable'][$FQFN] = false;
449 return unlink($FQFN);
452 // All fine if no file was removed. If we change this to 'false' or rewrite
453 // above if() block it would be to restrictive.
457 // Wrapper for $_POST['sel']
458 function countPostSelection ($element = 'sel') {
460 if (isPostRequestParameterSet($element)) {
461 // Return counted elements
462 return countSelection(postRequestParameter($element));
464 // Return zero if not found
469 // Checks wether the config-local.php is loaded
470 function isConfigLocalLoaded () {
471 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
474 // Checks wether a nickname or userid was entered and caches the result
475 function isNicknameUsed ($userid) {
479 // Is the cache there
480 if (isset($GLOBALS['is_nickname_used'][$userid])) {
482 $isUsed = $GLOBALS['is_nickname_used'][$userid];
485 $isUsed = (('' . round($userid) . '') != $userid);
487 // And write it to the cache
488 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
495 // Getter for 'what' value
496 function getWhat () {
501 if (isWhatSet(true)) {
503 $what = $GLOBALS['what'];
510 // Setter for 'what' value
511 function setWhat ($newWhat) {
512 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
515 // Setter for 'what' from configuration
516 function setWhatFromConfig ($configEntry) {
517 // Get 'what' from config
518 $what = getConfig($configEntry);
524 // Checks wether what is set and optionally aborts on miss
525 function isWhatSet ($strict = false) {
527 $isset = isset($GLOBALS['what']);
529 // Should we abort here?
530 if (($strict === true) && ($isset === false)) {
532 debug_report_bug('what is empty.');
539 // Getter for 'action' value
540 function getAction () {
545 if (isActionSet(true)) {
547 $action = $GLOBALS['action'];
554 // Setter for 'action' value
555 function setAction ($newAction) {
556 $GLOBALS['action'] = SQL_ESCAPE($newAction);
559 // Checks wether action is set and optionally aborts on miss
560 function isActionSet ($strict = false) {
562 $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
564 // Should we abort here?
565 if (($strict === true) && ($isset === false)) {
567 debug_report_bug('action is empty.');
574 // Getter for 'module' value
575 function getModule ($strict = true) {
580 if (isModuleSet($strict)) {
582 $module = $GLOBALS['module'];
589 // Setter for 'module' value
590 function setModule ($newModule) {
591 // Secure it and make all modules lower-case
592 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
595 // Checks wether module is set and optionally aborts on miss
596 function isModuleSet ($strict = false) {
598 $isset = (!empty($GLOBALS['module']));
600 // Should we abort here?
601 if (($strict === true) && ($isset === false)) {
603 debug_report_bug('module is empty.');
607 return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
610 // Getter for 'output_mode' value
611 function getOutputMode () {
616 if (isOutputModeSet(true)) {
618 $output_mode = $GLOBALS['output_mode'];
625 // Setter for 'output_mode' value
626 function setOutputMode ($newOutputMode) {
627 $GLOBALS['output_mode'] = (int) $newOutputMode;
630 // Checks wether output_mode is set and optionally aborts on miss
631 function isOutputModeSet ($strict = false) {
633 $isset = (isset($GLOBALS['output_mode']));
635 // Should we abort here?
636 if (($strict === true) && ($isset === false)) {
638 debug_report_bug('output_mode is empty.');
645 // Enables block-mode
646 function enableBlockMode ($enabled = true) {
647 $GLOBALS['block_mode'] = $enabled;
650 // Checks wether block-mode is enabled
651 function isBlockModeEnabled () {
653 if (!isset($GLOBALS['block_mode'])) {
655 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
659 return $GLOBALS['block_mode'];
662 // Wrapper function for addPointsThroughReferalSystem()
663 function addPointsDirectly ($subject, $userid, $points) {
665 unset($GLOBALS['ref_level']);
667 // Call more complicated method (due to more parameters)
668 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
671 // Wrapper function to redirect from member-only modules to index
672 function redirectToIndexMemberOnlyModule () {
673 // Do the redirect here
674 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
677 // Wrapper function for checking if extension is installed and newer or same version
678 function isExtensionInstalledAndNewer ($ext_name, $version) {
680 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
681 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
684 // Wrapper function for checking if extension is installed and older than given version
685 function isExtensionInstalledAndOlder ($ext_name, $version) {
687 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
688 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
692 function setUsername ($userName) {
693 $GLOBALS['username'] = (string) $userName;
697 function getUsername () {
699 $username = getMessage('USERNAME_GUEST');
702 if (isset($GLOBALS['username'])) {
704 $username = $GLOBALS['username'];
711 // Wrapper function for installation phase
712 function isInstallationPhase () {
714 if (!isset($GLOBALS['installation_phase'])) {
716 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
720 return $GLOBALS['installation_phase'];
723 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
724 function isDemoModeActive () {
725 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
728 // Wrapper function to redirect to de-refered URL
729 function redirectToDereferedUrl ($URL) {
731 $URL = generateDerefererUrl($URL);
737 // Getter for PHP caching value
738 function getPhpCaching () {
739 return $GLOBALS['php_caching'];
742 // Checks wether the admin hash is set
743 function isAdminHashSet ($admin) {
744 if (!isset($GLOBALS['cache_array']['admin'])) debug_report_bug('Cache not set.');
745 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
748 // Setter for admin hash
749 function setAdminHash ($admin, $hash) {
750 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
753 // Init user data array
754 function initUserData () {
755 // User id should not be zero
756 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
759 $GLOBALS['user_data'][getCurrentUserId()] = array();
762 // Getter for user data
763 function getUserData ($column) {
764 // User id should not be zero
765 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
768 return $GLOBALS['user_data'][getCurrentUserId()][$column];
771 // Geter for whole user data array
772 function getUserDataArray () {
773 // User id should not be zero
774 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
776 // Get the whole array
777 return $GLOBALS['user_data'][getCurrentUserId()];
780 // Checks if the user data is valid, this may indicate that the user has logged
781 // in, but you should use isMember() if you want to find that out.
782 function isUserDataValid () {
783 // User id should not be zero so abort here
784 if (!isCurrentUserIdSet()) return false;
786 // Is the array there and filled?
787 return ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
790 // Setter for current userid
791 function setCurrentUserId ($userid) {
792 $GLOBALS['current_userid'] = bigintval($userid);
795 // Getter for current userid
796 function getCurrentUserId () {
797 // Userid must be set before it can be used
798 if (!isCurrentUserIdSet()) {
800 debug_report_bug('User id is not set.');
804 return $GLOBALS['current_userid'];
807 // Checks if current userid is set
808 function isCurrentUserIdSet () {
809 return isset($GLOBALS['current_userid']);
812 // Checks wether we are debugging template cache
813 function isDebuggingTemplateCache () {
814 return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
817 // Wrapper for fetchUserData() and getUserData() calls
818 function getFetchedUserData ($keyColumn, $userId, $valueColumn) {
819 // Default is 'guest'
820 $data = getMessage('USERNAME_GUEST');
822 // Can we fetch the user data?
823 if (($userId > 0) && (fetchUserData($userId, $keyColumn))) {
824 // Now get the data back
825 $data = getUserData($valueColumn);