");
+ // Get theme from cookie
+ $ret = getSession('mxchange_theme');
- // Is this a valid reset file?
- //* DEBUG: */ print __FUNCTION__."(".__LINE__."):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile} \n";
- if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
- // Remove both for extension name
- $extName = substr($baseFile, strlen($prefix), -4);
+ // Is it valid?
+ if (getThemeId($ret) == 0) {
+ // Fix it to default
+ $ret = 'default';
+ } // END - if
+ } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
+ // Prepare FQFN for checking
+ $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
- // Try to find it
- $extId = GET_EXT_ID($extName);
+ // Installation mode active
+ if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
+ // Set cookie from URL data
+ setSession('mxchange_theme', REQUEST_GET('theme'));
+ } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+ // Set cookie from posted data
+ setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
+ }
- // Is the extension valid and active?
- if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
- // Then add this file
- $INCs[] = $file;
- } elseif ($extId == 0) {
- // Add non-extension files as well
- $INCs[] = $file;
- }
- } // END - if
- } // END - while
+ // Set return value
+ $ret = getSession('mxchange_theme');
+ } else {
+ // Invalid design, reset cookie
+ setSession('mxchange_theme', $ret);
+ }
- // Close directory
- closedir($dirPointer);
+ // Add (maybe) found theme.php file to inclusion list
+ $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
- // Sort array
- asort($INCs);
+ // Try to load the requested include file
+ if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
- // Return array with include files
- return $INCs;
+ // Return theme value
+ return $ret;
}
-// Load more reset scripts
-function RESET_ADD_INCLUDES () {
- // Is the reset set or old sql_patches?
- if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
+
+// Get id from theme
+function getThemeId ($name) {
+ // Is the extension 'theme' installed?
+ if (!EXT_IS_ACTIVE('theme')) {
// Then abort here
- return array();
+ return 0;
} // END - if
- // Get more daily reset scripts
- $INC_POOL = GET_DIR_AS_ARRAY(constant('PATH')."inc/reset/", "reset_");
+ // Default id
+ $id = 0;
- // Update database
- if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
+ // Is the cache entry there?
+ if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
+ // Get the version from cache
+ $id = $GLOBALS['cache_array']['themes']['id'][$name];
+
+ // Count up
+ incrementConfigEntry('cache_hits');
+ } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
+ // Check if current theme is already imported or not
+ $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
+ array($name), __FUNCTION__, __LINE__);
- // Create current week mark
- $currWeek = date("W", time());
+ // Entry found?
+ if (SQL_NUMROWS($result) == 1) {
+ // Fetch data
+ list($id) = SQL_FETCHROW($result);
+ } // END - if
- // Has it changed?
- if (getConfig('last_week') != $currWeek) {
- // Include weekly reset scripts
- $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(constant('PATH')."inc/weekly/", "weekly_"));
+ // Free result
+ SQL_FREERESULT($result);
+ }
- // Update config
- if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
- } // END - if
+ // Return id
+ return $id;
+}
- // Create current month mark
- $currMonth = date("m", time());
+// Generates an error code from given account status
+function generateErrorCodeFromUserStatus ($status) {
+ // Default error code if unknown account status
+ $errorCode = getCode('UNKNOWN_STATUS');
- // Has it changed?
- if (getConfig('last_month') != $currMonth) {
- // Include monthly reset scripts
- $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(constant('PATH')."inc/monthly/", "monthly_"));
+ // Generate constant name
+ $constantName = sprintf("ID_%s", $status);
- // Update config
- if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
- } // END - if
+ // Is the constant there?
+ if (isCodeSet($constantName)) {
+ // Then get it!
+ $errorCode = getCode($constantName);
+ } else {
+ // Unknown status
+ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
+ }
- // Return array
- return $INC_POOL;
+ // Return error code
+ return $errorCode;
+}
+
+// Function to search for the last modifified file
+function searchDirsRecursive ($dir, &$last_changed) {
+ // Get dir as array
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):dir=".$dir." \n";
+ // Does it match what we are looking for? (We skip a lot files already!)
+ // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
+ $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
+ $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):ds[]=".count($ds)." \n";
+
+ // Walk through all entries
+ foreach ($ds as $d) {
+ // Generate proper FQFN
+ $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
+
+ // Is it a file and readable?
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):FQFN={$FQFN} \n";
+ if (isDirectory($FQFN)) {
+ // $FQFN is a directory so also crawl into this directory
+ $newDir = $d;
+ if (!empty($dir)) $newDir = $dir . '/'. $d;
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):DESCENT: ".$newDir." \n";
+ searchDirsRecursive($newDir, $last_changed);
+ } elseif (isFileReadable($FQFN)) {
+ // $FQFN is a filename and no directory
+ $time = filemtime($FQFN);
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):File: ".$d." found. (".($last_changed['time'] - $time).") \n";
+ if ($last_changed['time'] < $time) {
+ // This file is newer as the file before
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__.") - NEWER! \n";
+ $last_changed['path_name'] = $FQFN;
+ $last_changed['time'] = $time;
+ } // END - if
+ }
+ } // END - foreach
}
-// Handle extra values
-function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
- // Default is the value itself
- $ret = $value;
- // Do we have a special filter function?
- if (!empty($filterFunction)) {
- // Does the filter function exist?
- if (function_exists($filterFunction)) {
- // Do we have extra parameters here?
- if (!empty($extraValue)) {
- // Put both parameters in one new array by default
- $args = array($value, $extraValue);
+// "Getter" for revision/version data
+function getActualVersion ($type = 'Revision') {
+ // By default nothing is new... ;-)
+ $new = false;
- // If we have an array simply use it and pre-extend it with our value
- if (is_array($extraValue)) {
- // Make the new args array
- $args = merge_array(array($value), $extraValue);
- } // END - if
+ if (EXT_IS_ACTIVE('cache')) {
+ // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
+ if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
+ if (!isset($GLOBALS['cache_array']['revision'][$type])
+ || count($GLOBALS['cache_array']['revision']) < 3
+ || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
- // Call the multi-parameter call-back
- $ret = call_user_func_array($filterFunction, $args);
- } else {
- // One parameter call
- $ret = call_user_func($filterFunction, $value);
- }
+ // Is the cache file outdated/invalid?
+ if ($new === true){
+ $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
+
+ // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
+ unset($GLOBALS['cache_array']['revision']);
+
+ // Reload load_cach-revison.php
+ loadInclude('inc/loader/load_cache-revision.php');
} // END - if
- } // END - if
- // Return the value
- return $ret;
-}
-// Check if given FQFN is a readable file
-function FILE_READABLE($fqfn) {
- // Check all...
- return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
-}
-// Converts timestamp selections into a timestamp
-function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
- // Init test variable
- $test2 = "";
+ // Return found value
+ return $GLOBALS['cache_array']['revision'][$type][0];
- // Get last three chars
- $test = substr($id, -3);
+ } else {
+ // Old Version without ext-cache active (deprecated ?)
- // Improved way of checking! :-)
- if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
- // Found a multi-selection for timings?
- $test = substr($id, 0, -3);
- if ((isset($POST[$test."_ye"])) && (isset($POST[$test."_mo"])) && (isset($POST[$test."_we"])) && (isset($POST[$test."_da"])) && (isset($POST[$test."_ho"])) && (isset($POST[$test."_mi"])) && (isset($POST[$test."_se"])) && ($test != $test2)) {
- // Generate timestamp
- $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
- $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
+ // FQFN of revision file
+ $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
- // Remove data from array
- foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
- unset($POST[$test."_".$rem]);
- } // END - foreach
+ // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
+ if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
+ // Has changed!
+ $new = true;
+ } else {
+ // Check for revision file
+ if (!isFileReadable($FQFN)) {
+ // Not found, so we need to create it
+ $new = true;
+ } else {
+ // Revision file found
+ $ins_vers = explode("\n", readFromFile($FQFN));
+
+ // Get array for mapping information
+ $mapper = array_flip(getSearchFor());
+ //* DEBUG: */ print("
");
+
+ // Is the content valid?
+ if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
+ // File needs update!
+ $new = true;
+ } else {
+ // Return found value
+ return trim($ins_vers[$mapper[$type]]);
+ }
+ }
+ }
- // Skip adding
- unset($id); $skip = true; $test2 = $test;
+ // Has it been updated?
+ if ($new === true) {
+ writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
} // END - if
- } else {
- // Process this entry
- $skip = false; $test2 = "";
}
}
-// Reverts the german decimal comma into Computer decimal dot
-function REVERT_COMMA ($str) {
- // Default float is not a float... ;-)
- $float = false;
-
- // Which language is selected?
- switch (GET_LANGUAGE()) {
- case "de": // German language
- // Remove german thousand dots first
- $str = str_replace(".", "", $str);
-
- // Replace german commata with decimal dot and cast it
- $float = (float)str_replace(",", ".", $str);
- break;
- default: // US and so on
- // Remove thousand dots first and cast
- $float = (float)str_replace(",", "", $str);
- break;
- }
+// Repares an array we are looking for
+// The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
+function getSearchFor () {
+ // Add Revision, Date, Tag and Author
+ $searchFor = array('Revision', 'Date', 'Tag', 'Author');
- // Return float
- return $float;
+ // Return the created array
+ return $searchFor;
}
-// Handle menu-depending failed logins and return the rendered content
-function HANDLE_LOGIN_FAILTURES ($accessLevel) {
- // Default output is empty ;-)
- $OUT = "";
+// @TODO Please describe this function
+function getArrayFromActualVersion () {
+ // Init variables
+ $next_dir = ''; // Directory to start with search
+ $last_changed = array(
+ 'path_name' => '',
+ 'time' => 0
+ );
+ $akt_vers = array(); // Init return array
+ $res = 0; // Init value for counting the founded keywords
- // Is the session data set?
- if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
- // Ignore zero values
- if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
- // Non-guest has login failures found, get both data and prepare it for template
- //* DEBUG: */ print __FUNCTION__."(".__LINE__."):accessLevel={$accessLevel} \n";
- $content = array(
- 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
- 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
- );
+ // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
+ searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
- // Load template
- $OUT = LOAD_TEMPLATE("login_failures", true, $content);
- } // END - if
+ // Get file
+ $last_file = readFromFile($last_changed['path_name']);
- // Reset session data
- set_session('mxchange_'.$accessLevel.'_failures', "");
- set_session('mxchange_'.$accessLevel.'_last_fail', "");
- } // END - if
+ // Get all the keywords to search for
+ $searchFor = getSearchFor();
- // Return rendered content
- return $OUT;
-}
+ // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
+ foreach ($searchFor as $search) {
+ // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
+ $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
+ // This trimms the search-result and puts it in the $akt_vers-return array
+ if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
+ } // END - foreach
-// Rebuild cache
-function REBUILD_CACHE ($cache, $inc="") {
- global $cacheInstance, $CSS;
+ // Save the last-changed filename for debugging
+ $akt_vers['File'] = $last_changed['path_name'];
- // Shall I remove the cache file?
- if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
- // Rebuild cache
- if ($cacheInstance->loadCacheFile($cache)) {
- // Destroy it
- $cacheInstance->destroyCacheFile();
- } // END - if
+ // at least 3 keyword-Tags are needed for propper values
+ if ($res && $res >= 3
+ && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
+ && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
+ && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
+ // Prepare content witch need special treadment
- // Include file given?
- if (!empty($inc)) {
- // Construct FQFN
- $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
+ // Prepare timestamp for date
+ preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
+ $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
- // Is the include there?
- if (INCLUDE_READABLE($INC)) {
- // And rebuild it from scratch
- //* DEBUG: */ print __FUNCTION__."(".__LINE__."): inc={$inc} - LOADED! \n";
- LOAD_INC($INC);
- } else {
- // Include not found!
- DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
- }
+ // Add author to the Tag if the author is set and is not quix0r (lead coder)
+ if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
+ $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
} // END - if
- } // END - if
-}
-// Purge admin menu cache
-function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
- global $cacheInstance;
+ } else {
+ // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
+ $version = sendGetRequest('check-updates3.php');
- // Is the cache extension enabled or no cache instance or admin menu cache disabled?
- if (!EXT_IS_ACTIVE("cache")) {
- // Cache extension not active
- return false;
- } elseif (!is_object($cacheInstance)) {
- // No cache instance!
- DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
- return false;
- } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
- // Caching disabled (currently experiemental!)
- return false;
+ // Prepare content
+ // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
+ if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
+ if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
+ if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
+ if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
}
- // Experiemental feature!
- debug_report_bug("Experimental feature: You have to delete the admin_*.cache files by yourself at this point.");
+ // Return prepared array
+ return $akt_vers;
}
-// Translates the "pool type" into human-readable
-function TRANSLATE_POOL_TYPE ($type) {
- // Default type is unknown
- $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
+// Back-ported from the new ship-simu engine. :-)
+function debug_get_printable_backtrace () {
+ // Init variable
+ $backtrace = "\n";
- // Generate constant
- $constName = sprintf("POOL_TYPE_%s", $type);
+ // Get and prepare backtrace for output
+ $backtraceArray = debug_backtrace();
+ foreach ($backtraceArray as $key => $trace) {
+ if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
+ if (!isset($trace['line'])) $trace['line'] = __LINE__;
+ if (!isset($trace['args'])) $trace['args'] = array();
+ $backtrace .= "
\n";
+ } // END - foreach
- // Does it exist?
- if (defined($constName)) {
- // Then use it
- $translated = getMessage($constName);
- } // END - if
+ // Close it
+ $backtrace .= "\n";
- // Return "translation"
- return $translated;
+ // Return the backtrace
+ return $backtrace;
}
-// "Getter" for remote IP number
-function GET_REMOTE_ADDR () {
- // Get remote ip from environment
- $remoteAddr = getenv('REMOTE_ADDR');
+// Output a debug backtrace to the user
+function debug_report_bug ($message = '') {
+ // Init message
+ $debug = '';
+ // Is the optional message set?
+ if (!empty($message)) {
+ // Use and log it
+ $debug = sprintf("Note: %s \n",
+ $message
+ );
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
+ // @TODO Add a little more infos here
+ DEBUG_LOG(__FUNCTION__, __LINE__, $message);
} // END - if
- // Return it
- return $remoteAddr;
-}
-// "Getter" for remote hostname
-function GET_REMOTE_HOST () {
- // Get remote ip from environment
- $remoteHost = getenv('REMOTE_HOST');
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
- } // END - if
+ // Add output
+ $debug .= "Please report this bug at bugs.mxchange.org:
\nRequest-URI: ".$_SERVER['REQUEST_URI']." \n";
+ $debug .= "Thank you for finding bugs.";
- // Return it
- return $remoteHost;
+ // And abort here
+ // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
+ die($debug);
}
-// "Getter" for user agent
-function GET_USER_AGENT () {
- // Get remote ip from environment
- $userAgent = getenv('HTTP_USER_AGENT');
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
- } // END - if
- // Return it
- return $userAgent;
+// Generates a ***weak*** seed (taken from de.php.net/mt_srand)
+function generateSeed () {
+ list($usec, $sec) = explode(" ", microtime());
+ return ((float)$sec + (float)$usec);
}
-// "Getter" for referer
-function GET_REFERER () {
- // Get remote ip from environment
- $referer = getenv('HTTP_REFERER');
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $referer = GET_ANONYMOUS_REFERER($referer);
- } // END - if
+// Converts a message code to a human-readable message
+function convertCodeToMessage ($code) {
+ $msg = '';
+ switch ($code) {
+ case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
+ case getCode('LOGOUT_FAILED') : $msg = "{--LOGOUT_FAILED--}"; break;
+ case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
+ case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
+ case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
+ case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
+ case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
+ case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+
+ case getCode('ERROR_MAILID'):
+ if (EXT_IS_ACTIVE($ext, true)) {
+ $msg = getMessage('ERROR_CONFIRMING_MAIL');
+ } else {
+ $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
+ }
+ break;
- // Return it
- return $referer;
-}
+ case getCode('EXTENSION_PROBLEM'):
+ if (REQUEST_ISSET_GET('ext')) {
+ $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET('ext'));
+ } else {
+ $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
+ }
+ break;
-// Adds a bonus mail to the queue
-// This is a high-level function!
-function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
- // Use mode from data if not set and availble ;-)
- if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
+ case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
+ case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
+ case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
+ case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
- // Generate receiver list
- $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
+ default:
+ // Missing/invalid code
+ $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
- // Receivers added?
- if (!empty($RECEIVER)) {
- // Add bonus mail to queue
- ADD_BONUS_MAIL_TO_QUEUE(
- $data['subject'],
- $data['text'],
- $RECEIVER,
- $data['points'],
- $data['seconds'],
- $data['url'],
- $data['cat'],
- $mode,
- $data['receiver']
- );
+ // Log it
+ DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
+ break;
+ } // END - switch
- // Mail inserted into bonus pool
- if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
- } elseif ($output) {
- // More entered than can be reached!
- LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
- } else {
- // Debug log
- DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
- }
+ // Return the message
+ return $msg;
}
-// Determines referal id and sets it
-function DETERMINE_REFID () {
- global $CLICK, $_SERVER;
+// Generate a "link" for the given admin id (aid)
+function generateAdminLink ($aid) {
+ // No assigned admin is default
+ $admin = "{--ADMIN_NO_ADMIN_ASSIGNED--}";
- // Check if refid is set
- if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
- // The variable user comes from the click-counter script click.php and we only accept this here
- $GLOBALS['refid'] = bigintval($_GET['user']);
- } elseif (!empty($_POST['refid'])) {
- // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
- } elseif (!empty($_GET['refid'])) {
- // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
- } elseif (!empty($_GET['ref'])) {
- // Set refid=ref (the referal link uses such variable)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
- } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
- // Set session refid als global
- $GLOBALS['refid'] = bigintval(get_session('refid'));
- } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
- // Set default refid as refid in URL
- $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
- } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
- // Select a random user which has confirmed enougth mails
- $GLOBALS['refid'] = SELECT_RANDOM_REFID();
- } else {
- // No default ID when sql_patches is not installed or none set
- $GLOBALS['refid'] = 0;
- }
+ // Zero? = Not assigned
+ if (bigintval($aid) > 0) {
+ // Load admin's login
+ $login = getAdminLogin($aid);
- // Set cookie when default refid > 0
- if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
- // Set cookie
- set_session('refid', $GLOBALS['refid']);
+ // Is the login valid?
+ if ($login != '***') {
+ // Is the extension there?
+ if (EXT_IS_ACTIVE('admins')) {
+ // Admin found
+ $admin = "".$login."";
+ } else {
+ // Extension not found
+ $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
+ }
+ } else {
+ // Maybe deleted?
+ $admin = "
".sprintf(getMessage('ADMIN_ID_404'), $aid)."
";
+ }
} // END - if
- // Return determined refid
- return $GLOBALS['refid'];
+ // Return result
+ return $admin;
}
-// Destroys the admin session
-function destroyAdminSession ($destroy = true) {
- // Kill maybe existing session variables including array elements
- set_session('admin_login', "");
- set_session('admin_md5' , "");
- set_session('admin_last' , "");
- set_session('admin_to' , "");
-
- // Destroy session and return status
- if ($destroy) {
- return session_destroy();
- } // END - if
-
- // All fine if we shall not really destroy the session
- return true;
-}
+// Compile characters which are allowed in URLs
+function compileUriCode ($code, $simple=true) {
+ // Compile constants
+ if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
-// Checks if a given apache module is loaded
-function IF_APACHE_MODULE_LOADED ($apacheModule) {
- // Check it and return result
- return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
-}
+ // Compile QUOT and other non-HTML codes
+ $code = str_replace('{DOT}', '.',
+ str_replace('{SLASH}', '/',
+ str_replace('{QUOT}', "'",
+ str_replace('{DOLLAR}', '$',
+ str_replace('{OPEN_ANCHOR}', '(',
+ str_replace('{CLOSE_ANCHOR}', ')',
+ str_replace('{OPEN_SQR}', '[',
+ str_replace('{CLOSE_SQR}', ']',
+ str_replace('{PER}', '%',
+ $code
+ )))))))));
-// Merges $_CONFIG with data in given array
-function mergeConfig ($newConfig) {
- global $_CONFIG;
- $_CONFIG = merge_array($_CONFIG, $newConfig);
+ // Return compiled code
+ return $code;
}
-// Getter for $_CONFIG entries
-function getConfig ($entry) {
- global $_CONFIG;
-
- // Default value
- $value = null;
-
- // Is the entry there?
- if (isConfigEntrySet($entry)) {
- // Then use it
- $value = $_CONFIG[$entry];
- } // END - if
+// Function taken from user comments on www.php.net / function eregi()
+function isUrlValidSimple ($url) {
+ // Prepare URL
+ $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
- // Return it
- return $value;
-}
+ // Allows http and https
+ $http = "(http|https)+(:\/\/)";
+ // Test domain
+ $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
+ // Test double-domains (e.g. .de.vu)
+ $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
+ // Test IP number
+ $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
+ // ... directory
+ $dir = "((/)+([-_\.[:alnum:]])+)*";
+ // ... page
+ $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
+ // ... and the string after and including question character
+ $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
+ // Pattern for URLs like http://url/dir/doc.html?var=value
+ $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
+ $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
+ $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
+ // Pattern for URLs like http://url/dir/?var=value
+ $pattern['d1dg1'] = $http.$domain1.$dir.'/'.$getstring1;
+ $pattern['d2dg1'] = $http.$domain2.$dir.'/'.$getstring1;
+ $pattern['ipdg1'] = $http.$ip.$dir.'/'.$getstring1;
+ // Pattern for URLs like http://url/dir/page.ext
+ $pattern['d1dp'] = $http.$domain1.$dir.$page;
+ $pattern['d1dp'] = $http.$domain2.$dir.$page;
+ $pattern['ipdp'] = $http.$ip.$dir.$page;
+ // Pattern for URLs like http://url/dir
+ $pattern['d1d'] = $http.$domain1.$dir;
+ $pattern['d2d'] = $http.$domain2.$dir;
+ $pattern['ipd'] = $http.$ip.$dir;
+ // Pattern for URLs like http://url/?var=value
+ $pattern['d1g1'] = $http.$domain1.'/'.$getstring1;
+ $pattern['d2g1'] = $http.$domain2.'/'.$getstring1;
+ $pattern['ipg1'] = $http.$ip.'/'.$getstring1;
+ // Pattern for URLs like http://url?var=value
+ $pattern['d1g12'] = $http.$domain1.$getstring1;
+ $pattern['d2g12'] = $http.$domain2.$getstring1;
+ $pattern['ipg12'] = $http.$ip.$getstring1;
+ // Test all patterns
+ $reg = false;
+ foreach ($pattern as $key=>$pat) {
+ // Debug regex?
+ if (defined('DEBUG_REGEX')) {
+ $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
+ $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
+ $pat = str_replace("[:digit:]", "0-9", $pat);
+ $pat = str_replace('.', "\.", $pat);
+ $pat = str_replace("@", "\@", $pat);
+ echo $key."= ".$pat." ";
+ }
-// Setter for $_CONFIG entries
-function setConfigEntry ($entry, $value) {
- global $_CONFIG;
+ // Check if expression matches
+ $reg = ($reg || preg_match(("^".$pat."^"), $url));
- // Secure the entry name
- $entry = SQL_ESCAPE($entry);
+ // Does it match?
+ if ($reg === true) break;
+ }
- // And set it
- $_CONFIG[$entry] = $value;
+ // Return true/false
+ return $reg;
}
-// Checks wether the given config entry is set
-function isConfigEntrySet ($entry) {
- global $_CONFIG;
- return (isset($_CONFIG[$entry]));
-}
+// Wtites data to a config.php-style file
+// @TODO Rewrite this function to use readFromFile() and writeToFile()
+function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
+ // Initialize some variables
+ $done = false;
+ $seek++;
+ $next = -1;
+ $found = false;
+
+ // Is the file there and read-/write-able?
+ if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
+ $search = "CFG: ".$comment;
+ $tmp = $FQFN.".tmp";
+
+ // Open the source file
+ $fp = fopen($FQFN, 'r') or OUTPUT_HTML("READ: ".$FQFN." ");
+
+ // Is the resource valid?
+ if (is_resource($fp)) {
+ // Open temporary file
+ $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("WRITE: ".$tmp." ");
+
+ // Is the resource again valid?
+ if (is_resource($fp_tmp)) {
+ while (!feof($fp)) {
+ // Read from source file
+ $line = fgets ($fp, 1024);
+
+ if (strpos($line, $search) > -1) { $next = 0; $found = true; }
+
+ if ($next > -1) {
+ if ($next === $seek) {
+ $next = -1;
+ $line = $prefix . $DATA . $suffix."\n";
+ } else {
+ $next++;
+ }
+ }
+
+ // Write to temp file
+ fputs($fp_tmp, $line);
+ }
-// Increment or init with given value or 1 as default the given config entry
-function incrementConfigEntry ($configEntry, $value=1) {
- global $_CONFIG;
+ // Close temp file
+ fclose($fp_tmp);
- // Increment it if set or init it with 1
- if (getConfig($configEntry) > 0) {
- $_CONFIG[$configEntry] += $value;
- } else {
- $_CONFIG[$configEntry] = $value;
- }
-}
+ // Finished writing tmp file
+ $done = true;
+ }
-// "Getter" for language strings
-// @TODO Rewrite all language constants to this function.
-function getMessage ($messageId) {
- // Default is not found!
- $return = "!".$messageId."!";
+ // Close source file
+ fclose($fp);
- // Is the language string found?
- if (isset($GLOBALS['msg'][strtolower($messageId)])) {
- // Language array element found in small_letters
- $return = $GLOBALS['msg'][$messageId];
- } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
- // @DEPRECATED Language array element found in BIG_LETTERS
- $return = $GLOBALS['msg'][$messageId];
- } elseif (defined($messageId)) {
- // @DEPRECATED Deprecated constant found
- $return = constant($messageId);
+ if (($done) && ($found)) {
+ // Copy back tmp file and delete tmp :-)
+ copy($tmp, $FQFN);
+ return unlink($tmp);
+ } elseif (!$found) {
+ OUTPUT_HTML("CHANGE: 404!");
+ } else {
+ OUTPUT_HTML("TMP: UNDONE!");
+ }
+ }
} else {
- // Missing language constant
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
+ // File not found, not readable or writeable
+ OUTPUT_HTML("404: ".$FQFN." ");
}
- // Return the string
- return $return;
+ // An error was detected!
+ return false;
}
-
-// Get current theme name
-function GET_CURR_THEME() {
- global $INC_POOL, $CSS, $cacheArray;
-
- // The default theme is 'default'... ;-)
- $ret = "default";
-
- // Load default theme if not empty from configuration
- if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
-
- if (!isSessionVariableSet('mxchange_theme')) {
- // Set default theme
- set_session('mxchange_theme', $ret);
- } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
- //die("
".print_r($cacheArray['themes'], true)."
");
- // Get theme from cookie
- $ret = get_session('mxchange_theme');
-
- // Is it valid?
- if (THEME_GET_ID($ret) == 0) {
- // Fix it to default
- $ret = "default";
- } // END - if
- } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
- // Prepare FQFN for checking
- $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_GET['theme']));
-
- // Installation mode active
- if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
- // Set cookie from URL data
- set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
- } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_POST['theme'])))) {
- // Set cookie from posted data
- set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
- }
-
- // Set return value
- $ret = get_session('mxchange_theme');
+// Send notification to admin
+function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
+ if (GET_EXT_VERSION('admins') >= '0.4.1') {
+ // Send new way
+ SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
} else {
- // Invalid design, reset cookie
- set_session('mxchange_theme', $ret);
+ // Send out out-dated way
+ $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
+ SEND_ADMIN_EMAILS($subject, $msg);
}
+}
- // Add (maybe) found theme.php file to inclusion list
- $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
-
- // Try to load the requested include file
- if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
+// Debug message logger
+function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
+ // Is debug mode enabled?
+ if ((isDebugModeEnabled()) || ($force === true)) {
+ // Remove CRLF
+ $message = str_replace("\r", '', str_replace("\n", '', $message));
- // Return theme value
- return $ret;
+ // Log this message away
+ $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
+ fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
+ fclose($fp);
+ } // END - if
}
-// Get id from theme
-function THEME_GET_ID ($name) {
- global $cacheArray;
-
- // Is the extension "theme" installed?
- if (!EXT_IS_ACTIVE("theme")) {
+// Load more reset scripts
+function runResetIncludes () {
+ // Is the reset set or old sql_patches?
+ if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
// Then abort here
- return 0;
+ DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
} // END - if
- // Default id
- $id = 0;
+ // Get more daily reset scripts
+ SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
- // Is the cache entry there?
- if (isset($cacheArray['themes']['id'][$name])) {
- // Get the version from cache
- $id = $cacheArray['themes']['id'][$name];
+ // Update database
+ if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
- // Count up
- incrementConfigEntry('cache_hits');
- } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
- // Check if current theme is already imported or not
- $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
- array($name), __FILE__, __LINE__);
+ // Is the config entry set?
+ if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
+ // Create current week mark
+ $currWeek = date('W', time());
- // Entry found?
- if (SQL_NUMROWS($result) == 1) {
- // Fetch data
- list($id) = SQL_FETCHROW($result);
- } // END - if
+ // Has it changed?
+ if (getConfig('last_week') != $currWeek) {
+ // Include weekly reset scripts
+ MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
- // Free result
- SQL_FREERESULT($result);
- }
+ // Update config
+ if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
+ } // END - if
- // Return id
- return $id;
-}
+ // Create current month mark
+ $currMonth = date('m', time());
-// Read a given file
-function READ_FILE ($FQFN, $sqlPrepare = false) {
- // Load the file
- if (function_exists('file_get_contents')) {
- // Use new function
- $content = file_get_contents($FQFN);
- } else {
- // Fall-back to implode-file chain
- $content = implode("", file($FQFN));
- }
+ // Has it changed?
+ if (getConfig('last_month') != $currMonth) {
+ // Include monthly reset scripts
+ MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
- // Prepare SQL queries?
- if ($sqlPrepare === true) {
- // Remove some unwanted chars
- $content = str_replace("\r", "", $content);
- $content = str_replace("\n\n", "\n", $content);
+ // Update config
+ if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
+ } // END - if
} // END - if
- // Return the content
- return $content;
+ // Run the filter
+ runFilterChain('load_includes');
}
-// Writes content to a file
-function WRITE_FILE ($FQFN, $content) {
- // Is the function there?
- if (function_exists('file_put_contents')) {
- // Write it directly
- file_put_contents($FQFN, $content);
- } else {
- // Write it with fopen
- $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
- fwrite($fp, $content);
- fclose($fp);
-
- // Set CHMOD rights
- chmod($FQFN, 0644);
- }
-}
+// Handle extra values
+function handleExtraValues ($filterFunction, $value, $extraValue) {
+ // Default is the value itself
+ $ret = $value;
-// Generates an error code from given account status
-function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
- // Default error code if unknown account status
- $ERROR = constant('CODE_UNKNOWN_STATUS');
+ // Do we have a special filter function?
+ if (!empty($filterFunction)) {
+ // Does the filter function exist?
+ if (function_exists($filterFunction)) {
+ // Do we have extra parameters here?
+ if (!empty($extraValue)) {
+ // Put both parameters in one new array by default
+ $args = array($value, $extraValue);
- // Generate constant name
- $constantName = sprintf("CODE_ID_%s", $status);
+ // If we have an array simply use it and pre-extend it with our value
+ if (is_array($extraValue)) {
+ // Make the new args array
+ $args = merge_array(array($value), $extraValue);
+ } // END - if
- // Is the constant there?
- if (defined($constantName)) {
- // Then get it!
- $ERROR = constant($constantName);
- } else {
- // Unknown status
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
- }
+ // Call the multi-parameter call-back
+ $ret = call_user_func_array($filterFunction, $args);
+ } else {
+ // One parameter call
+ $ret = call_user_func($filterFunction, $value);
+ }
+ } // END - if
+ } // END - if
- // Return error code
- return $ERROR;
+ // Return the value
+ return $ret;
}
-// Clears the output buffer. This function does *NOT* backup sent content.
-function clearOutputBuffer () {
- // Trigger an error on failure
- if (!ob_end_clean()) {
- // Failed!
- debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
- } // END - if
-}
+// Converts timestamp selections into a timestamp
+function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
+ // Init test variable
+ $test2 = '';
-// "Getter" for revision/version data
-function getActualVersion ($type = 0) {
- // By default nothing is new... ;-)
- $new = false;
+ // Get last three chars
+ $test = substr($id, -3);
- // FQFN of revision file
- $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
+ // Improved way of checking! :-)
+ if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
+ // Found a multi-selection for timings?
+ $test = substr($id, 0, -3);
+ if ((isset($POST[$test.'_ye'])) && (isset($POST[$test.'_mo'])) && (isset($POST[$test.'_we'])) && (isset($POST[$test.'_da'])) && (isset($POST[$test.'_ho'])) && (isset($POST[$test.'_mi'])) && (isset($POST[$test.'_se'])) && ($test != $test2)) {
+ // Generate timestamp
+ $POST[$test] = createTimestampFromSelections($test, $POST);
+ $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
- // Check for revision file
- if (!FILE_READABLE($FQFN)) {
- // Not found, so we need to create it
- $new = true;
- } else {
- // Revision file found
- $ins_vers = explode("\n", READ_FILE($FQFN));
+ // Remove data from array
+ foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
+ unset($POST[$test.'_'.$rem]);
+ } // END - foreach
- // Is the content valid?
- if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
- // File needs update!
- $new = true;
- } else {
- // Revision-File has valid Data and isn't 'new' so return the Rev-Number
- return trim($ins_vers[$type]);
- }
+ // Skip adding
+ unset($id); $skip = true; $test2 = $test;
+ } // END - if
+ } else {
+ // Process this entry
+ $skip = false;
+ $test2 = '';
}
+}
- // Has it been updated?
- if ($new === true) {
- // No Revision-File or has no valid Data so read the Revision from the Server.
- $version = GET_URL("check-updates3.php");
+// Reverts the german decimal comma into Computer decimal dot
+function convertCommaToDot ($str) {
+ // Default float is not a float... ;-)
+ $float = false;
- // Prepare content
- $akt_vers[] = trim($version[10]);
- $akt_vers[] = trim($version[9]);
- $akt_vers[] = trim($version[8]);
+ // Which language is selected?
+ switch (getLanguage()) {
+ case 'de': // German language
+ // Remove german thousand dots first
+ $str = str_replace('.', '', $str);
- // Write file
- WRITE_FILE($FQFN, implode("\n", $akt_vers));
+ // Replace german commata with decimal dot and cast it
+ $float = (float)str_replace(',', '.', $str);
+ break;
- // Return requested content
- return trim($akt_vers[$type]);
+ default: // US and so on
+ // Remove thousand dots first and cast
+ $float = (float)str_replace(',', '', $str);
+ break;
}
+
+ // Return float
+ return $float;
}
-// Loads an include file and logs any missing files for debug purposes
-function LOAD_INC ($INC) {
- // Get constant path
- $PATH = constant('PATH');
+// Handle menu-depending failed logins and return the rendered content
+function HANDLE_LOGIN_FAILTURES ($accessLevel) {
+ // Default output is empty ;-)
+ $OUT = '';
- // Use the include file name directly
- // @TODO Try to find all locations where an FQFN is given to these two
- // @TODO functions and avoid it.
- $FQFN = $INC;
+ // Is the session data set?
+ if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
+ // Ignore zero values
+ if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
+ // Non-guest has login failures found, get both data and prepare it for template
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."):accessLevel={$accessLevel} \n";
+ $content = array(
+ 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
+ 'last_failure' => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), '2')
+ );
- // Check if PATH is in $INC
- if (substr($INC, 0, $PATH) != $PATH) {
- // Add it. This is why we need a trailing slash in config.php
- $FQFN = $PATH . $INC;
- } // END - if
+ // Load template
+ $OUT = LOAD_TEMPLATE('login_failures', true, $content);
+ } // END - if
- // Is the include file there?
- if (!FILE_READABLE($FQFN)) {
- // Not there so log it
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
- return false;
+ // Reset session data
+ setSession('mxchange_'.$accessLevel.'_failures', '');
+ setSession('mxchange_'.$accessLevel.'_last_fail', '');
} // END - if
- // Try to load it
- require($FQFN);
+ // Return rendered content
+ return $OUT;
}
-// Loads an include file once
-function LOAD_INC_ONCE ($INC) {
- global $cacheArray;
+// Rebuild cache
+function rebuildCacheFiles ($cache, $inc = '') {
+ // Shall I remove the cache file?
+ if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
+ // Rebuild cache
+ if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
+ // Destroy it
+ $GLOBALS['cache_instance']->destroyCacheFile();
+ } // END - if
- // Is it not loaded?
- if (!isset($cacheArray['load_once'][$INC])) {
- // Then try to load it
- LOAD_INC($INC);
+ // Include file given?
+ if (!empty($inc)) {
+ // Construct FQFN
+ $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
- // And mark it as loaded
- $cacheArray['load_once'][$INC] = true;
+ // Is the include there?
+ if (isIncludeReadable($INC)) {
+ // And rebuild it from scratch
+ //* DEBUG: */ print __FUNCTION__."(".__LINE__."): inc={$inc} - LOADED! \n";
+ loadInclude($INC);
+ } else {
+ // Include not found!
+ DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
+ }
+ } // END - if
} // END - if
}
-// Back-ported from the new ship-simu engine. :-)
-function debug_get_printable_backtrace () {
- // Init variable
- $backtrace = "\n";
-
- // Get and prepare backtrace for output
- $backtraceArray = debug_backtrace();
- foreach ($backtraceArray as $key => $trace) {
- if (!isset($trace['file'])) $trace['file'] = __FILE__;
- if (!isset($trace['line'])) $trace['line'] = __LINE__;
- if (!isset($trace['args'])) $trace['args'] = array();
- $backtrace .= "
\n";
- } // END - foreach
-
- // Close it
- $backtrace .= "\n";
+// Purge admin menu cache
+function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
+ // Is the cache extension enabled or no cache instance or admin menu cache disabled?
+ if (!EXT_IS_ACTIVE('cache')) {
+ // Cache extension not active
+ return false;
+ } elseif (!isCacheInstanceValid()) {
+ // No cache instance!
+ DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
+ return false;
+ } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
+ // Caching disabled (currently experiemental!)
+ return false;
+ }
- // Return the backtrace
- return $backtrace;
+ // Experiemental feature!
+ debug_report_bug("Experimental feature: You have to delete the admin_*.cache files by yourself at this point.");
}
-// Output a debug backtrace to the user
-function debug_report_bug ($message = "") {
- // Init message
- $debug = "";
- // Is the optional message set?
- if (!empty($message)) {
- // Use and log it
- $debug = sprintf("Note: %s \n",
- $message
- );
+// Determines the real remote address
+function determineRealRemoteAddress () {
+ // Is a proxy in use?
+ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
+ // Proxy was used
+ $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
+ } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
+ // Yet, another proxy
+ $address = $_SERVER['HTTP_CLIENT_IP'];
+ } else {
+ // The regular address when no proxy was used
+ $address = $_SERVER['REMOTE_ADDR'];
+ }
- // @TODO Add a little more infos here
- DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+ // This strips out the real address from proxy output
+ if (strstr($address, ',')){
+ $addressArray = explode(',', $address);
+ $address = $addressArray[0];
} // END - if
- // Add output
- $debug .= ("Please report this error at bugs.mxchange.org:
Thank you for your help finding bugs.");
-
- // And abort here
- die($debug);
-}
-
-// Generates a ***weak*** seed (taken from de.php.net/mt_srand)
-function generateSeed () {
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$sec + (float)$usec);
+ // Return the result
+ return $address;
}
-// Converts a message code to a human-readable message
-function convertCodeToMessage ($code) {
- $msg = "";
- switch ($code) {
- case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
- case constant('CODE_LOGOUT_FAILED') : $msg = "{--LOGOUT_FAILED--}"; break;
- case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
- case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
- case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
- case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
- case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
- case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
-
- case constant('CODE_ERROR_MAILID'):
- if (EXT_IS_ACTIVE($ext, true)) {
- $msg = getMessage('ERROR_CONFIRMING_MAIL');
- } else {
- $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
- }
- break;
-
- case constant('CODE_EXTENSION_PROBLEM'):
- if (isset($_GET['ext'])) {
- $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), SQL_ESCAPE($_GET['ext']));
- } else {
- $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
- }
- break;
+// Adds a bonus mail to the queue
+// This is a high-level function!
+function addNewBonusMail ($data, $mode = '', $output=true) {
+ // Use mode from data if not set and availble ;-)
+ if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
- case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
- case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
- case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
- default : $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code); break;
- } // END - switch
+ // Generate receiver list
+ $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
- // Return the message
- return $msg;
-}
+ // Receivers added?
+ if (!empty($RECEIVER)) {
+ // Add bonus mail to queue
+ addBonusMailToQueue(
+ $data['subject'],
+ $data['text'],
+ $RECEIVER,
+ $data['points'],
+ $data['seconds'],
+ $data['url'],
+ $data['cat'],
+ $mode,
+ $data['receiver']
+ );
-// Checks wether the given extension is currently not installed
-// and redirects if so.
-function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
- // Is the extension uninstalled/inactive?
- if (!EXT_IS_ACTIVE($ext_name)) {
- // Redirect to index
- LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
- } // END - if
+ // Mail inserted into bonus pool
+ if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
+ } elseif ($output) {
+ // More entered than can be reached!
+ LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
+ } else {
+ // Debug log
+ DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
+ }
}
-// Generate a "link" for the given admin id (aid)
-function GENERATE_AID_LINK ($aid) {
- // No assigned admin is default
- $admin = "
{--ADMIN_NO_ADMIN_ASSIGNED--}
";
+// Determines referal id and sets it
+function DETERMINE_REFID () {
+ // Check if refid is set
+ if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
+ // The variable user comes from the click-counter script click.php and we only accept this here
+ $GLOBALS['refid'] = bigintval($_GET['user']);
+ } elseif (!empty($_POST['refid'])) {
+ // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
+ $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
+ } elseif (!empty($_GET['refid'])) {
+ // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
+ $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
+ } elseif (!empty($_GET['ref'])) {
+ // Set refid=ref (the referal link uses such variable)
+ $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
+ } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
+ // Set session refid als global
+ $GLOBALS['refid'] = bigintval(getSession('refid'));
+ } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
+ // Set default refid as refid in URL
+ $GLOBALS['refid'] = getConfig(('def_refid'));
+ } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
+ // Select a random user which has confirmed enougth mails
+ $GLOBALS['refid'] = determineRandomReferalId();
+ } else {
+ // No default ID when sql_patches is not installed or none set
+ $GLOBALS['refid'] = 0;
+ }
- // Zero? = Not assigned
- if ($aid == "0") {
- // Load admin's login
- $login = GET_ADMIN_LOGIN($aid);
- if ($login != "***") {
- // Is the extension there?
- if (EXT_IS_ACTIVE("admins")) {
- // Admin found
- $admin = "".$login."";
- } else {
- // Extension not found
- $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
- }
- } else {
- // Maybe deleted?
- $admin = "
".sprintf(getMessage('ADMIN_ID_404'), $aid)."
";
- }
+ // Set cookie when default refid > 0
+ if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
+ // Set cookie
+ setSession('refid', $GLOBALS['refid']);
} // END - if
- // Return result
- return $admin;
+ // Return determined refid
+ return $GLOBALS['refid'];
}
-// Checks wether an include file (non-FQFN better) is readable
-function INCLUDE_READABLE ($INC) {
- // Construct FQFN
- $FQFN = constant('PATH') . $INC;
+// Enables the reset mode. Only call this function if you really want the
+// reset to be run!
+function enableResetMode () {
+ // Enable the reset mode
+ $GLOBALS['reset_enabled'] = true;
- // Is it readable?
- return FILE_READABLE($FQFN);
+ // Run filters
+ runFilterChain('reset_enabled');
}
-// Encode strings
-// @TODO Implement $compress
-function encodeString ($str, $compress=true) {
- $str = urlencode(base64_encode(compileUriCode($str)));
- return $str;
+// Our shutdown-function
+function shutdown () {
+ // Call the filter chain 'shutdown'
+ runFilterChain('shutdown', null, false);
+
+ if (SQL_IS_LINK_UP()) {
+ // Close link
+ SQL_CLOSE(__FILE__, __LINE__);
+ } elseif ((!isInstalling()) && (isInstalled())) {
+ // No database link
+ addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
+ }
+
+ // Stop executing here
+ exit;
}
-// Decode strings encoded with encodeString()
-// @TODO Implement $decompress
-function decodeString ($str, $decompress=true) {
- $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
- return $str;
+// Setter for userid
+function setUserId ($userid) {
+ $GLOBALS['userid'] = bigintval($userid);
}
-// Compile characters which are allowed in URLs
-function compileUriCode ($code, $simple=true) {
- // Compile constants
- if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
+// Getter for userid or returns zero
+function getUserId () {
+ // Default userid
+ $userid = 0;
- // Compile QUOT and other non-HTML codes
- $code = str_replace("{DOT}", ".",
- str_replace("{SLASH}", "/",
- str_replace("{QUOT}", "'",
- str_replace("{DOLLAR}", "$",
- str_replace("{OPEN_ANCHOR}", "(",
- str_replace("{CLOSE_ANCHOR}", ")",
- str_replace("{OPEN_SQR}", "[",
- str_replace("{CLOSE_SQR}", "]",
- str_replace("{PER}", "%",
- $code
- )))))))));
+ // Is the userid set?
+ if (isUserIdSet()) {
+ // Then use it
+ $userid = $GLOBALS['userid'];
+ } // END - if
- // Return compiled code
- return $code;
+ // Return it
+ return $userid;
}
-// Function taken from user comments on www.php.net / function eregi()
-function isUrlValid ($url) {
- // Prepare URL
- $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
+// Checks ether the userid is set
+function isUserIdSet () {
+ return (isset($GLOBALS['userid']));
+}
- // Allows http and https
- $http = "(http|https)+(:\/\/)";
- // Test domain
- $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
- // Test double-domains (e.g. .de.vu)
- $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
- // Test IP number
- $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
- // ... directory
- $dir = "((/)+([-_\.[:alnum:]])+)*";
- // ... page
- $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
- // ... and the string after and including question character
- $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
- // Pattern for URLs like http://url/dir/doc.html?var=value
- $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
- $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
- $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
- // Pattern for URLs like http://url/dir/?var=value
- $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
- $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
- $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
- // Pattern for URLs like http://url/dir/page.ext
- $pattern['d1dp'] = $http.$domain1.$dir.$page;
- $pattern['d1dp'] = $http.$domain2.$dir.$page;
- $pattern['ipdp'] = $http.$ip.$dir.$page;
- // Pattern for URLs like http://url/dir
- $pattern['d1d'] = $http.$domain1.$dir;
- $pattern['d2d'] = $http.$domain2.$dir;
- $pattern['ipd'] = $http.$ip.$dir;
- // Pattern for URLs like http://url/?var=value
- $pattern['d1g1'] = $http.$domain1."/".$getstring1;
- $pattern['d2g1'] = $http.$domain2."/".$getstring1;
- $pattern['ipg1'] = $http.$ip."/".$getstring1;
- // Pattern for URLs like http://url?var=value
- $pattern['d1g12'] = $http.$domain1.$getstring1;
- $pattern['d2g12'] = $http.$domain2.$getstring1;
- $pattern['ipg12'] = $http.$ip.$getstring1;
- // Test all patterns
- $reg = false;
- foreach ($pattern as $key=>$pat) {
- // Debug regex?
- if (defined('DEBUG_REGEX')) {
- $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
- $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
- $pat = str_replace("[:digit:]", "0-9", $pat);
- $pat = str_replace(".", "\.", $pat);
- $pat = str_replace("@", "\@", $pat);
- echo $key."= ".$pat." ";
- }
+// Handle message codes from URL
+function handleCodeMessage () {
+ if (REQUEST_ISSET_GET('msg')) {
+ // Default extension is "unknown"
+ $ext = 'unknown';
- // Check if expression matches
- $reg = ($reg || preg_match(("^".$pat."^"), $url));
+ // Is extension given?
+ if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
- // Does it match?
- if ($reg === true) break;
- }
+ // Convert the 'msg' parameter from URL to a human-readable message
+ $msg = convertCodeToMessage(REQUEST_GET('msg'));
- // Return true/false
- return $reg;
+ // Load message template
+ LOAD_TEMPLATE('message', false, $msg);
+ } // END - if
}
-// Smartly adds slashes
-function smartAddSlashes ($unquoted) {
- $unquoted = str_replace("\\", "", $unquoted);
- return addslashes($unquoted);
+// Setter for extra title
+function setExtraTitle ($extraTitle) {
+ $GLOBALS['extra_title'] = $extraTitle;
}
-// Decode entities in a nicer way
-function decodeEntities ($str) {
- // @TODO We may want to switch over to UTF-8 here!
- $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
+// Getter for extra title
+function getExtraTitle () {
+ // Is the extra title set?
+ if (!isExtraTitleSet()) {
+ // No, then abort here
+ debug_report_bug('extra_title is not set!');
+ } // END - if
+
+ // Return it
+ return $GLOBALS['extra_title'];
+}
- // Return decoded string
- return $decodedString;
+// Checks if the extra title is set
+function isExtraTitleSet () {
+ return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
}
//////////////////////////////////////////////////