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, $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 // 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)));
176 return $GLOBALS['file_readable'][$FQFN];
179 // Checks wether the given FQFN is a directory and not ., .. or .svn
180 function isDirectory ($FQFN) {
182 if (!isset($GLOBALS['is_directory'][$FQFN])) {
184 $baseName = basename($FQFN);
187 $GLOBALS['is_directory'][$FQFN] = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != '.svn'));
191 return $GLOBALS['is_directory'][$FQFN];
194 // "Getter" for remote IP number
195 function detectRemoteAddr () {
196 // Get remote ip from environment
197 $remoteAddr = determineRealRemoteAddress();
199 // Is removeip installed?
200 if (isExtensionActive('removeip')) {
202 $remoteAddr = getAnonymousRemoteAddress($remoteAddr);
209 // "Getter" for remote hostname
210 function detectRemoteHostname () {
211 // Get remote ip from environment
212 $remoteHost = getenv('REMOTE_HOST');
214 // Is removeip installed?
215 if (isExtensionActive('removeip')) {
217 $remoteHost = getAnonymousRemoteHost($remoteHost);
224 // "Getter" for user agent
225 function detectUserAgent ($alwaysReal = false) {
226 // Get remote ip from environment
227 $userAgent = getenv('HTTP_USER_AGENT');
229 // Is removeip installed?
230 if ((isExtensionActive('removeip')) && ($alwaysReal === false)) {
232 $userAgent = getAnonymousUserAgent($userAgent);
239 // "Getter" for referer
240 function detectReferer () {
241 // Get remote ip from environment
242 $referer = getenv('HTTP_REFERER');
244 // Is removeip installed?
245 if (isExtensionActive('removeip')) {
247 $referer = getAnonymousReferer($referer);
254 // "Getter" for request URI
255 function detectRequestUri () {
257 return (getenv('REQUEST_URI'));
260 // "Getter" for query string
261 function detectQueryString () {
262 return str_replace('&', '&', (getenv('QUERY_STRING')));
265 // Check wether we are installing
266 function isInstalling () {
267 // Determine wether we are installing
268 if (!isset($GLOBALS['mxchange_installing'])) {
269 // Check URL (css.php/js.php need this)
270 $GLOBALS['mxchange_installing'] = isGetRequestParameterSet('installing');
274 return $GLOBALS['mxchange_installing'];
277 // Check wether this script is installed
278 function isInstalled () {
280 if (!isset($GLOBALS['is_installed'])) {
281 // Determine wether this script is installed
282 $GLOBALS['is_installed'] = (
287 isConfigEntrySet('MXCHANGE_INSTALLED')
289 getConfig('MXCHANGE_INSTALLED') == 'Y'
293 // New config file found and loaded
294 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
297 // New config file found, but not yet read
298 isIncludeReadable(getConfig('CACHE_PATH') . 'config-local.php')
301 // Only new config file is found
302 !isIncludeReadable('inc/config.php')
304 // Is installation mode
311 // Then use the cache
312 return $GLOBALS['is_installed'];
315 // Check wether an admin is registered
316 function isAdminRegistered () {
317 return ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
320 // Checks wether the reset mode is active
321 function isResetModeEnabled () {
322 // Now simply check it
323 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
326 // Checks wether the debug mode is enabled
327 function isDebugModeEnabled () {
329 return ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
332 // Checks wether we shall debug regular expressions
333 function isDebugRegExpressionEnabled () {
335 return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
338 // Checks wether the cache instance is valid
339 function isCacheInstanceValid () {
340 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
343 // Copies a file from source to destination and verifies if that goes fine.
344 // This function should wrap the copy() command and make a nicer debug backtrace
345 // even if there is no xdebug extension installed.
346 function copyFileVerified ($source, $dest, $chmod = '') {
347 // Failed is the default
350 // Is the source file there?
351 if (!isFileReadable($source)) {
353 debug_report_bug('Cannot read from source file ' . basename($source) . '.');
356 // Is the target directory there?
357 if (!isDirectory(dirname($dest))) {
359 debug_report_bug('Cannot find directory ' . str_replace(getConfig('PATH'), '', dirname($dest)) . '.');
362 // Now try to copy it
363 if (!copy($source, $dest)) {
364 // Something went wrong
365 debug_report_bug('copy() has failed to copy the file.');
368 $GLOBALS['file_readable'][$dest] = true;
371 // If there are chmod rights set, apply them
372 if (!empty($chmod)) {
374 $status = changeMode($dest, $chmod);
384 // Wrapper function for header()
385 // Send a header but checks before if we can do so
386 function sendHeader ($header) {
388 $GLOBALS['header'][] = trim($header);
391 // Flushes all headers
392 function flushHeaders () {
393 // Is the header already sent?
394 if (headers_sent()) {
396 debug_report_bug('Headers already sent!');
400 foreach ($GLOBALS['header'] as $header) {
404 // Mark them as flushed
405 $GLOBALS['header'] = array();
408 // Wrapper function for chmod()
409 // @TODO Do some more sanity check here
410 function changeMode ($FQFN, $mode) {
411 // Is the file/directory there?
412 if ((!isFileReadable($FQFN)) && (!isDirectory($FQFN))) {
413 // Neither, so abort here
414 debug_report_bug('Cannot chmod() on ' . basename($FQFN) . '.');
421 // Wrapper for unlink()
422 function removeFile ($FQFN) {
423 // Is the file there?
424 if (isFileReadable($FQFN)) {
426 $GLOBALS['file_readable'][$FQFN] = false;
429 return unlink($FQFN);
432 // All fine if no file was removed. If we change this to 'false' or rewrite
433 // above if() block it would be to restrictive.
437 // Wrapper for $_POST['sel']
438 function countPostSelection ($element = 'sel') {
440 if (isPostRequestParameterSet($element)) {
441 // Return counted elements
442 return countSelection(postRequestParameter($element));
444 // Return zero if not found
449 // Checks wether the config-local.php is loaded
450 function isConfigLocalLoaded () {
451 return ((isset($GLOBALS['config_local_loaded'])) && ($GLOBALS['config_local_loaded'] === true));
454 // Checks wether a nickname or userid was entered and caches the result
455 function isNicknameUsed ($userid) {
459 // Is the cache there
460 if (isset($GLOBALS['is_nickname_used'][$userid])) {
462 $isUsed = $GLOBALS['is_nickname_used'][$userid];
465 $isUsed = (('' . round($userid) . '') != $userid);
467 // And write it to the cache
468 $GLOBALS['is_nickname_used'][$userid] = $isUsed;
475 // Getter for 'what' value
476 function getWhat () {
481 if (isWhatSet(true)) {
483 $what = $GLOBALS['what'];
490 // Setter for 'what' value
491 function setWhat ($newWhat) {
492 $GLOBALS['what'] = SQL_ESCAPE($newWhat);
495 // Setter for 'what' from configuration
496 function setWhatFromConfig ($configEntry) {
497 // Get 'what' from config
498 $what = getConfig($configEntry);
504 // Checks wether what is set and optionally aborts on miss
505 function isWhatSet ($strict = false) {
507 $isset = (isset($GLOBALS['what']));
509 // Should we abort here?
510 if (($strict === true) && ($isset === false)) {
512 debug_report_bug('what is empty.');
519 // Getter for 'action' value
520 function getAction () {
525 if (isActionSet(true)) {
527 $action = $GLOBALS['action'];
534 // Setter for 'action' value
535 function setAction ($newAction) {
536 $GLOBALS['action'] = SQL_ESCAPE($newAction);
539 // Checks wether action is set and optionally aborts on miss
540 function isActionSet ($strict = false) {
542 $isset = (isset($GLOBALS['action']));
544 // Should we abort here?
545 if (($strict === true) && ($isset === false)) {
547 debug_report_bug('action is empty.');
554 // Getter for 'module' value
555 function getModule ($strict = true) {
560 if (isModuleSet($strict)) {
562 $module = $GLOBALS['module'];
569 // Setter for 'module' value
570 function setModule ($newModule) {
571 // Secure it and make all modules lower-case
572 $GLOBALS['module'] = SQL_ESCAPE(strtolower($newModule));
575 // Checks wether module is set and optionally aborts on miss
576 function isModuleSet ($strict = false) {
578 $isset = (!empty($GLOBALS['module']));
580 // Should we abort here?
581 if (($strict === true) && ($isset === false)) {
583 debug_report_bug('module is empty.');
587 return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
590 // Getter for 'output_mode' value
591 function getOutputMode () {
596 if (isOutputModeSet(true)) {
598 $output_mode = $GLOBALS['output_mode'];
605 // Setter for 'output_mode' value
606 function setOutputMode ($newOutputMode) {
607 $GLOBALS['output_mode'] = (int) $newOutputMode;
610 // Checks wether output_mode is set and optionally aborts on miss
611 function isOutputModeSet ($strict = false) {
613 $isset = (isset($GLOBALS['output_mode']));
615 // Should we abort here?
616 if (($strict === true) && ($isset === false)) {
618 debug_report_bug('output_mode is empty.');
625 // Enables block-mode
626 function enableBlockMode ($enabled = true) {
627 $GLOBALS['block_mode'] = $enabled;
630 // Checks wether block-mode is enabled
631 function isBlockModeEnabled () {
633 if (!isset($GLOBALS['block_mode'])) {
635 debug_report_bug(__FUNCTION__ . ': block_mode is not set.');
639 return $GLOBALS['block_mode'];
642 // Wrapper function for addPointsThroughReferalSystem()
643 function addPointsDirectly ($subject, $userid, $points) {
645 unset($GLOBALS['ref_level']);
647 // Call more complicated method (due to more parameters)
648 return addPointsThroughReferalSystem($subject, $userid, $points, false, 0, false, 'direct');
651 // Wrapper function to redirect from member-only modules to index
652 function redirectToIndexMemberOnlyModule () {
653 // Do the redirect here
654 redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
657 // Wrapper function for checking if extension is installed and newer or same version
658 function isExtensionInstalledAndNewer ($ext_name, $version) {
660 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=>'.$version.'<br />';
661 return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
664 // Wrapper function for checking if extension is installed and older than given version
665 function isExtensionInstalledAndOlder ($ext_name, $version) {
667 //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'<'.$version.'<br />';
668 return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
672 function setUsername ($userName) {
673 $GLOBALS['username'] = (string) $userName;
677 function getUsername () {
678 return $GLOBALS['username'];
681 // Wrapper function for installation phase
682 function isInstallationPhase () {
684 if (!isset($GLOBALS['installation_phase'])) {
686 $GLOBALS['installation_phase'] = ((!isInstalled()) || (isInstalling()));
690 return $GLOBALS['installation_phase'];
693 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
694 function isDemoModeActive () {
695 return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
698 // Wrapper function to redirect to de-refered URL
699 function redirectToDereferedUrl ($URL) {
701 $URL = generateDerefererUrl($URL);
707 // Getter for PHP caching value
708 function getPhpCaching () {
709 return $GLOBALS['php_caching'];
712 // Checks wether the admin hash is set
713 function isAdminHashSet ($admin) {
714 return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
717 // Setter for admin hash
718 function setAdminHash ($admin, $hash) {
719 $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
722 // Init user data array
723 function initUserData () {
724 // User id should not be zero
725 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
728 $GLOBALS['user_data'][getCurrentUserId()] = array();
731 // Getter for user data
732 function getUserData ($column) {
733 // User id should not be zero
734 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
737 return $GLOBALS['user_data'][getCurrentUserId()][$column];
740 // Geter for whole user data array
741 function getUserDataArray () {
742 // User id should not be zero
743 if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
745 // Get the whole array
746 return $GLOBALS['user_data'][getCurrentUserId()];
749 // Checks if the user data is valid, this may indicate that the user has logged
750 // in, but you should use isMember() if you want to find that out.
751 function isUserDataValid () {
752 // User id should not be zero so abort here
753 if (!isCurrentUserIdSet()) return false;
755 // Is the array there and filled?
756 return ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
759 // Setter for current userid
760 function setCurrentUserId ($userid) {
761 $GLOBALS['current_userid'] = bigintval($userid);
764 // Getter for current userid
765 function getCurrentUserId () {
766 // Userid must be set before it can be used
767 if (!isCurrentUserIdSet()) {
769 debug_report_bug('User id is not set.');
773 return $GLOBALS['current_userid'];
776 // Checks if current userid is set
777 function isCurrentUserIdSet () {
778 return isset($GLOBALS['current_userid']);
781 // Checks wether we are debugging template cache
782 function isDebuggingTemplateCache () {
783 return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
786 // Wrapper for fetchUserData() and getUserData() calls
787 function getFetchedUserData ($keyColumn, $userId, $valueColumn) {
788 // Default is 'guest'
789 $data = getMessage('USERNAME_GUEST');
791 // Can we fetch the user data?
792 if (($userId > 0) && (fetchUserData($userId, $keyColumn))) {
793 // Now get the data back
794 $data = getUserData($valueColumn);