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!');
410 // Flush all headers if found
411 if ((isset($GLOBALS['header'])) && (is_array($GLOBALS['header']))) {
412 foreach ($GLOBALS['header'] as $header) {
417 // Mark them as flushed
418 $GLOBALS['header'] = array();
421 // Wrapper function for chmod()
422 // @TODO Do some more sanity check here
423 function changeMode ($FQFN, $mode) {
424 // Is the file/directory there?
425 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
426 // Neither, so abort here
427 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
434 // Wrapper for unlink()
435 function removeFile ($FQFN) {
436 // Is the file there?
437 if (isFileReadable($FQFN)) {
439 $GLOBALS['file_readable'][$FQFN] = false;
442 return unlink($FQFN);
445 // All fine if no file was removed. If we change this to 'false' or rewrite
446 // above if() block it would be to restrictive.
450 // Wrapper for $_POST['sel']
451 function countPostSelection ($element = 'sel') {
453 if (isPostRequestParameterSet($element)) {
454 // Return counted elements
455 return countSelection(postRequestParameter($element));
457 // Return zero if not found
462 // Checks wether the config-local.php is loaded
463 function isConfigLocalLoaded () {
464 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
467 // Checks wether a nickname or userid was entered and caches the result
468 function isNicknameUsed ($userid) {
472 // Is the cache there
473 if (isset($GLOBALS['is_nickname_used'][$userid])) {
475 $isUsed = $GLOBALS['is_nickname_used'][$userid];
478 $isUsed = (('' . round($userid) . '') != $userid);
480 // And write it to the cache
481 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
488 // Getter for 'what' value
489 function getWhat () {
494 if (isWhatSet(true)) {
496 $what = $GLOBALS['what'];
503 // Setter for 'what' value
504 function setWhat ($newWhat) {
505 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
508 // Setter for 'what' from configuration
509 function setWhatFromConfig ($configEntry) {
510 // Get 'what' from config
511 $what = getConfig($configEntry);
517 // Checks wether what is set and optionally aborts on miss
518 function isWhatSet ($strict = false) {
520 $isset = isset($GLOBALS['what']);
522 // Should we abort here?
523 if (($strict === true) && ($isset === false)) {
525 debug_report_bug('what is empty.');
532 // Getter for 'action' value
533 function getAction () {
538 if (isActionSet(true)) {
540 $action = $GLOBALS['action'];
547 // Setter for 'action' value
548 function setAction ($newAction) {
549 $GLOBALS['action'] = SQL_ESCAPE($newAction);
552 // Checks wether action is set and optionally aborts on miss
553 function isActionSet ($strict = false) {
555 $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
557 // Should we abort here?
558 if (($strict === true) && ($isset === false)) {
560 debug_report_bug('action is empty.');
567 // Getter for 'module' value
568 function getModule ($strict = true) {
573 if (isModuleSet($strict)) {
575 $module = $GLOBALS['module'];
582 // Setter for 'module' value
583 function setModule ($newModule) {
584 // Secure it and make all modules lower-case
585 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
588 // Checks wether module is set and optionally aborts on miss
589 function isModuleSet ($strict = false) {
591 $isset = (!empty($GLOBALS['module']));
593 // Should we abort here?
594 if (($strict === true) && ($isset === false)) {
596 debug_report_bug('module is empty.');
600 return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
603 // Getter for 'output_mode' value
604 function getOutputMode () {
609 if (isOutputModeSet(true)) {
611 $output_mode = $GLOBALS['output_mode'];
618 // Setter for 'output_mode' value
619 function setOutputMode ($newOutputMode) {
620 $GLOBALS['output_mode'] = (int) $newOutputMode;
623 // Checks wether output_mode is set and optionally aborts on miss
624 function isOutputModeSet ($strict = false) {
626 $isset = (isset($GLOBALS['output_mode']));
628 // Should we abort here?
629 if (($strict === true) && ($isset === false)) {
631 debug_report_bug('output_mode is empty.');
638 // Enables block-mode
639 function enableBlockMode ($enabled = true) {
640 $GLOBALS['block_mode'] = $enabled;
643 // Checks wether block-mode is enabled
644 function isBlockModeEnabled () {
646 if (!isset($GLOBALS['block_mode'])) {
648 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
652 return $GLOBALS['block_mode'];
655 // Wrapper function for addPointsThroughReferalSystem()
656 function addPointsDirectly ($subject, $userid, $points) {
658 unset($GLOBALS['ref_level']);
660 // Call more complicated method (due to more parameters)
661 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
664 // Wrapper function to redirect from member-only modules to index
665 function redirectToIndexMemberOnlyModule () {
666 // Do the redirect here
667 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
670 // Wrapper function for checking if extension is installed and newer or same version
671 function isExtensionInstalledAndNewer ($ext_name, $version) {
673 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
674 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
677 // Wrapper function for checking if extension is installed and older than given version
678 function isExtensionInstalledAndOlder ($ext_name, $version) {
680 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
681 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
685 function setUsername ($userName) {
686 $GLOBALS['username'] = (string) $userName;
690 function getUsername () {
692 $username = getMessage('USERNAME_GUEST');
695 if (isset($GLOBALS['username'])) {
697 $username = $GLOBALS['username'];
704 // Wrapper function for installation phase
705 function isInstallationPhase () {
707 if (!isset($GLOBALS['installation_phase'])) {
709 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
713 return $GLOBALS['installation_phase'];
716 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
717 function isDemoModeActive () {
718 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
721 // Wrapper function to redirect to de-refered URL
722 function redirectToDereferedUrl ($URL) {
724 $URL = generateDerefererUrl($URL);
730 // Getter for PHP caching value
731 function getPhpCaching () {
732 return $GLOBALS['php_caching'];
735 // Checks wether the admin hash is set
736 function isAdminHashSet ($admin) {
737 if (!isset($GLOBALS['cache_array']['admin'])) debug_report_bug('Cache not set.');
738 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
741 // Setter for admin hash
742 function setAdminHash ($admin, $hash) {
743 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
746 // Init user data array
747 function initUserData () {
748 // User id should not be zero
749 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
752 $GLOBALS['user_data'][getCurrentUserId()] = array();
755 // Getter for user data
756 function getUserData ($column) {
757 // User id should not be zero
758 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
761 return $GLOBALS['user_data'][getCurrentUserId()][$column];
764 // Geter for whole user data array
765 function getUserDataArray () {
766 // User id should not be zero
767 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
769 // Get the whole array
770 return $GLOBALS['user_data'][getCurrentUserId()];
773 // Checks if the user data is valid, this may indicate that the user has logged
774 // in, but you should use isMember() if you want to find that out.
775 function isUserDataValid () {
776 // User id should not be zero so abort here
777 if (!isCurrentUserIdSet()) return false;
779 // Is the array there and filled?
780 return ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
783 // Setter for current userid
784 function setCurrentUserId ($userid) {
785 $GLOBALS['current_userid'] = bigintval($userid);
788 // Getter for current userid
789 function getCurrentUserId () {
790 // Userid must be set before it can be used
791 if (!isCurrentUserIdSet()) {
793 debug_report_bug('User id is not set.');
797 return $GLOBALS['current_userid'];
800 // Checks if current userid is set
801 function isCurrentUserIdSet () {
802 return isset($GLOBALS['current_userid']);
805 // Checks wether we are debugging template cache
806 function isDebuggingTemplateCache () {
807 return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
810 // Wrapper for fetchUserData() and getUserData() calls
811 function getFetchedUserData ($keyColumn, $userId, $valueColumn) {
812 // Default is 'guest'
813 $data = getMessage('USERNAME_GUEST');
815 // Can we fetch the user data?
816 if (($userId > 0) && (fetchUserData($userId, $keyColumn))) {
817 // Now get the data back
818 $data = getUserData($valueColumn);