X-Git-Url: https://git.mxchange.org/?p=mailer.git;a=blobdiff_plain;f=inc%2Ffunctions.php;h=673c8e822c4482a960b7e145b72cd22722adc754;hp=98533a8799a6433ba4fcccbf6e4a935a7a905457;hb=0f3a135204757cc8750262871c8e62c42300acb4;hpb=648afd5e9ca91e878a755fdb5438ac6103a4ac7e diff --git a/inc/functions.php b/inc/functions.php index 98533a8799..e65600e13e 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -6,19 +6,17 @@ * -------------------------------------------------------------------- * * File : functions.php * * -------------------------------------------------------------------- * - * Short description : Many non-MySQL functions (also file access) * + * Short description : Many non-database functions (also file access) * * -------------------------------------------------------------------- * - * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) * + * Kurzbeschreibung : Viele Nicht-Datenbank-Funktionen * * -------------------------------------------------------------------- * * $Revision:: $ * * $Date:: $ * * $Tag:: 0.2.1-FINAL $ * * $Author:: $ * - * Needs to be in all Files and every File needs "svn propset * - * svn:keywords Date Revision" (autoprobset!) at least!!!!!! * * -------------------------------------------------------------------- * * Copyright (c) 2003 - 2009 by Roland Haeder * - * Copyright (c) 2009, 2010 by Mailer Developer Team * + * Copyright (c) 2009 - 2011 by Mailer Developer Team * * For more information visit: http://www.mxchange.org * * * * This program is free software; you can redistribute it and/or modify * @@ -42,183 +40,6 @@ if (!defined('__SECURITY')) { die(); } // END - if -// Output HTML code directly or 'render' it. You addionally switch the new-line character off -function outputHtml ($htmlCode, $newLine = true) { - // Init output - if (!isset($GLOBALS['output'])) { - $GLOBALS['output'] = ''; - } // END - if - - // Do we have HTML-Code here? - if (!empty($htmlCode)) { - // Yes, so we handle it as you have configured - switch (getConfig('OUTPUT_MODE')) { - case 'render': - // That's why you don't need any \n at the end of your HTML code... :-) - if (getPhpCaching() == 'on') { - // Output into PHP's internal buffer - outputRawCode($htmlCode); - - // That's why you don't need any \n at the end of your HTML code... :-) - if ($newLine === true) print("\n"); - } else { - // Render mode for old or lame servers... - $GLOBALS['output'] .= $htmlCode; - - // That's why you don't need any \n at the end of your HTML code... :-) - if ($newLine === true) $GLOBALS['output'] .= "\n"; - } - break; - - case 'direct': - // If we are switching from render to direct output rendered code - if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; } - - // The same as above... ^ - outputRawCode($htmlCode); - if ($newLine === true) print("\n"); - break; - - default: - // Huh, something goes wrong or maybe you have edited config.php ??? - debug_report_bug(__FUNCTION__, __LINE__, '{--FATAL_ERROR--}: {--LANG_NO_RENDER_DIRECT--}'); - break; - } // END - switch - } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) { - // Output cached HTML code - $GLOBALS['output'] = ob_get_contents(); - - // Clear output buffer for later output if output is found - if (!empty($GLOBALS['output'])) { - clearOutputBuffer(); - } // END - if - - // Send all HTTP headers - sendHttpHeaders(); - - // Compile and run finished rendered HTML code - compileFinalOutput(); - - // Output code here, DO NOT REMOVE! ;-) - outputRawCode($GLOBALS['output']); - } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) { - // Send all HTTP headers - sendHttpHeaders(); - - // Compile and run finished rendered HTML code - compileFinalOutput(); - - // Output code here, DO NOT REMOVE! ;-) - outputRawCode($GLOBALS['output']); - } else { - // And flush all headers - flushHeaders(); - } -} - -// Sends out all headers required for HTTP/1.1 reply -function sendHttpHeaders () { - // Used later - $now = gmdate('D, d M Y H:i:s') . ' GMT'; - - // Send HTTP header - sendHeader('HTTP/1.1 ' . getHttpStatus()); - - // General headers for no caching - sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21 - sendHeader('Last-Modified: ' . $now); - sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1 - sendHeader('Pragma: no-cache'); // HTTP/1.0 - sendHeader('Connection: Close'); - sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8'); - sendHeader('Content-Language: ' . getLanguage()); -} - -// Compiles the final output -function compileFinalOutput () { - // Add page header and footer - addPageHeaderFooter(); - - // Do the final compilation - $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']); - - // Extension 'rewrite' installed? - if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) { - $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']); - } // END - if - - // Compress it? - if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) { - // Compress it for HTTP gzip - $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true); - - // Add header - sendHeader('Content-Encoding: gzip'); - } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) { - // Compress it for HTTP deflate - $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9); - - // Add header - sendHeader('Content-Encoding: deflate'); - } - - // Add final length - sendHeader('Content-Length: ' . strlen($GLOBALS['output'])); - - // Flush all headers - flushHeaders(); -} - -// Main compilation loop -function doFinalCompilation ($code, $insertComments = true) { - // Insert comments? (Only valid with HTML templates, of course) - enableTemplateHtml($insertComments); - - // Init counter - $cnt = 0; - - // Compile all out - while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 3)) { - // Init common variables - $content = array(); - $newContent = ''; - - // Compile it - //* DEBUG: */ print '
'.htmlentities($code).'
'.linenumberCode($eval).'
'.htmlentities($newContent).'
' . linenumberCode($eval) . '
' . print_r($content, true) . '
' . print_r($DATA, true) . '
'.print_r($request, true).'
'.print_r($response, true).'
' . $proxyTunnel.'
'; - debug_print_backtrace(); - die('
'; - $debug .= debug_get_printable_backtrace(); - $debug .= '
'.print_r($args,true).',ret='.print_r($ret,true).''); } else { // One parameter call $ret = call_user_func($filterFunction, $value); @@ -2876,7 +1466,7 @@ function handleExtraValues ($filterFunction, $value, $extraValue) { } // Converts timestamp selections into a timestamp -function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) { +function convertSelectionsToEpocheTime (array &$postData, array &$DATA, &$id, &$skip) { // Init test variable $skip = false; $test2 = ''; @@ -2890,7 +1480,7 @@ function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) { $test = substr($id, 0, -3); 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); + $postData[$test] = createEpocheTimeFromSelections($test, $postData); $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]); $GLOBALS['skip_config'][$test] = true; @@ -2942,9 +1532,9 @@ function handleLoginFailures ($accessLevel) { // Ignore zero values if (getSession('mailer_' . $accessLevel . '_failures') > 0) { // Non-guest has login failures found, get both data and prepare it for template - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}"); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . ''); $content = array( - 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'), + 'login_failures' => 'mailer_' . $accessLevel . '_failures', 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2) ); @@ -2977,28 +1567,28 @@ function rebuildCache ($cache, $inc = '', $force = false) { // Include file given? if (!empty($inc)) { // Construct FQFN - $inc = sprintf("inc/loader/load_cache-%s.php", $inc); + $inc = sprintf("inc/loader/load-%s.php", $inc); // Is the include there? if (isIncludeReadable($inc)) { // And rebuild it from scratch - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!"); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!'); loadInclude($inc); } else { - // Include not found! - logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}"); + // Include not found + logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache); } } // END - if } // END - if } // Determines the real remote address -function determineRealRemoteAddress () { +function determineRealRemoteAddress ($remoteAddr = false) { // Is a proxy in use? - if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) { // Proxy was used $address = $_SERVER['HTTP_X_FORWARDED_FOR']; - } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { + } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) { // Yet, another proxy $address = $_SERVER['HTTP_CLIENT_IP']; } else { @@ -3018,9 +1608,11 @@ function determineRealRemoteAddress () { // Adds a bonus mail to the queue // This is a high-level function! -function addNewBonusMail ($data, $mode = '', $output=true) { +function addNewBonusMail ($data, $mode = '', $output = true) { // Use mode from data if not set and availble ;-) - if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode']; + if ((empty($mode)) && (isset($data['mode']))) { + $mode = $data['mode']; + } // END - if // Generate receiver list $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode); @@ -3029,88 +1621,119 @@ function addNewBonusMail ($data, $mode = '', $output=true) { 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'] + $data['subject'], + $data['text'], + $receiver, + $data['points'], + $data['seconds'], + $data['url'], + $data['cat'], + $mode, + $data['receiver'] ); // Mail inserted into bonus pool - if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND')); - } elseif ($output) { + if ($output === true) { + displayMessage('{--ADMIN_BONUS_SEND--}'); + } // END - if + } elseif ($output === true) { // More entered than can be reached! - loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED')); + displayMessage('{--ADMIN_MORE_SELECTED--}'); } else { // Debug log - logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!"); + logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!'); } } // Determines referal id and sets it function determineReferalId () { // Skip this in non-html-mode and outside ref.php - if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false; + if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) { + return false; + } // END - if // Check if refid is set - if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) { + if (isReferalIdValid()) { // This is fine... - } elseif ((isGetRequestParameterSet('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(getRequestParameter('user')); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GLOBALS (' . getReferalId() . ')'); } elseif (isPostRequestParameterSet('refid')) { - // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts) - $GLOBALS['refid'] = secureString(postRequestParameter('refid')); + // Get referal id from POST element refid + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from POST data (' . postRequestParameter('refid') . ')'); + setReferalId(secureString(postRequestParameter('refid'))); } elseif (isGetRequestParameterSet('refid')) { - // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts) - $GLOBALS['refid'] = secureString(getRequestParameter('refid')); + // Get referal id from GET parameter refid + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GET data (' . getRequestParameter('refid') . ')'); + setReferalId(secureString(getRequestParameter('refid'))); } elseif (isGetRequestParameterSet('ref')) { // Set refid=ref (the referal link uses such variable) - $GLOBALS['refid'] = secureString(getRequestParameter('ref')); - } 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')) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using ref from GET data (' . getRequestParameter('refid') . ')'); + setReferalId(secureString(getRequestParameter('ref'))); + } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) { + // The variable user comes from click.php + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using user from GET data (' . getRequestParameter('user') . ')'); + setReferalId(bigintval(getRequestParameter('user'))); + } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) { + // Set session refid as global + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from SESSION data (' . getSession('refid') . ')'); + setReferalId(bigintval(getSession('refid'))); + } elseif (isRandomReferalIdEnabled()) { // Select a random user which has confirmed enougth mails - $GLOBALS['refid'] = determineRandomReferalId(); - } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Checking random referal id'); + setReferalId(determineRandomReferalId()); + } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) { // Set default refid as refid in URL - $GLOBALS['refid'] = getConfig('def_refid'); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')'); + setReferalId(getDefRefid()); } else { // No default id when sql_patches is not installed or none set - $GLOBALS['refid'] = '0'; + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using NULL as refid'); + setReferalId(NULL); } // 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') || (!isValidUserId(getReferalId())) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) { // Default is not found $found = false; // Do we have nickname or userid set? - if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) { + if ((isExtensionActive('nickname')) && (isNicknameUsed(getReferalId()))) { // Nickname in URL, so load the id - $found = fetchUserData($GLOBALS['refid'], 'nickname'); - } elseif ($GLOBALS['refid'] > 0) { + $found = fetchUserData(getReferalId(), 'nickname'); + + // If we found it, use the userid as referal id + if ($found === true) { + // Set the userid as 'refid' + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from user account by nickname (' . getUserData('userid') . ')'); + setReferalId(getUserData('userid')); + } // END - if + } elseif (isValidUserId(getReferalId())) { // Direct userid entered - $found = fetchUserData($GLOBALS['refid']); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using direct userid (' . getReferalId() . ')'); + $found = fetchUserData(getReferalId()); } // Is the record valid? - if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) { + if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) { // No, then reset referal id - $GLOBALS['refid'] = getConfig('def_refid'); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')'); + setReferalId(getDefRefid()); } // END - if // Set cookie - setSession('refid', $GLOBALS['refid']); - } // END - if + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferalId() . ') #1'); + setSession('refid', getReferalId()); + } elseif (!isReferalIdValid()) { + // Not valid! + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not valid referal id (' . getReferalId() . '), setting NULL in session'); + setSession('refid', NULL); + } elseif ((!isSessionVariableSet('refid')) && (isValidUserId(getReferalId()))) { + // Set it from GLOBALS array in session + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferalId() . ') #2'); + setSession('refid', getReferalId()); + } // Return determined refid - return $GLOBALS['refid']; + return getReferalId(); } // Enables the reset mode and runs it @@ -3122,6 +1745,15 @@ function doReset () { runFilterChain('reset'); } +// Enables the reset mode (hourly, weekly and monthly) and runs it +function doHourly () { + // Enable the hourly reset mode + $GLOBALS['hourly_enabled'] = true; + + // Run filters (one always!) + runFilterChain('hourly'); +} + // Our shutdown-function function shutdown () { // Call the filter chain 'shutdown' @@ -3133,7 +1765,7 @@ function shutdown () { SQL_CLOSE(__FUNCTION__, __LINE__); } elseif (!isInstallationPhase()) { // No database link - addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN')); + debug_report_bug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.'); } // Stop executing here @@ -3148,7 +1780,9 @@ function initMemberId () { // Setter for member id function setMemberId ($memberid) { // We should not set member id to zero - if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.'); + if ($memberid == '0') { + debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.'); + } // END - if // Set it secured $GLOBALS['member_id'] = bigintval($memberid); @@ -3174,27 +1808,10 @@ function isMemberIdSet () { return (isset($GLOBALS['member_id'])); } -// Handle message codes from URL -function handleCodeMessage () { - if (isGetRequestParameterSet('code')) { - // Default extension is 'unknown' - $ext = 'unknown'; - - // Is extension given? - if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext'); - - // Convert the 'code' parameter from URL to a human-readable message - $message = getMessageFromErrorCode(getRequestParameter('code')); - - // Load message template - loadTemplate('message', false, $message); - } // END - if -} - -// Setter for extra title -function setExtraTitle ($extraTitle) { - $GLOBALS['extra_title'] = $extraTitle; -} +// Setter for extra title +function setExtraTitle ($extraTitle) { + $GLOBALS['extra_title'] = $extraTitle; +} // Getter for extra title function getExtraTitle () { @@ -3213,74 +1830,6 @@ function isExtraTitleSet () { return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title']))); } -// Generates a 'extension foo inactive' message -function generateExtensionInactiveMessage ($ext_name) { - // Is the extension empty? - if (empty($ext_name)) { - // This should not happen - debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.'); - } // END - if - - // Default message - $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name); - - // Is an admin logged in? - if (isAdmin()) { - // Then output admin message - $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name); - } // END - if - - // Return prepared message - return $message; -} - -// Generates a 'extension foo not installed' message -function generateExtensionNotInstalledMessage ($ext_name) { - // Is the extension empty? - if (empty($ext_name)) { - // This should not happen - debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.'); - } // END - if - - // Default message - $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name); - - // Is an admin logged in? - if (isAdmin()) { - // Then output admin message - $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name); - } // END - if - - // Return prepared message - return $message; -} - -// Generates a message depending on if the extension is not installed or not -// just activated -function generateExtensionInactiveNotInstalledMessage ($ext_name) { - // Init message - $message = ''; - - // Is the extension not installed or just deactivated? - switch (isExtensionInstalled($ext_name)) { - case true; // Deactivated! - $message = generateExtensionInactiveMessage($ext_name); - break; - - case false; // Not installed! - $message = generateExtensionNotInstalledMessage($ext_name); - break; - - default: // Should not happen! - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name)); - $message = sprintf("Invalid state of extension %s detected.", $ext_name); - break; - } // END - switch - - // Return the message - return $message; -} - // 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. @@ -3291,25 +1840,25 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad $excludeArray[] = '.svn'; $excludeArray[] = '.htaccess'; - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!"); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!'); // Init includes $files = array(); // Open directory - $dirPointer = opendir(getConfig('PATH') . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.'); + $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.'); // Read all entries while ($baseFile = readdir($dirPointer)) { // Exclude '.', '..' and entries in $excludeArray automatically if (in_array($baseFile, $excludeArray, true)) { // Exclude them - //* DEBUG: */ outputHtml('excluded=' . $baseFile . ''); + //* DEBUG: */ debugOutput('excluded=' . $baseFile); continue; } // END - if // Construct include filename and FQFN $fileName = $baseDir . $baseFile; - $FQFN = getConfig('PATH') . $fileName; + $FQFN = getPath() . $fileName; // Remove double slashes $FQFN = str_replace('//', '/', $FQFN); @@ -3317,9 +1866,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad // 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: */ debugOutput('baseDir:' . $baseDir); + //* DEBUG: */ debugOutput('baseFile:' . $baseFile); + //* DEBUG: */ debugOutput('FQFN:' . $FQFN); // Exclude this one continue; @@ -3332,47 +1881,44 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad // And skip further processing continue; - } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) { + } elseif (!isFilePrefixFound($baseFile, $prefix)) { // Skip this file - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix); + //* 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); + //* 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!"); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!'); continue; } + // Get file' extension (last 4 chars) + $fileExtension = substr($baseFile, -4, 4); + // Is the file a PHP script or other? - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}"); - if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile); + if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) { // Is this a valid include file? if ($extension == '.php') { // Remove both for extension name $extName = substr($baseFile, strlen($prefix), -4); - // Is the extension valid and active? - if (isExtensionNameValid($extName)) { - // Then add this file - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.'); + // Add file with or without base path + if ($addBaseDir === true) { + // With base path $files[] = $fileName; } else { - // Add non-extension files as well - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.'); - if ($addBaseDir === true) { - $files[] = $fileName; - } else { - $files[] = $baseFile; - } + // No base path + $files[] = $baseFile; } } else { // We found .php file but should not search for them, why? - debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.'); + debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')'); } - } elseif (substr($baseFile, -4, 4) == $extension) { + } elseif ($fileExtension == $extension) { // Other, generic file found $files[] = $fileName; } @@ -3389,6 +1935,12 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad return $files; } +// Checks wether $prefix is found in $fileName +function isFilePrefixFound ($fileName, $prefix) { + // @TODO Find a way to cache this + return (substr($fileName, 0, strlen($prefix)) == $prefix); +} + // Maps a module name into a database table name function mapModuleToTable ($moduleName) { // Map only these, still lame code... @@ -3406,19 +1958,10 @@ function mapModuleToTable ($moduleName) { // Add SQL debug data to array for later output function addSqlToDebug ($result, $sqlString, $timing, $F, $L) { - // Already executed? - if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) { - // Then abort here, we don't need to profile a query twice - return; - } // END - if - - // Remeber this as profiled (or not, but we don't care here) - $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true; - // Do we have cache? if (!isset($GLOBALS['debug_sql_available'])) { // Check it and cache it in $GLOBALS - $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y')); + $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled())); } // END - if // Don't execute anything here if we don't need or ext-other is missing @@ -3426,6 +1969,15 @@ function addSqlToDebug ($result, $sqlString, $timing, $F, $L) { return; } // END - if + // Already executed? + if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) { + // Then abort here, we don't need to profile a query twice + return; + } // END - if + + // Remeber this as profiled (or not, but we don't care here) + $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true; + // Generate record $record = array( 'num_rows' => SQL_NUMROWS($result), @@ -3442,14 +1994,22 @@ function addSqlToDebug ($result, $sqlString, $timing, $F, $L) { // Initializes the cache instance function initCacheInstance () { + // Check for double-initialization + if (isset($GLOBALS['cache_instance'])) { + // This should not happen and must be fixed + debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance'])); + } // END - if + // Load include for CacheSystem class loadIncludeOnce('inc/classes/cachesystem.class.php'); // Initialize cache system only when it's needed $GLOBALS['cache_instance'] = new CacheSystem(); - if ($GLOBALS['cache_instance']->getStatus() != 'done') { + + // Did it work? + if ($GLOBALS['cache_instance']->getStatusCode() != 'done') { // Failed to initialize cache sustem - addFatalMessage(__FUNCTION__, __LINE__, '(' . __LINE__ . '): {--CACHE_CANNOT_INITIALIZE--}'); + debug_report_bug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode()); } // END - if } @@ -3468,294 +2028,11 @@ function getMessageFromIndexedArray ($message, $pos, $array) { return $ret; } -// Print code with line numbers -function linenumberCode ($code) { - if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code; - $count_lines = count($codeE); - - $r = 'Line | Code:'; - foreach($codeE as $line => $c) { - $r .= ''; - if ($count_lines == 1) { - $r .= 1; - } else { - $r .= ($line == ($count_lines - 1)) ? '' : ($line+1); - } - $r .= '|'; - - // Add code - $r .= '' . htmlentities($c) . ''; - } - - return '' . $r . ''; -} - // Convert ';' to ', ' for e.g. receiver list 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_MAILER'); - } elseif ((!isInstalled()) || (!isAdminRegistered())) { - // Installation mode - $pageTitle = getMessage('INSTALLATION_OF_MAILER'); - } else { - // Configuration not found! - $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE'); - - // Do not add the fatal message in installation mode - if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __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 = generateCacheFqfn($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 = generateCacheFqfn($template); - - // 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 = generateCacheFqfn($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 = encodeHashForCookie(getUserData('password')); - - // Does the hash match or should we change it? - if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) { - // Load the data - $content = getUserDataArray(); - - // 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').": ".postRequestParameter('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(postRequestParameter('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 = '', $extraName = '') { - // Start the output - $OUT = ' -{--PLEASE_SELECT--}'; - - // Walk through all options - foreach ($options as $option) { - // Add the entry - if (empty($optionContent)) { - // ... from template - $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option); - } else { - // Direct HTML code - $OUT .= '' . $option[$optionContent] . ''; - } - } // END - foreach - - // Finish selection box - $OUT .= ''; - - // Prepare output - $content = array( - 'selection_box' => $OUT, - 'module' => getModule(), - 'what' => getWhat() - ); - - // Load template and return it - return loadTemplate('select_' . $name . $extraName . '_box', true, $content); -} - // Get a module from filename and access level function getModuleFromFileName ($file, $accessLevel) { // Default is 'invalid'; @@ -3785,7 +2062,10 @@ function getModuleFromFileName ($file, $accessLevel) { // Encodes an URL for adding session id, etc. function encodeUrl ($url, $outputMode = '0') { // Do we have already have a PHPSESSID inside or view.php is called? Then abort here - if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url; + if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) { + // Raw output mode detected or session_name() found in URL + return $url; + } // END - if // Do we have a valid session? if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) { @@ -3795,8 +2075,8 @@ function encodeUrl ($url, $outputMode = '0') { if (strpos($url, '?') === false) { // No question mark $seperator = '?'; - } elseif ((getOutputMode() != '0') || ($outputMode != '0')) { - // Non-HTML mode + } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) { + // Non-HTML mode (or forced non-HTML mode $seperator = '&'; } @@ -3807,7 +2087,7 @@ function encodeUrl ($url, $outputMode = '0') { } // 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://')) { + if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) { // Add it $url = '{?URL?}/' . $url; } // END - if @@ -3818,74 +2098,19 @@ function encodeUrl ($url, $outputMode = '0') { // Simple check for spider function isSpider () { - // Get the UA - $userAgent = strtolower(detectUserAgent(true)); + // Get the UA and trim it down + $userAgent = trim(strtolower(detectUserAgent(true))); // It should not be empty, if so it is better a spider/bot - if (empty($userAgent)) return true; + if (empty($userAgent)) { + // It is a spider/bot + return true; + } // END - if // Is it a spider? return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false)); } -// Prepares the header for HTML output -function loadHtmlHeader () { - // Run two filters: - // 1.) pre_page_header (mainly loads the page_header template and includes - // meta description) - runFilterChain('pre_page_header'); - - // Here can be something be added, but normally one of the two filters - // around this line should do the job for you. - - // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and - // to close the head-tag) - // Include more header data here - runFilterChain('post_page_header'); -} - -// Adds page header and footer to output array element -function addPageHeaderFooter () { - // Init output - $OUT = ''; - - // Add them all together. This is maybe to simple - foreach (array('page_header', 'output', 'page_footer') as $pagePart) { - // Add page part if set - if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart]; - } // END - foreach - - // Transfer $OUT to 'output' - $GLOBALS['output'] = $OUT; -} - -// Generates meta description for current module and 'what' value -function generateMetaDescriptionCode () { - // Only include from guest area and if sql_patches has correct version - if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) { - // Construct dynamic description - $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()); - - // Output it directly - $GLOBALS['page_header'] .= ''; - } // END - if - - // Remove depth - unset($GLOBALS['ref_level']); -} - -// Generates an FQFN for template cache from the given template name -function generateCacheFqfn ($template) { - // Is this cached? - if (!isset($GLOBALS['template_cache_fqfn'][$template])) { - // Generate the FQFN - $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template); - } // END - if - - // Return it - return $GLOBALS['template_cache_fqfn'][$template]; -} - // Function to search for the last modified file function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') { // Get dir as array @@ -3900,7 +2125,7 @@ function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') { // Walk through all entries foreach ($ds as $d) { // Generate proper FQFN - $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d); + $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d); // Is it a file and readable? //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d); @@ -3923,21 +2148,6 @@ function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') { } // END - foreach } -// "Fixes" null or empty string to count of dashes -function fixNullEmptyToDashes ($str, $num) { - // Use str as default - $return = $str; - - // Is it empty? - if ((is_null($str)) || (trim($str) == '')) { - // Set it - $return = str_repeat('-', $num); - } // END - if - - // Return final string - return $return; -} - // Handles the braces [] of a field (e.g. value of 'name' attribute) function handleFieldWithBraces ($field) { // Are there braces [] at the end? @@ -3960,40 +2170,345 @@ function handleFieldWithBraces ($field) { return $field; } -////////////////////////////////////////////////// -// AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS // -////////////////////////////////////////////////// -// -if (!function_exists('html_entity_decode')) { - // Taken from documentation on www.php.net - function html_entity_decode ($string) { - $trans_tbl = get_html_translation_table(HTML_ENTITIES); - $trans_tbl = array_flip($trans_tbl); - return strtr($string, $trans_tbl); +// Converts a zero or NULL to word 'NULL' +function makeZeroToNull ($number) { + // Is it a valid username? + if ((!is_null($number)) && ($number > 0)) { + // Always secure it + $number = bigintval($number); + } else { + // Is not valid or zero + $number = 'NULL'; } -} // END - if -if (!function_exists('http_build_query')) { - // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder - function http_build_query($data, $prefix = '', $sep = '', $key = '') { - $ret = array(); - foreach ((array)$data as $k => $v) { - if (is_int($k) && $prefix != null) { - $k = urlencode($prefix . $k); - } // END - if + // Return it + return $number; +} - if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']'; +// Converts NULL into number zero +function makeNullToZero ($number) { + // Is this a NULL? + if ((is_null($number)) || (empty($number))) { + // Simply set it + $number = '0'; + } // END - if - if (is_array($v) || is_object($v)) { - array_push($ret, http_build_query($v, '', $sep, $k)); - } else { - array_push($ret, $k.'='.urlencode($v)); - } + // Return it + return $number; +} + +// Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString +// Note: This function is cached +function capitalizeUnderscoreString ($str) { + // Do we have cache? + if (!isset($GLOBALS[__FUNCTION__][$str])) { + // Init target string + $capitalized = ''; + + // Explode it with the underscore, but rewrite dashes to underscore before + $strArray = explode('_', str_replace('-', '_', $str)); + + // "Walk" through all elements and make them lower-case but first upper-case + foreach ($strArray as $part) { + // Capitalize the string part + $capitalized .= firstCharUpperCase($part); } // END - foreach - if (empty($sep)) $sep = ini_get('arg_separator.output'); + // Store the converted string in cache array + $GLOBALS[__FUNCTION__][$str] = $capitalized; + } // END - if + + // Return cache + return $GLOBALS[__FUNCTION__][$str]; +} + +// Generate admin links for mail order +// mailType can be: 'mid' or 'bid' +function generateAdminMailLinks ($mailType, $mailId) { + // Init variables + $OUT = ''; + $table = ''; + + // Default column for mail status is 'data_type' + // @TODO Rename column data_type to e.g. mail_status + $statusColumn = 'data_type'; + + // Which mail do we have? + switch ($mailType) { + case 'bid': // Bonus mail + $table = 'bonus'; + break; + + case 'mid': // Member mail + $table = 'pool'; + break; + + default: // Handle unsupported types + logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.'); + $OUT = '{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}'; + break; + } // END - switch + + // Is the mail type supported? + if (!empty($table)) { + // Query for the mail + $result = SQL_QUERY_ESC("SELECT `id`,`%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1", + array( + $statusColumn, + $table, + bigintval($mailId) + ), __FILE__, __LINE__); + + // Do we have one entry there? + if (SQL_NUMROWS($result) == 1) { + // Load the entry + $content = SQL_FETCHARRAY($result); + + // Add output and type + $content['type'] = $mailType; + $content['__output'] = ''; + + // Filter all data + $content = runFilterChain('generate_admin_mail_links', $content); + + // Get output back + $OUT = $content['__output']; + } // END - if + + // Free result + SQL_FREERESULT($result); + } // END - if + + // Return generated HTML code + return $OUT; +} + - return implode($sep, $ret); +/** + * Determine if a string can represent a number in hexadecimal + * + * @param $hex A string to check if it is hex-encoded + * @return $foo True if the string is a hex, otherwise false + * @author Marques Johansson + * @link http://php.net/manual/en/function.http-chunked-decode.php#89786 + */ +function isHexadecimal ($hex) { + // Make it lowercase + $hex = strtolower(trim(ltrim($hex, '0'))); + + // Fix empty strings to zero + if (empty($hex)) { + $hex = 0; + } // END - if + + // Simply compare decode->encode result with original + return ($hex == dechex(hexdec($hex))); +} + +/** + * Replace "\r" with "[r]" and "\n" with "[n]" and add a final new-line to make + * them visible to the developer. Use this function to debug e.g. buggy HTTP + * response handler functions. + * + * @param $str String to overwork + * @return $str Overworked string + */ +function replaceReturnNewLine ($str) { + return str_replace("\r", '[r]', str_replace("\n", '[n] +', $str)); +} + +// Converts a given string by splitting it up with given delimiter similar to +// explode(), but appending the delimiter again +function stringToArray ($delimiter, $string) { + // Init array + $strArray = array(); + + // "Walk" through all entries + foreach (explode($delimiter, $string) as $split) { + // Append the delimiter and add it to the array + $strArray[] = $split . $delimiter; + } // END - foreach + + // Return array + return $strArray; +} + +// Detects the prefix 'mb_' if a multi-byte string is given +function detectMultiBytePrefix ($str) { + // Default is without multi-byte + $mbPrefix = ''; + + // Detect multi-byte (strictly) + if (mb_detect_encoding($str, 'auto', true) !== false) { + // With multi-byte encoded string + $mbPrefix = 'mb_'; + } // END - if + + // Return the prefix + return $mbPrefix; +} + +// Searches the given array for a sub-string match and returns all found keys in an array +function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) { + // Init array for all found keys + $keys = array(); + + // Now check all entries + foreach ($needles as $key => $needle) { + // Do we have found a partial string? + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset); + if (strpos($heystack, $needle, $offset) !== false) { + // Add the found key + $keys[] = $key; + } // END - if + } // END - foreach + + // Return the array + return $keys; +} + +// Determines database column name from given subject and locked +function determinePointsColumnFromSubjectLocked ($subject, $locked) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!'); + // Default is 'normal' points + $pointsColumn = 'points'; + + // Which points, locked or normal? + if ($locked === true) { + $pointsColumn = 'locked_points'; + } // END - if + + // Prepare array for filter + $filterData = array( + 'subject' => $subject, + 'locked' => $locked, + 'column' => $pointsColumn + ); + + // Run the filter + $filterData = runFilterChain('determine_points_column_name', $filterData); + + // Extract column name from array + $pointsColumn = $filterData['column']; + + // Return it + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!'); + return $pointsColumn; +} + +// Setter for referal id (no bigintval, or nicknames will fail!) +function setReferalId ($refid) { + $GLOBALS['refid'] = $refid; +} + +// Checks if 'refid' is valid +function isReferalIdValid () { + return ((isset($GLOBALS['refid'])) && (getReferalId() !== NULL) && (getReferalId() > 0)); +} + +// Getter for referal id +function getReferalId () { + return $GLOBALS['refid']; +} + +// Converts a boolean variable into 'Y' for true and 'N' for false +function convertBooleanToYesNo ($boolean) { + // Default is 'N' + $converted = 'N'; + if ($boolean === true) { + // Set 'Y' + $converted = 'Y'; + } // END - if + + // Return it + return $converted; +} + +// Translates task type to a human-readable version +function translateTaskType ($taskType) { + // Construct message id + $messageId = 'ADMIN_TASK_TYPE_' . strtoupper($taskType) . ''; + + // Is the message id there? + if (isMessageIdValid($messageId)) { + // Then construct message + $message = '{--' . $messageId . '--}'; + } else { + // Else it is an unknown task type + $message = '{%message,ADMIN_TASK_TYPE_UNKNOWN=' . $taskType . '%}'; + } // END - if + + // Return message + return $message; +} + +// Translates points subject to human-readable +function translatePointsSubject ($subject) { + // Construct message id + $messageId = 'POINTS_SUBJECT_' . strtoupper($subject) . ''; + + // Is the message id there? + if (isMessageIdValid($messageId)) { + // Then construct message + $message = '{--' . $messageId . '--}'; + } else { + // Else it is an unknown task type + $message = '{%message,POINTS_SUBJECT_UNKNOWN=' . $subject . '%}'; + } // END - if + + // Return message + return $message; +} + +// "Translates" 'true' to true and 'false' to false +function convertStringToBoolean ($str) { + // Trim it lower-case for validation + $str = trim(strtolower($str)); + + // Is it valid? + if (!in_array($str, array('true', 'false'))) { + // Not valid! + debug_report_bug(__FUNCTION__, __LINE__, 'str=' . $str . ' is not true/false'); + } // END - if + + // Return it + return (($str == 'true') ? true : false); +} + +/** + * "Makes" a variable in given string parseable, this function will throw an + * error if the first character is not a dollar sign. + * + * @param $varString String which contains a variable + * @return $return String with added single quotes for better parsing + */ +function makeParseableVariable ($varString) { + // The first character must be a dollar sign + if (substr($varString, 0, 1) != '$') { + // Please report this + debug_report_bug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.'); + } // END - if + + // Do we have cache? + if (!isset($GLOBALS[__FUNCTION__][$varString])) { + // Snap them in, if [,] are there + $GLOBALS[__FUNCTION__][$varString] = str_replace('[', "['", str_replace(']', "']", $varString)); + } // END - if + + // Return cache + return $GLOBALS[__FUNCTION__][$varString]; +} + +//----------------------------------------------------------------------------- +// Automatically re-created functions, all taken from user comments on www.php.net +//----------------------------------------------------------------------------- +if (!function_exists('html_entity_decode')) { + // Taken from documentation on www.php.net + function html_entity_decode ($string) { + $trans_tbl = get_html_translation_table(HTML_ENTITIES); + $trans_tbl = array_flip($trans_tbl); + return strtr($string, $trans_tbl); } } // END - if
'.print_r($ret,true).'