-';
} else {
// Open anchor tag and add base URL
- $NAV .= ' 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
// Close open anchor tag
- $NAV .= '">';
+ $NAV .= '%}">';
}
$NAV .= $page;
if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
@@ -1725,16 +1714,16 @@ function extractHostnameFromUrl (&$script) {
if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
// Generate relative URL
- //* DEBUG: */ print("SCRIPT=" . $script."
");
+ //* DEBUG: */ print("SCRIPT=" . $script.'
');
if (substr(strtolower($script), 0, 7) == 'http://') {
// But only if http:// is in front!
$script = substr($script, (strlen($url) + 7));
- } elseif (substr(strtolower($script), 0, 8) == "https://") {
+ } elseif (substr(strtolower($script), 0, 8) == 'https://') {
// Does this work?!
$script = substr($script, (strlen($url) + 8));
}
- //* DEBUG: */ print("SCRIPT=" . $script."
");
+ //* DEBUG: */ print("SCRIPT=" . $script.'
');
if (substr($script, 0, 1) == '/') $script = substr($script, 1);
// Return host name
@@ -1747,19 +1736,22 @@ function sendGetRequest ($script, $data = array()) {
$host = extractHostnameFromUrl($script);
// Add data
- $scriptData = http_build_query($data, '', '&');
+ $body = http_build_query($data, '', '&');
// Do we have a question-mark in the script?
if (strpos($script, '?') === false) {
// No, so first char must be question mark
- $scriptData = '?' . $scriptData;
+ $body = '?' . $body;
} else {
// Ok, add &
- $scriptData = '&' . $scriptData;
+ $body = '&' . $body;
}
// Add script data
- $script .= $scriptData;
+ $script .= $body;
+
+ // Remove trailed & to make it more conform
+ if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
// Generate GET request header
$request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
@@ -1770,9 +1762,12 @@ function sendGetRequest ($script, $data = array()) {
} else {
$request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
}
- $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+ $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
+ $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
$request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
- $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
+ $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+ $request .= 'Content-Length: '.strlen($body) . getConfig('HTTP_EOL');
+ $request .= 'Connection: close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
// Send the raw request
$response = sendRawRequest($host, $request);
@@ -1790,25 +1785,21 @@ function sendPostRequest ($script, $postData) {
return array('', '', '');
} // END - if
- // Compile the script name
- $script = compileCode($script);
-
// Extract host name from script
$host = extractHostnameFromUrl($script);
// Construct request
- $data = http_build_query($postData, '', '&');
+ $body = http_build_query($postData, '', '&');
// Generate POST request header
$request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
$request .= 'Host: ' . $host . getConfig('HTTP_EOL');
$request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
$request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
- $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
- $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
$request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
- $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
- $request .= $data;
+ $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
+ $request .= 'Connection: close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
+ $request .= $body;
// Send the raw request
$response = sendRawRequest($host, $request);
@@ -1820,7 +1811,7 @@ function sendPostRequest ($script, $postData) {
// Sends a raw request to another host
function sendRawRequest ($host, $request) {
// Init errno and errdesc with 'all fine' values
- $errno = 0; $errdesc = '';
+ $errno = '0'; $errdesc = '';
// Initialize array
$response = array('', '', '');
@@ -1835,40 +1826,45 @@ function sendRawRequest ($host, $request) {
} // END - if
// Open connection
- //* DEBUG: */ die("SCRIPT=" . $script."
");
+ //* DEBUG: */ die("SCRIPT=" . $script.'
');
if ($useProxy === true) {
// Connect to host through proxy connection
- $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
+ $fp = fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
} else {
// Connect to host directly
- $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
+ $fp = fsockopen($host, 80, $errno, $errdesc, 30);
}
// Is there a link?
if (!is_resource($fp)) {
// Failed!
+ logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
return $response;
- } // END - if
+ } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
+ // Cannot set non-blocking mode or timeout
+ logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
+ return $response;
+ }
// Do we use proxy?
if ($useProxy === true) {
// Generate CONNECT request header
- $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
- $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
+ $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
+ $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
// Use login data to proxy? (username at least!)
if (getConfig('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
- $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
+ $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
+ $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
} // END - if
// Add last new-line
$proxyTunnel .= getConfig('HTTP_EOL');
- //* DEBUG: */ print("proxyTunnel=" . $proxyTunnel."
");
+ //* DEBUG: */ print('proxyTunnel=' . $proxyTunnel.'
');
// Write request
- fputs($fp, $proxyTunnel);
+ fwrite($fp, $proxyTunnel);
// Got response?
if (feof($fp)) {
@@ -1886,11 +1882,39 @@ function sendRawRequest ($host, $request) {
} // END - if
// Write request
- fputs($fp, $request);
+ fwrite($fp, $request);
+
+ // Start counting
+ $start = microtime(true);
// Read response
while (!feof($fp)) {
- $response[] = trim(fgets($fp, 1024));
+ // Get info from stream
+ $info = stream_get_meta_data($fp);
+
+ // Is it timed out? 15 seconds is a really patient...
+ if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
+ // Timeout
+ logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
+
+ // Abort here
+ break;
+ } // END - if
+
+ // Get line from stream
+ $line = fgets($fp, 128);
+
+ // Ignore empty lines because of non-blocking mode
+ if (empty($line)) {
+ // uslepp a little to avoid 100% CPU load
+ usleep(10);
+
+ // Skip this
+ continue;
+ } // END - if
+
+ // Add it to response
+ $response[] = trim($line);
} // END - while
// Close socket
@@ -1912,10 +1936,13 @@ function sendRawRequest ($host, $request) {
}
} // END - foreach
- //* DEBUG: */ print("Response:".print_r($response, true)."
");
+ //* DEBUG: */ print('Response:'.print_r($response, true).'
');
- // Proxy agent found?
- if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
+ // Proxy agent found or something went wrong?
+ if (!isset($response[0])) {
+ // No response, maybe timeout
+ $response = array('', '', '');
+ } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
// Proxy header detected, so remove two lines
array_shift($response);
array_shift($response);
@@ -1933,9 +1960,6 @@ function sendRawRequest ($host, $request) {
// Taken from www.php.net eregi() user comments
function isEmailValid ($email) {
- // Compile email
- $email = compileCode($email);
-
// Check first part of email address
$first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
@@ -1953,11 +1977,11 @@ function isEmailValid ($email) {
function isUrlValid ($URL, $compile=true) {
// Trim URL a little
$URL = trim(urldecode($URL));
- //* DEBUG: */ outputHtml($URL."
");
+ //* DEBUG: */ outputHtml($URL.'
');
// Compile some chars out...
if ($compile === true) $URL = compileUriCode($URL, false, false, false);
- //* DEBUG: */ outputHtml($URL."
");
+ //* DEBUG: */ outputHtml($URL.'
');
// Check for the extension filter
if (isExtensionActive('filter')) {
@@ -1979,11 +2003,11 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
$targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
// Begin of navigation links
- $OUT = "[ ";
+ $OUT = '[ ';
foreach ($targetArray as $tar) {
- $OUT .= "");
+ $OUT .= '{--ADMIN_";
+ $OUT .= '_TITLE--}">{--ADMIN_';
if (($tar == 'lock_user') && ($status == 'LOCKED')) {
// Locked accounts shall be unlocked
$OUT .= 'UNLOCK_USER';
@@ -1999,7 +2023,7 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
// All other status is fine
$OUT .= strtoupper($tar);
}
- $OUT .= "--} | ";
+ $OUT .= '--} | ';
}
// Finish navigation link
@@ -2036,7 +2060,7 @@ function generateEmailLink ($email, $table = 'admins') {
// Generate a hash for extra-security for all passwords
function generateHash ($plainText, $salt = '') {
// Is the required extension 'sql_patches' there and a salt is not given?
- if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches'))) && (empty($salt))) {
+ if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
// Extension sql_patches is missing/outdated so we hash the plain text with MD5
return md5($plainText);
} // END - if
@@ -2063,19 +2087,26 @@ function generateHash ($plainText, $salt = '') {
// Generate SHA1 sum from modula of number and the prime number
$sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
- //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")
");
+ //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')
');
$sha1 = scrambleString($sha1);
- //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")
");
+ //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')
');
//* DEBUG: */ $sha1b = descrambleString($sha1);
- //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")
");
+ //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')
');
// Generate the password salt string
$salt = substr($sha1, 0, getConfig('salt_length'));
- //* DEBUG: */ outputHtml($salt." (".strlen($salt).")
");
+ //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')
');
} else {
// Use given salt
+ //* DEBUG: */ print 'salt=' . $salt . '
';
$salt = substr($salt, 0, getConfig('salt_length'));
- //* DEBUG: */ outputHtml("GIVEN={$salt}
");
+ //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')
';
+
+ // Sanity check on salt
+ if (strlen($salt) != getConfig('salt_length')) {
+ // Not the same!
+ debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
+ } // END - if
}
// Return hash
@@ -2099,9 +2130,12 @@ function scrambleString($str) {
$scrambleNums = explode(':', genScrambleString(strlen($str)));
}
+ // Compare both lengths and abort if different
+ if (strlen($str) != count($scrambleNums)) return $str;
+
// Scramble string here
- //* DEBUG: */ outputHtml("***Original=" . $str."***
");
- for ($idx = 0; $idx < strlen($str); $idx++) {
+ //* DEBUG: */ outputHtml('***Original=' . $str.'***
');
+ for ($idx = '0'; $idx < strlen($str); $idx++) {
// Get char on scrambled position
$char = substr($str, $scrambleNums[$idx], 1);
@@ -2110,7 +2144,7 @@ function scrambleString($str) {
} // END - for
// Return scrambled string
- //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***
");
+ //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***
');
return $scrambled;
}
@@ -2127,14 +2161,14 @@ function descrambleString($str) {
// Begin descrambling
$orig = str_repeat(' ', 40);
- //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++
");
- for ($idx = 0; $idx < 40; $idx++) {
+ //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++
');
+ for ($idx = '0'; $idx < 40; $idx++) {
$char = substr($str, $idx, 1);
$orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
} // END - for
// Return scrambled string
- //* DEBUG: */ outputHtml("+++Original=" . $orig."+++
");
+ //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++
');
return $orig;
}
@@ -2144,7 +2178,7 @@ function genScrambleString ($len) {
$scrambleNumbers = array();
// First we need to setup randomized numbers from 0 to 31
- for ($idx = 0; $idx < $len; $idx++) {
+ for ($idx = '0'; $idx < $len; $idx++) {
// Generate number
$rand = mt_rand(0, ($len -1));
@@ -2168,10 +2202,10 @@ function generatePassString ($passHash) {
$ret = $passHash;
// Is a secret key and master salt already initialized?
- if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
+ if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
// Only calculate when the secret key is generated
$newHash = ''; $start = 9;
- for ($idx = 0; $idx < 10; $idx++) {
+ for ($idx = '0'; $idx < 10; $idx++) {
$part1 = hexdec(substr($passHash, $start, 4));
$part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
$mod = dechex($idx);
@@ -2180,16 +2214,17 @@ function generatePassString ($passHash) {
} elseif ($part2 > $part1) {
$mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
}
- $mod = substr(round($mod), 0, 4);
- $mod = str_repeat(0, 4-strlen($mod)) . $mod;
- //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*
");
+ $mod = substr($mod, 0, 4);
+ //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')
');
+ $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
+ //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*
');
$start += 4;
$newHash .= $mod;
} // END - for
- //* DEBUG: */ print($passHash."
" . $newHash." (".strlen($newHash).')');
+ //* DEBUG: */ print($passHash.'
' . $newHash." (".strlen($newHash).')
');
$ret = generateHash($newHash, getConfig('master_salt'));
- //* DEBUG: */ print($ret."
");
+ //* DEBUG: */ print('ret='.$ret.'
');
} else {
// Hash it simple
//* DEBUG: */ outputHtml("--" . $passHash."--
");
@@ -2229,10 +2264,10 @@ function app_die ($F, $L, $message) {
$message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
// Better log this message away
- logDebugMessage($F, $L, $message);
+ if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
// Load the message template
- loadTemplate('admin_settings_saved', false, $message);
+ loadTemplate('app_die_message', false, $message);
// Load footer
loadIncludeOnce('inc/footer.php');
@@ -2257,7 +2292,7 @@ function displayParsingTime() {
$start = explode(' ', $GLOBALS['startTime']);
$end = explode(' ', $endTime);
$runTime = $end[0] - $start[0];
- if ($runTime < 0) $runTime = 0;
+ if ($runTime < 0) $runTime = '0';
// Prepare output
$content = array(
@@ -2309,107 +2344,34 @@ function getCurrentTheme () {
// The default theme is 'default'... ;-)
$ret = 'default';
- // Load default theme if not empty from configuration
- if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
-
- if (!isSessionVariableSet('mxchange_theme')) {
- // Set default theme
- setTheme($ret);
- } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
- //die("".print_r($GLOBALS['cache_array']['themes'], true)."
");
- // Get theme from cookie
- $ret = getSession('mxchange_theme');
-
- // Is it valid?
- if (getThemeId($ret) == 0) {
- // Fix it to default
- $ret = 'default';
- } // END - if
- } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
- // Prepare FQFN for checking
- $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
-
- // Installation mode active
- if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
- // Set cookie from URL data
- setTheme(getRequestElement('theme'));
- } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
- // Set cookie from posted data
- setTheme(SQL_ESCAPE(postRequestElement('theme')));
- }
-
- // Set return value
- $ret = getSession('mxchange_theme');
- } else {
- // Invalid design, reset cookie
- setTheme($ret);
- }
+ // Do we have ext-theme installed and active?
+ if (isExtensionActive('theme')) {
+ // Call inner method
+ $ret = getActualTheme();
+ } // END - if
// Return theme value
return $ret;
}
-// Setter for theme in session
-function setTheme ($newTheme) {
- setSession('mxchange_theme', $newTheme);
-}
-
-// Get id from theme
-// @TODO Try to move this to inc/libs/theme_functions.php
-function getThemeId ($name) {
- // Is the extension 'theme' installed?
- if (!isExtensionActive('theme')) {
- // Then abort here
- return 0;
- } // END - if
-
- // Default id
- $id = 0;
-
- // 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
- incrementStatsEntry('cache_hits');
- } elseif (getExtensionVersion('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__);
-
- // Entry found?
- if (SQL_NUMROWS($result) == 1) {
- // Fetch data
- list($id) = SQL_FETCHROW($result);
- } // END - if
-
- // Free result
- SQL_FREERESULT($result);
- }
-
- // Return id
- return $id;
-}
-
// Generates an error code from given account status
-function generateErrorCodeFromUserStatus ($status) {
- // @TODO The status should never be empty
- if (empty($status)) {
- // Something really bad happend here
- debug_report_bug(__FUNCTION__ . ': status is empty.');
+function generateErrorCodeFromUserStatus ($status='') {
+ // If no status is provided, use the default, cached
+ if ((empty($status)) && (isMember())) {
+ // Get user status
+ $status = getUserData('status');
} // END - if
// Default error code if unknown account status
$errorCode = getCode('UNKNOWN_STATUS');
// Generate constant name
- $constantName = sprintf("ID_%s", $status);
+ $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
// Is the constant there?
- if (isCodeSet($constantName)) {
+ if (isCodeSet($codeName)) {
// Then get it!
- $errorCode = getCode($constantName);
+ $errorCode = getCode($codeName);
} else {
// Unknown status
logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
@@ -2422,12 +2384,12 @@ function generateErrorCodeFromUserStatus ($status) {
// Function to search for the last modifified file
function searchDirsRecursive ($dir, &$last_changed) {
// Get dir as array
- //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):dir=" . $dir."
");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):dir=" . $dir.'
');
// 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|debug\.log|\.cache|config\.php)$@';
$ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
- //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):ds[]=".count($ds)."
");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):ds[]=".count($ds).'
');
// Walk through all entries
foreach ($ds as $d) {
@@ -2440,7 +2402,7 @@ function searchDirsRecursive ($dir, &$last_changed) {
// $FQFN is a directory so also crawl into this directory
$newDir = $d;
if (!empty($dir)) $newDir = $dir . '/'. $d;
- //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):DESCENT: " . $newDir."
");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):DESCENT: " . $newDir.'
');
searchDirsRecursive($newDir, $last_changed);
} elseif (isFileReadable($FQFN)) {
// $FQFN is a filename and no directory
@@ -2495,7 +2457,7 @@ function getActualVersion ($type = 'Revision') {
$new = true;
} else {
// Generate fake cache entry
- foreach ($mapper as $map=>$idx) {
+ foreach ($mapper as $map => $idx) {
$GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
} // END - foreach
@@ -2541,7 +2503,7 @@ function getArrayFromActualVersion () {
$akt_vers = array();
// Init value for counting the founded keywords
- $res = 0;
+ $res = '0';
// 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);
@@ -2617,8 +2579,26 @@ function debug_get_printable_backtrace () {
return $backtrace;
}
+// A mail-able backtrace
+function debug_get_mailable_backtrace () {
+ // Init variable
+ $backtrace = '';
+
+ // 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 .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
+ } // END - foreach
+
+ // Return the backtrace
+ return $backtrace;
+}
+
// Output a debug backtrace to the user
-function debug_report_bug ($message = '') {
+function debug_report_bug ($message = '', $sendEmail = true) {
// Is this already called?
if (isset($GLOBALS[__FUNCTION__])) {
// Other backtrace
@@ -2645,21 +2625,30 @@ function debug_report_bug ($message = '') {
} // END - if
// Add output
- $debug .= "Please report this bug at bugs.mxchange.org and include the logfile from " . getConfig('CACHE_PATH') . "debug.log in your report (you can now attach files):";
+ $debug .= "Please report this bug at http://bugs.mxchange.org and include the logfile from " . str_replace(getConfig('PATH'), '', getConfig('CACHE_PATH')) . "debug.log in your report (you can now attach files):";
$debug .= debug_get_printable_backtrace();
$debug .= "
\nRequest-URI: " . getRequestUri()."
\n";
$debug .= "Thank you for finding bugs.";
+ // Send an email? (e.g. not wanted for evaluation errors)
+ if (($sendEmail === true) && (!isInstallationPhase())) {
+ // Prepare content
+ $content = array(
+ 'message' => trim($message),
+ 'backtrace' => trim(debug_get_mailable_backtrace())
+ );
+
+ // Send email to webmaster
+ sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
+ } // END - if
+
// And abort here
- // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
- die($debug);
+ app_die(__FUNCTION__, __LINE__, $debug);
}
-// Generates a ***weak*** seed (taken from de.php.net/mt_srand)
+// Generates a ***weak*** seed
function generateSeed () {
- list($usec, $sec) = explode(' ', microtime());
- $microTime = (((float)$sec + (float)$usec)) * 100000;
- return $microTime;
+ return microtime(true) * 100000;
}
// Converts a message code to a human-readable message
@@ -2667,40 +2656,40 @@ function getMessageFromErrorCode ($code) {
$message = '';
switch ($code) {
case '': break;
- case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
- case getCode('LOGOUT_FAILED') : $message = "{--LOGOUT_FAILED--}"; break;
- case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
- case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
- case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
- case getCode('USER_404') : $message = getMessage('USER_404'); break;
- case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
- case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
- case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
- case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
- case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
- case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
- case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
- case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
- case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
- case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
- case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
- case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
- case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
- case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
- case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}
\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
- case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
- case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
- case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
- case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
- case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
- case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
- case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
+ case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
+ case getCode('LOGOUT_FAILED') : $message = '{--LOGOUT_FAILED--}'; break;
+ case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
+ case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
+ case getCode('USER_404') : $message = getMessage('USER_404'); break;
+ case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
+ case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+ case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
+ case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
+ case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
+ case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
+ case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
+ case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
+ case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
+ case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestElement('mod')); break;
+ case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
+ case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
+ case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
+ case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}
\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
+ case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
+ case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
+ case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
+ case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
+ case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
+ case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
+ case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
+ case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
+ case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
case getCode('ERROR_MAILID'):
if (isExtensionActive('mailid', true)) {
$message = getMessage('ERROR_CONFIRMING_MAIL');
} else {
- $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
+ $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
}
break;
@@ -2713,16 +2702,19 @@ function getMessageFromErrorCode ($code) {
break;
case getCode('URL_TLOCK'):
+ // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
$result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
// Load timestamp from last order
list($timestamp) = SQL_FETCHROW($result);
- $timestamp = generateDateTime($timestamp, 1);
// Free memory
SQL_FREERESULT($result);
+ // Translate it for templates
+ $timestamp = generateDateTime($timestamp, 1);
+
// Calculate hours...
$STD = round(getConfig('url_tlock') / 60 / 60);
@@ -2741,7 +2733,7 @@ function getMessageFromErrorCode ($code) {
default:
// Missing/invalid code
- $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
+ $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
// Log it
logDebugMessage(__FUNCTION__, __LINE__, $message);
@@ -2752,36 +2744,6 @@ function getMessageFromErrorCode ($code) {
return $message;
}
-// Generate a "link" for the given admin id (admin_id)
-function generateAdminLink ($adminId) {
- // No assigned admin is default
- $admin = "{--ADMIN_NO_ADMIN_ASSIGNED--}";
-
- // Zero? = Not assigned
- if (bigintval($adminId) > 0) {
- // Load admin's login
- $login = getAdminLogin($adminId);
-
- // Is the login valid?
- if ($login != '***') {
- // Is the extension there?
- if (isExtensionActive('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'), $adminId)."
";
- }
- } // END - if
-
- // Return result
- return $admin;
-}
-
// Compile characters which are allowed in URLs
function compileUriCode ($code, $simple = true) {
// Compile constants
@@ -2807,7 +2769,7 @@ function compileUriCode ($code, $simple = true) {
// Function taken from user comments on www.php.net / function eregi()
function isUrlValidSimple ($url) {
// Prepare URL
- $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
+ $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
// Allows http and https
$http = "(http|https)+(:\/\/)";
@@ -2855,7 +2817,7 @@ function isUrlValidSimple ($url) {
// @TODO Are these convertions still required?
$pat = str_replace('.', "\.", $pat);
$pat = str_replace('@', "\@", $pat);
- //* DEBUG: */ outputHtml($key."= " . $pat . "
");
+ //* DEBUG: */ outputHtml($key."= " . $pat . '
');
} // END - if
// Check if expression matches
@@ -2901,7 +2863,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
// Read from source file
$line = fgets ($fp, 1024);
- if (strpos($line, $search) > -1) { $next = 0; $found = true; }
+ if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
if ($next > -1) {
if ($next === $seek) {
@@ -2913,7 +2875,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
} // END - if
// Write to temp file
- fputs($fp_tmp, $line);
+ fwrite($fp_tmp, $line);
} // END - while
// Close temp file
@@ -2945,8 +2907,8 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
return false;
}
// Send notification to admin
-function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
- if (getExtensionVersion('admins') >= '0.4.1') {
+function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
+ if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
// Send new way
sendAdminsEmails($subject, $templateName, $content, $userid);
} else {
@@ -2965,7 +2927,7 @@ function logDebugMessage ($funcFile, $line, $message, $force=true) {
// Log this message away, we better don't call app_die() here to prevent an endless loop
$fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
- fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
+ fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
fclose($fp);
} // END - if
}
@@ -3006,6 +2968,7 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
// Converts timestamp selections into a timestamp
function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
// Init test variable
+ $skip = false;
$test2 = '';
// Get last three chars
@@ -3018,21 +2981,20 @@ function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
// Generate timestamp
$postData[$test] = createTimestampFromSelections($test, $postData);
- $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
+ $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
+ $GLOBALS['skip_config'][$test] = true;
// Remove data from array
foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
- unset($postData[$test.'_' . $rem]);
+ unset($postData[$test . '_' . $rem]);
} // END - foreach
// Skip adding
- unset($id); $skip = true; $test2 = $test;
+ unset($id);
+ $skip = true;
+ $test2 = $test;
} // END - if
- } else {
- // Process this entry
- $skip = false;
- $test2 = '';
- }
+ } // END - if
}
// Reverts the german decimal comma into Computer decimal dot
@@ -3151,15 +3113,15 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
// Generate receiver list
- $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
+ $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
// Receivers added?
- if (!empty($RECEIVER)) {
+ if (!empty($receiver)) {
// Add bonus mail to queue
addBonusMailToQueue(
$data['subject'],
$data['text'],
- $RECEIVER,
+ $receiver,
$data['points'],
$data['seconds'],
$data['url'],
@@ -3181,8 +3143,8 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
// Determines referal id and sets it
function determineReferalId () {
- // Skip this in non-html-mode
- if (getOutputMode() != 0) return false;
+ // Skip this in non-html-mode and outside ref.php
+ if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
// Check if refid is set
if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
@@ -3202,19 +3164,37 @@ function determineReferalId () {
} elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
// Set session refid als global
$GLOBALS['refid'] = bigintval(getSession('refid'));
- } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
+ } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
// Select a random user which has confirmed enougth mails
$GLOBALS['refid'] = determineRandomReferalId();
} elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
// Set default refid as refid in URL
$GLOBALS['refid'] = getConfig('def_refid');
} else {
- // No default ID when sql_patches is not installed or none set
- $GLOBALS['refid'] = 0;
+ // No default id when sql_patches is not installed or none set
+ $GLOBALS['refid'] = '0';
}
// Set cookie when default refid > 0
- if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+ if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+ // Default is not found
+ $found = false;
+
+ // Do we have nickname or userid set?
+ if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
+ // Nickname in URL, so load the id
+ $found = fetchUserData($GLOBALS['refid'], 'nickname');
+ } elseif ($GLOBALS['refid'] > 0) {
+ // Direct userid entered
+ $found = fetchUserData($GLOBALS['refid']);
+ }
+
+ // Is the record valid?
+ if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
+ // No, then reset referal id
+ $GLOBALS['refid'] = getConfig('def_refid');
+ } // END - if
+
// Set cookie
setSession('refid', $GLOBALS['refid']);
} // END - if
@@ -3237,7 +3217,8 @@ function shutdown () {
// Call the filter chain 'shutdown'
runFilterChain('shutdown', null);
- if (SQL_IS_LINK_UP()) {
+ // Check if not in installation phase and the link is up
+ if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
// Close link
SQL_CLOSE(__FILE__, __LINE__);
} elseif (!isInstallationPhase()) {
@@ -3249,29 +3230,38 @@ function shutdown () {
exit;
}
-// Setter for userid
-function setUserId ($userid) {
- $GLOBALS['userid'] = bigintval($userid);
+// Init member id
+function initMemberId () {
+ $GLOBALS['member_id'] = '0';
+}
+
+// Setter for member id
+function setMemberId ($memberid) {
+ // We should not set member id to zero
+ if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
+
+ // Set it secured
+ $GLOBALS['member_id'] = bigintval($memberid);
}
-// Getter for userid or returns zero
-function getUserId () {
- // Default userid
- $userid = 0;
+// Getter for member id or returns zero
+function getMemberId () {
+ // Default member id
+ $memberid = '0';
- // Is the userid set?
- if (isUserIdSet()) {
+ // Is the member id set?
+ if (isMemberIdSet()) {
// Then use it
- $userid = $GLOBALS['userid'];
+ $memberid = $GLOBALS['member_id'];
} // END - if
// Return it
- return $userid;
+ return $memberid;
}
-// Checks ether the userid is set
-function isUserIdSet () {
- return (isset($GLOBALS['userid']));
+// Checks ether the member id is set
+function isMemberIdSet () {
+ return (isset($GLOBALS['member_id']));
}
// Handle message codes from URL
@@ -3322,12 +3312,12 @@ function generateExtensionInactiveMessage ($ext_name) {
} // END - if
// Default message
- $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+ $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
// Is an admin logged in?
if (isAdmin()) {
// Then output admin message
- $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+ $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
} // END - if
// Return prepared message
@@ -3343,12 +3333,12 @@ function generateExtensionNotInstalledMessage ($ext_name) {
} // END - if
// Default message
- $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+ $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
// Is an admin logged in?
if (isAdmin()) {
// Then output admin message
- $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+ $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
} // END - if
// Return prepared message
@@ -3384,7 +3374,7 @@ function generateExtensionInactiveNotInstalledMessage ($ext_name) {
// Reads a directory recursively by default and searches for files not matching
// an exclusion pattern. You can now keep the exclusion pattern empty for reading
// a whole directory.
-function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
+function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
// Add default entries we should exclude
$excludeArray[] = '.';
$excludeArray[] = '..';
@@ -3403,7 +3393,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Exclude '.', '..' and entries in $excludeArray automatically
if (in_array($baseFile, $excludeArray, true)) {
// Exclude them
- //* DEBUG: */ outputHtml('excluded=' . $baseFile . "
");
+ //* DEBUG: */ outputHtml('excluded=' . $baseFile . '
');
continue;
} // END - if
@@ -3414,12 +3404,12 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Remove double slashes
$FQFN = str_replace('//', '/', $FQFN);
- // Check if the base filename matches an exclusion pattern and if the pattern is not empty
+ // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
// These Lines are only for debugging!!
- //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "
");
- //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "
");
- //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "
");
+ //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '
');
+ //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '
');
+ //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '
');
// Exclude this one
continue;
@@ -3436,6 +3426,10 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Skip this file
//* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
continue;
+ } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
+ // Skip wrong suffix as well
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
+ continue;
} elseif (!isFileReadable($FQFN)) {
// Not readable so skip it
//* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
@@ -3478,7 +3472,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
closedir($dirPointer);
// Sort array
- asort($files);
+ sort($files);
// Return array with include files
//* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
@@ -3514,7 +3508,7 @@ function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
// Do we have cache?
if (!isset($GLOBALS['debug_sql_available'])) {
// Check it and cache it in $GLOBALS
- $GLOBALS['debug_sql_available'] = ((isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
+ $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
} // END - if
// Don't execute anything here if we don't need or ext-other is missing
@@ -3545,7 +3539,7 @@ function initCacheInstance () {
$GLOBALS['cache_instance'] = new CacheSystem();
if ($GLOBALS['cache_instance']->getStatus() != 'done') {
// Failed to initialize cache sustem
- addFatalMessage(__FILE__, __LINE__, "(".__LINE__."): ".getMessage('CACHE_CANNOT_INITIALIZE'));
+ addFatalMessage(__FILE__, __LINE__, '(' . __LINE__ . '): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
} // END - if
}
@@ -3591,6 +3585,339 @@ function convertReceivers ($old) {
return str_replace(';', ', ', $old);
}
+// Determines the right page title
+function determinePageTitle () {
+ // Config and database connection valid?
+ if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+ // Init title
+ $TITLE = '';
+
+ // Title decoration enabled?
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
+
+ // Do we have some extra title?
+ if (isExtraTitleSet()) {
+ // Then prepent it
+ $TITLE .= getExtraTitle() . ' by ';
+ } // END - if
+
+ // Add main title
+ $TITLE .= getConfig('MAIN_TITLE');
+
+ // Add title of module? (middle decoration will also be added!)
+ if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+ $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+ } // END - if
+
+ // Add title from what file
+ $mode = '';
+ if (getModule() == 'login') $mode = 'member';
+ elseif (getModule() == 'index') $mode = 'guest';
+ if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
+
+ // Add title decorations? (right)
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
+
+ // Remember title in constant for the template
+ $pageTitle = $TITLE;
+ } elseif ((isInstalled()) && (isAdminRegistered())) {
+ // Installed, admin registered but no ext-sql_patches
+ $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
+ } elseif ((isInstalled()) && (!isAdminRegistered())) {
+ // Installed but no admin registered
+ $pageTitle = getMessage('SETUP_OF_MXCHANGE');
+ } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+ // Installation mode
+ $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
+ } else {
+ // Configuration not found!
+ $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
+
+ // Do not add the fatal message in installation mode
+ if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
+ }
+
+ // Return title
+ return decodeEntities($pageTitle);
+}
+
+// Checks wethere there is a cache file there. This function is cached.
+function isTemplateCached ($template) {
+ // Do we have cached this result?
+ if (!isset($GLOBALS['template_cache'][$template])) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // Is it there?
+ $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
+ } // END - if
+
+ // Return it
+ return $GLOBALS['template_cache'][$template];
+}
+
+// Flushes non-flushed template cache to disk
+function flushTemplateCache ($template, $eval) {
+ // Is this cache flushed?
+ if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // Replace username with a call
+ $eval = str_replace('$username', '".getUsername()."', $eval);
+
+ // And flush it
+ writeToFile($FQFN, $eval, true);
+ } // END - if
+}
+
+// Reads a template cache
+function readTemplateCache ($template) {
+ // Check it again
+ if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // And read from it
+ $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
+ } // END - if
+
+ // And return it
+ return $GLOBALS['template_eval'][$template];
+}
+
+// Escapes quotes (default is only double-quotes)
+function escapeQuotes ($str, $single = false) {
+ // Should we escape all?
+ if ($single === true) {
+ // Escape all (including null)
+ $str = addslashes($str);
+ } else {
+ // Escape only double-quotes but prevent double-quoting
+ $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
+ }
+
+ // Return the escaped string
+ return $str;
+}
+
+// Escapes the JavaScript code, prevents \r and \n becoming char 10/13
+function escapeJavaScriptQuotes ($str) {
+ // Replace all double-quotes and secure back-ticks
+ $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
+
+ // Return it
+ return $str;
+}
+
+// Send out mails depending on the 'mod/modes' combination
+// @TODO Lame description for this function
+function sendModeMails ($mod, $modes) {
+ // Load hash
+ if (fetchUserData(getMemberId())) {
+ // Extract salt from cookie
+ $salt = substr(getSession('u_hash'), 0, -40);
+
+ // Now let's compare passwords
+ $hash = generatePassString(getUserData('password'));
+
+ // Does the hash match or should we change it?
+ if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
+ // Load the data
+ $content = getUserDataArray();
+
+ // Translate gender
+ $content['gender'] = translateGender($content['gender']);
+
+ // Clear/init the content variable
+ $content['message'] = '';
+
+ // Which mail?
+ // @TODO Move this in a filter
+ switch ($mod) {
+ case 'mydata':
+ foreach ($modes as $mode) {
+ switch ($mode) {
+ case 'normal': break; // Do not add any special lines
+ case 'email': // Email was changed!
+ $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
+ break;
+
+ case 'pass': // Password was changed
+ $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
+ break;
+
+ default:
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
+ $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
+ break;
+ } // END - switch
+ } // END - foreach
+
+ if (isExtensionActive('country')) {
+ // Replace code with description
+ $content['country'] = generateCountryInfo(postRequestElement('country_code'));
+ } // END - if
+
+ // Merge content with data from POST
+ $content = merge_array($content, postRequestArray());
+
+ // Load template
+ $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
+
+ if (getConfig('admin_notify') == 'Y') {
+ // The admin needs to be notified about a profile change
+ $message_admin = 'admin_mydata_notify';
+ $sub_adm = getMessage('ADMIN_CHANGED_DATA');
+ } else {
+ // No mail to admin
+ $message_admin = '';
+ $sub_adm = '';
+ }
+
+ // Set subject lines
+ $sub_mem = getMessage('MEMBER_CHANGED_DATA');
+
+ // Output success message
+ $content = "{--MYDATA_MAIL_SENT--}";
+ break;
+
+ default: // Unsupported module!
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
+ $content = "{--UNKNOWN_MODULE--}";
+ break;
+ } // END - switch
+ } else {
+ // Passwords mismatch
+ $content = "{--MEMBER_PASSWORD_ERROR--}";
+ }
+ } else {
+ // Could not load profile
+ $content = "{--MEMBER_CANNOT_LOAD_PROFILE--}";
+ }
+
+ // Send email to user if required
+ if ((!empty($sub_mem)) && (!empty($message))) {
+ // Send member mail
+ sendEmail($content['email'], $sub_mem, $message);
+ } // END - if
+
+ // Send only if no other error has occured
+ if (empty($content)) {
+ if ((!empty($sub_adm)) && (!empty($message_admin))) {
+ // Send admin mail
+ sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
+ } elseif (getConfig('admin_notify') == 'Y') {
+ // Cannot send mails to admin!
+ $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
+ } else {
+ // No mail to admin
+ $content = "{--MYDATA_MAIL_SENT--}";
+ }
+ } // END - if
+
+ // Load template
+ loadTemplate('admin_settings_saved', false, $content);
+}
+
+// Generates a 'selection box' from given array
+function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
+ // Start the output
+ $OUT = '';
+
+ // Prepare output
+ $content = array(
+ 'selection_box' => $OUT,
+ 'module' => getModule(),
+ 'what' => getWhat()
+ );
+
+ // Load template and return it
+ return loadTemplate('select_' . $name . '_box', true, $content);
+}
+
+// Get a module from filename and access level
+function getModuleFromFileName ($file, $accessLevel) {
+ // Default is 'invalid';
+ $modCheck = 'invalid';
+
+ // @TODO This is still very static, rewrite it somehow
+ switch ($accessLevel) {
+ case 'admin':
+ $modCheck = 'admin';
+ break;
+
+ case 'sponsor':
+ case 'guest':
+ case 'member':
+ $modCheck = getModule();
+ break;
+
+ default: // Unsupported file name / access level
+ debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
+ break;
+ }
+
+ // Return result
+ return $modCheck;
+}
+
+// Encodes an URL for adding session id, etc.
+function encodeUrl ($url, $outputMode = '0') {
+ // Do we have already have a PHPSESSID inside? Then it is already converted...
+ if (strpos($url, session_name()) !== false) return $url;
+
+ // Do we have a valid session?
+ if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
+ // Invalid session
+ // Determine right seperator
+ $seperator = '&';
+ if (strpos($url, '?') === false) {
+ // No question mark
+ $seperator = '?';
+ } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
+ // Non-HTML mode
+ $seperator = '&';
+ }
+
+ // Add it to URL
+ if (session_id() != '') {
+ $url .= $seperator . session_name() . '=' . session_id();
+ } // END - if
+ } // END - if
+
+ // Add {?URL?} ?
+ if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
+ // Add it
+ $url = '{?URL?}/' . $url;
+ } // END - if
+
+ // Return the URL
+ return $url;
+}
+
+// Simple check for spider
+function isSpider () {
+ // Get the UA
+ $userAgent = strtolower(detectUserAgent(true));
+
+ // It should not be empty, if so it is better a spider/bot
+ if (empty($userAgent)) return true;
+
+ // Is it a spider?
+ return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
+}
+
//////////////////////////////////////////////////
// AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
//////////////////////////////////////////////////
@@ -3606,7 +3933,7 @@ if (!function_exists('html_entity_decode')) {
if (!function_exists('http_build_query')) {
// Taken from documentation on www.php.net, credits to Marco K. (Germany)
- function http_build_query($data, $prefix='', $sep='', $key='') {
+ function http_build_query($data, $prefix = '', $sep = '', $key = '') {
$ret = array();
foreach ((array)$data as $k => $v) {
if (is_int($k) && $prefix != null) {
@@ -3626,7 +3953,7 @@ if (!function_exists('http_build_query')) {
return implode($sep, $ret);
}
-}// // END - if
+} // END - if
// [EOF]
?>