X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=inc%2Ffunctions.php;h=5ebcaebce1fc5211496031264048ccf9a9deb519;hb=b1cf96c4a5a63a1d334119a0681e5fbf68edf527;hp=6737f4580844963e85acfa5ea4bbd88aec7d6eb9;hpb=40547996bdb16c5d2c507cb7111ae993a3fcebb9;p=mailer.git
diff --git a/inc/functions.php b/inc/functions.php
index 6737f45808..5ebcaebce1 100644
--- a/inc/functions.php
+++ b/inc/functions.php
@@ -1,7 +1,7 @@
{--FATAL_ERROR--}: {--LANG_NO_RENDER_DIRECT--}');
break;
- }
- } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
+ } // END - switch
+ } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
// Headers already sent?
if (headers_sent()) {
// Log this error
- DEBUG_LOG(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
+ logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
// Trigger an user error
debug_report_bug('Headers are already sent!');
} // END - if
// Output cached HTML code
- $OUTPUT = ob_get_contents();
+ $GLOBALS['output'] = ob_get_contents();
// Clear output buffer for later output if output is found
- if (!empty($OUTPUT)) {
+ if (!empty($GLOBALS['output'])) {
clearOutputBuffer();
} // END - if
- // Send HTTP header
- sendHeader('HTTP/1.1 200');
-
- // Used later
- $now = gmdate('D, d M Y H:i:s') . ' GMT';
-
- // General headers for no caching
- sendHeader('Expired: ' . $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');
-
// Extension 'rewrite' installed?
- if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
- $OUTPUT = rewriteLinksInCode($OUTPUT);
+ if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
+ $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
} // END - if
// Compile and run finished rendered HTML code
- while (strpos($OUTPUT, '{!') > 0) {
- // Replace _MYSQL_PREFIX
- $OUTPUT = str_replace('{!_MYSQL_PREFIX!}', getConfig('_MYSQL_PREFIX'), $OUTPUT);
-
- // Prepare the content and eval() it...
- $newContent = '';
- $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
- eval($eval);
-
- // Was that eval okay?
- if (empty($newContent)) {
- // Something went wrong!
- app_die(__FUNCTION__, __LINE__, 'Evaluation error:
' . htmlentities($eval) . ' ');
- } // END - if
- $OUTPUT = $newContent;
- } // END - while
+ compileFinalOutput();
+
+ // Send all HTTP headers
+ sendHttpHeaders();
// Output code here, DO NOT REMOVE! ;-)
- outputRawCode($OUTPUT);
- } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
+ outputRawCode($GLOBALS['output']);
+ } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
// Rewrite links when rewrite extension is active
- if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
- $OUTPUT = rewriteLinksInCode($OUTPUT);
+ if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
+ $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
} // END - if
// Compile and run finished rendered HTML code
- while (strpos($OUTPUT, '{!') > 0) {
- $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
- eval($eval);
- } // END - while
+ compileFinalOutput();
+
+ // Send all HTTP headers
+ sendHttpHeaders();
// Output code here, DO NOT REMOVE! ;-)
- outputRawCode($OUTPUT);
+ outputRawCode($GLOBALS['output']);
}
}
+// 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 200');
+
+ // General headers for no caching
+ sendHeader('Expired: ' . $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 () {
+ // Init counter
+ $cnt = '0';
+
+ // Compile all out
+ while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
+ // Init common variables
+ $content = array();
+ $newContent = '';
+
+ // Compile it
+ $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
+ eval($eval);
+
+ // Was that eval okay?
+ if (empty($newContent)) {
+ // Something went wrong!
+ debug_report_bug('Evaluation error:' . linenumberCode($eval) . ' ');
+ } // END - if
+ $GLOBALS['output'] = $newContent;
+
+ // Count round
+ $cnt++;
+ } // END - while
+
+ // Add final length
+ sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
+}
+
// Output the raw HTML code
-function outputRawCode ($HTML) {
+function outputRawCode ($htmlCode) {
// Output stripped HTML code to avoid broken JavaScript code, etc.
- print(stripslashes(stripslashes($HTML)));
+ print(str_replace('{BACK}', "\\", $htmlCode));
- // Flush the output if only constant('_OB_CACHING') is not 'on'
- if (constant('_OB_CACHING') != 'on') {
+ // Flush the output if only getPhpCaching() is not 'on'
+ if (getPhpCaching() != 'on') {
// Flush it
flush();
} // END - if
@@ -182,7 +204,7 @@ function getFatalArray () {
}
// Add a fatal error message to the queue array
-function addFatalMessage ($F, $L, $message, $extra='') {
+function addFatalMessage ($F, $L, $message, $extra = '') {
if (is_array($extra)) {
// Multiple extras for a message with masks
$message = call_user_func_array('sprintf', $extra);
@@ -195,13 +217,14 @@ function addFatalMessage ($F, $L, $message, $extra='') {
$GLOBALS['fatal_messages'][] = $message;
// Log fatal messages away
- DEBUG_LOG($F, $L, " message={$message}");
+ debug_report_bug($message);
+ logDebugMessage($F, $L, 'Fatal error message: ' . $message);
}
// Getter for total fatal message count
function getTotalFatalErrors () {
// Init coun
- $count = 0;
+ $count = '0';
// Do we have at least the first entry?
if (!empty($GLOBALS['fatal_messages'][0])) {
@@ -214,117 +237,245 @@ function getTotalFatalErrors () {
}
// Load a template file and return it's content (only it's name; do not use ' or ")
-function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
+function loadTemplate ($template, $return = false, $content = array()) {
// @TODO Remove this sanity-check if all is fine
if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
- // Prepare IP number and User Agent
- $REMOTE_ADDR = detectRemoteAddr();
- $HTTP_USER_AGENT = detectUserAgent();
+ // @TODO Try to rewrite all $DATA to $content
+ global $DATA;
- // Add more variables which you want to use in your template files
- global $DATA, $username;
+ // Do we have cache?
+ if (isTemplateCached($template)) {
+ // Evaluate the cache
+ eval(readTemplateCache($template));
+ } elseif (!isset($GLOBALS['template_eval'][$template])) {
+ // Add more variables which you want to use in your template files
+ $username = getUsername();
- // Make all template names lowercase
- $template = strtolower($template);
+ // Make all template names lowercase
+ $template = strtolower($template);
- // Count the template load
- incrementConfigEntry('num_templates');
+ // Init some data
+ $ret = '';
+ if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
- // Init some data
- $ret = '';
- if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
+ // Base directory
+ $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
+ $extraPath = detectExtraTemplatePath($template);;
- // Generate date/time string
- $date_time = generateDateTime(time(), '1');
+ ////////////////////////
+ // Generate file name //
+ ////////////////////////
+ $FQFN = $basePath . $extraPath . $template . '.tpl';
- // Is content an array
- if (is_array($content)) $content['date_time'] = $date_time;
+ // Does the special template exists?
+ if (!isFileReadable($FQFN)) {
+ // Reset to default template
+ $FQFN = $basePath . $template . '.tpl';
+ } // END - if
- // @DEPRECATED Try to rewrite the if() condition
- if ($template == 'member_support_form') {
- // Support request of a member
- $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
- array(getUserId()), __FUNCTION__, __LINE__);
+ // Now does the final template exists?
+ if (isFileReadable($FQFN)) {
+ // Count the template load
+ incrementConfigEntry('num_templates');
+
+ // The local file does exists so we load it. :)
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
+
+ // Do we have to compile the code?
+ $ret = '';
+ if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
+ // Normal HTML output?
+ if (getOutputMode() == '0') {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = '\n" . $GLOBALS['tpl_content'] . '\n";
+
+ // Prepare eval() command
+ $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
+ } elseif (substr($template, 0, 3) == 'js_') {
+ // JavaScripts don't like entities and timings
+ $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
+ } else {
+ // Prepare eval() command, other output doesn't like entities, maybe
+ $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
+ }
+ } else {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = '\n" . $GLOBALS['tpl_content'] . '\n";
+ $eval = '$ret = "' . escapeQuotes($ret) . '";';
+ } // END - if
- // Is content an array?
- if (is_array($content)) {
- // Merge data
- $content = merge_array($content, SQL_FETCHARRAY($result));
+ // Cache the eval() command here
+ $GLOBALS['template_eval'][$template] = $eval;
- // Translate gender
- $content['gender'] = translateGender($content['gender']);
+ // Eval the code
+ eval($GLOBALS['template_eval'][$template]);
+ } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
+ // Only admins shall see this warning or when installation mode is active
+ $ret = '{--TEMPLATE_404--}
+(' . $template . ')
+
+{--TEMPLATE_CONTENT--}
+' . print_r($content, true) . '
+{--TEMPLATE_DATA--}
+' . print_r($DATA, true) . '
+ ';
} else {
- // @DEPRECATED
- // @TODO Find all templates which are using these direct variables and rewrite them.
- // @TODO After this step is done, this else-block is history
- list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
-
- // Translate gender
- $gender = translateGender($gender);
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
+ // No file!
+ $GLOBALS['template_eval'][$template] = '404';
}
+ } else {
+ // Eval the code
+ eval($GLOBALS['template_eval'][$template]);
+ }
- // Free result
- SQL_FREERESULT($result);
- } // END - if
+ // Do we have some content to output or return?
+ if (!empty($ret)) {
+ // Not empty so let's put it out! ;)
+ if ($return === true) {
+ // Return the HTML code
+ return $ret;
+ } else {
+ // Output directly
+ outputHtml($ret);
+ }
+ } elseif (isDebugModeEnabled()) {
+ // Warning, empty output!
+ return 'E:' . $template . ',content=' . print_r($content, true) . ' ';
+ }
+}
- // Base directory
- $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
- $mode = '';
+// Detects the extra template path from given template name
+function detectExtraTemplatePath ($template) {
+ // Default is empty
+ $extraPath = '';
// Check for admin/guest/member templates
- if (strpos($template, 'admin_') > -1) {
+ if (substr($template, 0, 6) == 'admin_') {
// Admin template found
- $mode = 'admin/';
- } elseif (strpos($template, 'guest_') > -1) {
+ $extraPath = 'admin/';
+ } elseif (substr($template, 0, 6) == 'guest_') {
// Guest template found
- $mode = 'guest/';
- } elseif (strpos($template, 'member_') > -1) {
+ $extraPath = 'guest/';
+ } elseif (substr($template, 0, 7) == 'member_') {
// Member template found
- $mode = 'member/';
- } elseif (strpos($template, 'install_') > -1) {
+ $extraPath = 'member/';
+ } elseif (substr($template, 0, 8) == 'install_') {
// Installation template found
- $mode = 'install/';
- } elseif (strpos($template, 'ext_') > -1) {
+ $extraPath = 'install/';
+ } elseif (substr($template, 0, 4) == 'ext_') {
// Extension template found
- $mode = 'ext/';
- } elseif (strpos($template, 'la_') > -1) {
+ $extraPath = 'ext/';
+ } elseif (substr($template, 0, 3) == 'la_') {
// 'Logical-area' template found
- $mode = 'la/';
- } elseif (strpos($template, 'js_') > -1) {
+ $extraPath = 'la/';
+ } elseif (substr($template, 0, 3) == 'js_') {
// JavaScript template found
- $mode = 'js/';
+ $extraPath = 'js/';
+ } elseif (substr($template, 0, 5) == 'menu_') {
+ // Menu template found
+ $extraPath = 'menu/';
} else {
// Test for extension
$test = substr($template, 0, strpos($template, '_'));
- if (EXT_IS_ACTIVE($test)) {
+
+ // Probe for valid extension name
+ if (isExtensionNameValid($test)) {
// Set extra path to extension's name
- $mode = $test . '/';
+ $extraPath = $test . '/';
} // END - if
}
- ////////////////////////
- // Generate file name //
- ////////////////////////
- $FQFN = $basePath . $mode . $template . '.tpl';
-
- if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
- // Select what depended header/footer template file for admin/guest/member area
- $file2 = sprintf("%s%s%s_%s.tpl",
- $basePath,
- $mode,
- $template,
- getWhat()
- );
+ // Return result
+ return $extraPath;
+}
- // Probe for it...
- if (isFileReadable($file2)) $FQFN = $file2;
+// Loads an email template and compiles it
+function loadEmailTemplate ($template, $content = array(), $UID = '0') {
+ global $DATA;
+
+ // Make sure all template names are lowercase!
+ $template = strtolower($template);
- // Remove variable from memory
- unset($file2);
+ // Default 'nickname' if extension is not installed
+ $nick = '---';
+
+ // Prepare IP number and User Agent
+ $REMOTE_ADDR = detectRemoteAddr();
+ $HTTP_USER_AGENT = detectUserAgent();
+
+ // Default admin
+ $ADMIN = getConfig('MAIN_TITLE');
+
+ // Is the admin logged in?
+ if (isAdmin()) {
+ // Get admin id
+ $adminId = getCurrentAdminId();
+
+ // Load Admin data
+ $ADMIN = getAdminEmail($adminId);
+ } // END - if
+
+ // Neutral email address is default
+ $email = getConfig('WEBMASTER');
+
+ // Expiration in a nice output format
+ // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
+ if (getConfig('auto_purge') == '0') {
+ // Will never expire!
+ $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
+ } else {
+ // Create nice date string
+ $EXPIRATION = createFancyTime(getConfig('auto_purge'));
+ }
+
+ // Is content an array?
+ if (is_array($content)) {
+ // Add expiration to array, $EXPIRATION is now deprecated!
+ $content['expiration'] = $EXPIRATION;
+ } // END - if
+
+ // Load user's data
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):UID={$UID},template={$template},content[]=".gettype($content).' ');
+ if (($UID > 0) && (is_array($content))) {
+ // If nickname extension is installed, fetch nickname as well
+ if (isNicknameUsed($UID)) {
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):NICKNAME! ");
+ // Load by nickname
+ fetchUserData($UID, 'nickname');
+ } else {
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):NO-NICK! ");
+ /// Load by userid
+ fetchUserData($UID);
+ }
+
+ // Merge data if valid
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - PRE ");
+ if (isUserDataValid()) {
+ $content = merge_array($content, getUserDataArray());
+ } // END - if
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - AFTER ");
} // END - if
+ // Translate M to male or F to female if present
+ if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
+
+ // Overwrite email from data if present
+ if (isset($content['email'])) $email = $content['email'];
+
+ // Store email for some functions in global data array
+ // @TODO Do only use $contentn, not $DATA or raw variables
+ $DATA['email'] = $email;
+
+ // Base directory
+ $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
+
+ // Detect extra path
+ $extraPath = detectExtraTemplatePath($template);
+
+ // Generate full FQFN
+ $FQFN = $basePath . $extraPath . $template . '.tpl';
+
// Does the special template exists?
if (!isFileReadable($FQFN)) {
// Reset to default template
@@ -332,155 +483,126 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
} // END - if
// Now does the final template exists?
+ $newContent = '';
if (isFileReadable($FQFN)) {
// The local file does exists so we load it. :)
- $tmpl_file = readFromFile($FQFN);
-
- // Replace ' to our own chars to preventing them being quoted
- while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
-
- // Do we have to compile the code?
- $ret = '';
- if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
- // Compile it
- $eval = "\$ret = \"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
- eval($eval);
- // NEW WAY: $ret = str_replace("\$content", "\$GLOBALS[compile][".$template."]", $tmpl_file);
- // NEW WAY: $ret = str_replace("\$DATA", "\$GLOBALS[data][".$template."]", $ret);
- // NEW WAY: $GLOBALS['compile'][$template] = $content;
- // NEW WAY: $GLOBALS['data'][$template] = $DATA;
- } else {
- // Simply return loaded code
- $ret = $tmpl_file;
- }
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
- // Normal HTML output?
- if ($GLOBALS['output_mode'] == 0) {
- // Add surrounding HTML comments to help finding bugs faster
- $ret = "\n" . $ret . "\n";
- } // END - if
- } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
- // Only admins shall see this warning or when installation mode is active
- $ret = "{--TEMPLATE_404--}
-(".basename($FQFN).")
-
+ // Run code
+ $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
+ eval($GLOBALS['tpl_content']);
+ } elseif (!empty($template)) {
+ // Template file not found!
+ $newContent = '{--TEMPLATE_404--}: ' . $template . '
{--TEMPLATE_CONTENT--}
-".print_r($content, true)."
+' . print_r($content, true) . '
{--TEMPLATE_DATA--}
-".print_r($DATA, true)."
- ";
+' . print_r($DATA, true) . '
+ ';
+
+ // Debug mode not active? Then remove the HTML tags
+ if (!isDebugModeEnabled()) $newContent = secureString($newContent);
+ } else {
+ // No template name supplied!
+ $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
}
+ // Is there some content?
+ if (empty($newContent)) {
+ // Compiling failed
+ $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
+
+ // Add last error if the required function exists
+ if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
+ } // END - if
+
// Remove content and data
unset($content);
unset($DATA);
- // Do we have some content to output or return?
- if (!empty($ret)) {
- // Not empty so let's put it out! ;)
- if ($return === true) {
- // Return the HTML code
- return $ret;
- } else {
- // Output direct
- OUTPUT_HTML($ret);
- }
- } elseif (isDebugModeEnabled()) {
- // Warning, empty output!
- return "E:" . $template." \n";
- }
+ // Return content
+ return $newContent;
}
// Send mail out to an email address
-function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):TO={$toEmail},SUBJECT={$subject} ");
+function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):TO={$toEmail},SUBJECT={$subject} ");
// Compile subject line (for POINTS constant etc.)
- $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
- eval($eval);
+ eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
// Set from header
if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
// Value detected, is the message extension installed?
// @TODO Extension 'msg' does not exist
- if (EXT_IS_ACTIVE('msg')) {
- ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
+ if (isExtensionActive('msg')) {
+ ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
return;
} else {
- // Load email address
- $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
- array(bigintval($toEmail)), __FUNCTION__, __LINE__);
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):numRows=".SQL_NUMROWS($result_email)." ");
-
// Does the user exist?
- if (SQL_NUMROWS($result_email)) {
- // Load email address
- list($toEmail) = SQL_FETCHROW($result_email);
+ if (fetchUserData($toEmail)) {
+ // Get the email
+ $toEmail = getUserData('email');
} else {
// Set webmaster
$toEmail = getConfig('WEBMASTER');
}
-
- // Free result
- SQL_FREERESULT($result_email);
}
} elseif ($toEmail == '0') {
// Is the webmaster!
$toEmail = getConfig('WEBMASTER');
}
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):TO={$toEmail} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):TO={$toEmail} ");
// Check for PHPMailer or debug-mode
if (!checkPhpMailerUsage()) {
// Not in PHPMailer-Mode
if (empty($mailHeader)) {
// Load email header template
- $mailHeader = LOAD_EMAIL_TEMPLATE('header');
+ $mailHeader = loadEmailTemplate('header');
} else {
// Append header
- $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
+ $mailHeader .= loadEmailTemplate('header');
}
} elseif (isDebugModeEnabled()) {
if (empty($mailHeader)) {
// Load email header template
- $mailHeader = LOAD_EMAIL_TEMPLATE('header');
+ $mailHeader = loadEmailTemplate('header');
} else {
// Append header
- $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
+ $mailHeader .= loadEmailTemplate('header');
}
}
// Compile "TO"
- $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
- eval($eval);
+ eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
// Compile "MSG"
- $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
- eval($eval);
+ eval("\$message = \"".compileRawCode(escapeQuotes($message))."\";");
// Fix HTML parameter (default is no!)
- if (empty($HTML)) $HTML = 'N';
+ if (empty($isHtml)) $isHtml = 'N';
if (isDebugModeEnabled()) {
// In debug mode we want to display the mail instead of sending it away so we can debug this part
- OUTPUT_HTML("
-".htmlentities(trim($mailHeader))."
-To : " . $toEmail."
-Subject : " . $subject."
-Message : " . $message."
- \n");
- } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
+ outputHtml('
+Headers : ' . str_replace('<', '<', str_replace('>', '>', secureString(trim($mailHeader)))) . '
+To : ' . $toEmail . '
+Subject : ' . $subject . '
+Message : ' . $message . '
+ ');
+ } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
// Send mail as HTML away
sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
} elseif (!empty($toEmail)) {
// Send Mail away
sendRawEmail($toEmail, $subject, $message, $mailHeader);
- } elseif ($HTML == 'N') {
+ } elseif ($isHtml != 'Y') {
// Problem found!
sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
}
}
-// Check if legacy or PHPMailer command
+// Check to use wether legacy mail() command or PHPMailer class
// @TODO Rewrite this to an extension 'smtp'
// @private
function checkPhpMailerUsage() {
@@ -489,6 +611,12 @@ function checkPhpMailerUsage() {
// Send out a raw email with PHPMailer class or legacy mail() command
function sendRawEmail ($toEmail, $subject, $message, $from) {
+ // Just compile all again, to put out all configs, etc.
+ eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
+ eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
+ eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
+ eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
+
// Shall we use PHPMailer class or legacy mode?
if (checkPhpMailerUsage()) {
// Use PHPMailer class with SMTP enabled
@@ -497,6 +625,11 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
// get new instance
$mail = new PHPMailer();
+
+ // Set charset to UTF-8
+ $mail->CharSet('UTF-8');
+
+ // Path for PHPMailer
$mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
$mail->IsSMTP();
@@ -512,7 +645,7 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
}
$mail->FromName = getConfig('MAIN_TITLE');
$mail->Subject = $subject;
- if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
+ if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
$mail->Body = $message;
$mail->AltBody = 'Your mail program required HTML support to read this mail!';
$mail->WordWrap = 70;
@@ -532,16 +665,16 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
}
// Generate a password in a specified length or use default password length
-function generatePassword ($length = 0) {
+function generatePassword ($length = '0') {
// Auto-fix invalid length of zero
- if ($length == 0) $length = getConfig('pass_len');
+ if ($length == '0') $length = getConfig('pass_len');
// Initialize array with all allowed chars
$ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/,.');
// Start creating password
$PASS = '';
- for ($i = 0; $i < $length; $i++) {
+ for ($i = '0'; $i < $length; $i++) {
$PASS .= $ABC[mt_rand(0, count($ABC) -1)];
} // END - for
@@ -562,49 +695,50 @@ function generateDateTime ($time, $mode = '0') {
$time = bigintval($time);
// If the stamp is zero it mostly didn't "happen"
- if ($time == 0) {
+ if ($time == '0') {
// Never happend
return getMessage('NEVER_HAPPENED');
} // END - if
- switch (getLanguage())
- {
+ switch (getLanguage()) {
case 'de': // German date / time format
switch ($mode) {
case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
- case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
- case '2': $ret = date("d.m.Y|H:i", $time); break;
- case '3': $ret = date("d.m.Y", $time); break;
+ case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
+ case '2': $ret = date('d.m.Y|H:i', $time); break;
+ case '3': $ret = date('d.m.Y', $time); break;
default:
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
break;
}
break;
- default: // Default is the US date / time format!
- switch ($mode) {
- case '0': $ret = date("r", $time); break;
- case '1': $ret = date("Y-m-d - g:i A", $time); break;
- case '2': $ret = date("y-m-d|H:i", $time); break;
- case '3': $ret = date("y-m-d", $time); break;
- default:
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
- break;
- }
- }
+ default: // Default is the US date / time format!
+ switch ($mode) {
+ case '0': $ret = date('r', $time); break;
+ case '1': $ret = date('Y-m-d - g:i A', $time); break;
+ case '2': $ret = date('y-m-d|H:i', $time); break;
+ case '3': $ret = date('y-m-d', $time); break;
+ default:
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+ break;
+ } // END - switch
+ } // END - switch
+
+ // Return result
return $ret;
}
// Translates Y/N to yes/no
function translateYesNo ($yn) {
// Default
- $translated = "??? (" . $yn.')';
+ $translated = '??? (' . $yn . ')';
switch ($yn) {
case 'Y': $translated = getMessage('YES'); break;
case 'N': $translated = getMessage('NO'); break;
default:
// Log unknown value
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
break;
}
@@ -621,7 +755,7 @@ function translatePoolType ($type) {
$constName = sprintf("POOL_TYPE_%s", $type);
// Does it exist?
- if (defined($constName)) {
+ if (isMessageIdValid($constName)) {
// Then use it
$translated = getMessage($constName);
} // END - if
@@ -631,9 +765,9 @@ function translatePoolType ($type) {
}
// Translates the american decimal dot into a german comma
-function translateComma ($dotted, $cut = true, $max = 0) {
+function translateComma ($dotted, $cut = true, $max = '0') {
// Default is 3 you can change this in admin area "Misc -> Misc Options"
- if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
+ if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
// Use from config is default
$maxComma = getConfig('max_comma');
@@ -642,25 +776,25 @@ function translateComma ($dotted, $cut = true, $max = 0) {
if ($max > 0) $maxComma = $max;
// Cut zeros off?
- if (($cut) && ($max == 0)) {
+ if (($cut === true) && ($max == '0')) {
// Test for commata if in cut-mode
$com = explode('.', $dotted);
if (count($com) < 2) {
// Don't display commatas even if there are none... ;-)
- $maxComma = 0;
+ $maxComma = '0';
}
} // END - if
// Debug log
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
// Translate it now
switch (getLanguage()) {
- case 'de':
+ case 'de': // German language
$dotted = number_format($dotted, $maxComma, ',', '.');
break;
- default:
+ default: // All others
$dotted = number_format($dotted, $maxComma, '.', ',');
break;
}
@@ -681,7 +815,7 @@ function translateGender ($gender) {
case 'C': $ret = getMessage('GENDER_C'); break;
default:
// Log unknown gender
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
break;
}
@@ -691,8 +825,8 @@ function translateGender ($gender) {
// "Translates" the user status
function translateUserStatus ($status) {
- switch ($status)
- {
+ // Generate message depending on status
+ switch ($status) {
case 'UNCONFIRMED':
case 'CONFIRMED':
case 'LOCKED':
@@ -705,21 +839,21 @@ function translateUserStatus ($status) {
break;
default:
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
$ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
break;
- }
+ } // END - switch
// Return it
return $ret;
}
// Generates an URL for the dereferer
-function DEREFERER ($URL) {
+function generateDerefererUrl ($URL) {
// Don't de-refer our own links!
if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
// De-refer this link
- $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
+ $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
} // END - if
// Return link
@@ -727,200 +861,64 @@ function DEREFERER ($URL) {
}
// Generates an URL for the frametester
-function FRAMETESTER ($URL) {
+function generateFrametesterUrl ($URL) {
// Prepare frametester URL
$frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
- encodeString(compileUriCode($URL))
+ encodeString(compileUriCode($URL))
);
+
+ // Return the new URL
return $frametesterUrl;
}
// Count entries from e.g. a selection box
function countSelection ($array) {
- $ret = 0;
- if (is_array($array)) {
- foreach ($array as $key => $selected) {
- if (!empty($selected)) $ret++;
- }
- }
- return $ret;
-}
-
-// Generate XHTML code for the CAPTCHA
-function generateCaptchaCode ($code, $type, $DATA, $uid) {
- return ' ';
-}
-
-// Loads an email template and compiles it
-function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
- global $DATA;
-
- // Our configuration is kept non-global here
- $_CONFIG = getConfigArray();
-
- // Make sure all template names are lowercase!
- $template = strtolower($template);
-
- // Default 'nickname' if extension is not installed
- $nick = '---';
-
- // Prepare IP number and User Agent
- $REMOTE_ADDR = detectRemoteAddr();
- $HTTP_USER_AGENT = detectUserAgent();
-
- // Default admin
- $ADMIN = getConfig('MAIN_TITLE');
-
- // Is the admin logged in?
- if (IS_ADMIN()) {
- // Get admin id
- $aid = getCurrentAdminId();
-
- // Load Admin data
- $ADMIN = getAdminEmail($aid);
- } // END - if
-
- // Neutral email address is default
- $email = getConfig('WEBMASTER');
-
- // Expiration in a nice output format
- // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
- if (getConfig('auto_purge') == 0) {
- // Will never expire!
- $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
- } else {
- // Create nice date string
- $EXPIRATION = createFancyTime(getConfig('auto_purge'));
- }
-
- // Is content an array?
- if (is_array($content)) {
- // Add expiration to array, $EXPIRATION is now deprecated!
- $content['expiration'] = $EXPIRATION;
+ // Integrity check
+ if (!is_array($array)) {
+ // Not an array!
+ debug_report_bug(__FUNCTION__.': No array provided.');
} // END - if
- // Load user's data
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):UID={$UID},template={$template},content[]=".gettype($content)." ");
- if (($UID > 0) && (is_array($content))) {
- // If nickname extension is installed, fetch nickname as well
- if (EXT_IS_ACTIVE('nickname')) {
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):NICKNAME! ");
- // Load nickname
- $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
- array(bigintval($UID)), __FUNCTION__, __LINE__);
- } else {
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):NO-NICK! ");
- /// Load normal data
- $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
- array(bigintval($UID)), __FUNCTION__, __LINE__);
- }
-
- // Fetch and merge data
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - PRE ");
- $content = merge_array($content, SQL_FETCHARRAY($result));
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - AFTER ");
+ // Init count
+ $ret = '0';
- // Free result
- SQL_FREERESULT($result);
- } // END - if
-
- // Translate M to male or F to female if present
- if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
-
- // Overwrite email from data if present
- if (isset($content['email'])) $email = $content['email'];
-
- // Store email for some functions in global data array
- $DATA['email'] = $email;
-
- // Base directory
- $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
-
- // Check for admin/guest/member templates
- if (strpos($template, 'admin_') > -1) {
- // Admin template found
- $FQFN = $basePath.'admin/' . $template.'.tpl';
- } elseif (strpos($template, 'guest_') > -1) {
- // Guest template found
- $FQFN = $basePath.'guest/' . $template.'.tpl';
- } elseif (strpos($template, 'member_') > -1) {
- // Member template found
- $FQFN = $basePath.'member/' . $template.'.tpl';
- } else {
- // Test for extension
- $test = substr($template, 0, strpos($template, '_'));
- if (EXT_IS_ACTIVE($test)) {
- // Set extra path to extension's name
- $FQFN = $basePath . $test.'/' . $template.'.tpl';
- } else {
- // No special filename
- $FQFN = $basePath . $template.'.tpl';
- }
- }
-
- // Does the special template exists?
- if (!isFileReadable($FQFN)) {
- // Reset to default template
- $FQFN = $basePath . $template.'.tpl';
- } // END - if
-
- // Now does the final template exists?
- $newContent = '';
- if (isFileReadable($FQFN)) {
- // The local file does exists so we load it. :)
- $tmpl_file = readFromFile($FQFN);
- $tmpl_file = SQL_ESCAPE($tmpl_file);
-
- // Run code
- $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
- eval($tmpl_file);
- } elseif (!empty($template)) {
- // Template file not found!
- $newContent = "{--TEMPLATE_404--}: " . $template."
-{--TEMPLATE_CONTENT--}
-".print_r($content, true)."
-{--TEMPLATE_DATA--}
-".print_r($DATA, true)."
- ";
-
- // Debug mode not active? Then remove the HTML tags
- if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
- } else {
- // No template name supplied!
- $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
- }
-
- // Is there some content?
- if (empty($newContent)) {
- // Compiling failed
- $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $tmpl_file;
- // Add last error if the required function exists
- if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
- } // END - if
+ // Count all entries
+ foreach ($array as $key => $selected) {
+ // Is it checked?
+ if (!empty($selected)) $ret++;
+ } // END - foreach
- // Remove content and data
- unset($content);
- unset($DATA);
+ // Return counted selections
+ return $ret;
+}
- // Return compiled content
- return COMPILE_CODE($newContent);
+// Generate XHTML code for the CAPTCHA
+function generateCaptchaCode ($code, $type, $DATA, $userid) {
+ return ' ';
}
// Generates a timestamp (some wrapper for mktime())
-function makeTime ($H, $M, $S, $stamp) {
+function makeTime ($hours, $minutes, $seconds, $stamp) {
// Extract day, month and year from given timestamp
- $day = date('d', $stamp);
- $month = date('m', $stamp);
- $year = date('Y', $stamp);
+ $days = date('d', $stamp);
+ $months = date('m', $stamp);
+ $years = date('Y', $stamp);
// Create timestamp for wished time which depends on extracted date
- return mktime($H, $M, $S, $month, $day, $year);
+ return mktime(
+ $hours,
+ $minutes,
+ $seconds,
+ $months,
+ $days,
+ $years
+ );
}
// Redirects to an URL and if neccessarry extends it with own base URL
function redirectToUrl ($URL) {
- // Compile out URI codes
- $URL = compileUriCode($URL);
+ // Compile out codes
+ eval('$URL = "' . compileRawCode($URL) . '";');
// Check if http(s):// is there
if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
@@ -930,7 +928,7 @@ function redirectToUrl ($URL) {
// Three different debug ways...
//* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
//* DEBUG: */ die($URL);
// Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
@@ -943,28 +941,31 @@ function redirectToUrl ($URL) {
} // END - if
// Get output buffer
- $OUTPUT = ob_get_contents();
+ $GLOBALS['output'] = ob_get_contents();
// Clear it only if there is content
- if (!empty($OUTPUT)) {
+ if (!empty($GLOBALS['output'])) {
clearOutputBuffer();
} // END - if
// Simple probe for bots/spiders from search engines
if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
// Secure the URL against bad things such als HTML insertions and so on...
- $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
+ $URL = secureString($URL);
// Output new location link as anchor
- OUTPUT_HTML('' . $URL . ' ');
+ outputHtml('' . $URL . ' ');
} elseif (!headers_sent()) {
- // Load URL when headers are not sent
//* DEBUG: */ debug_report_bug("URL={$URL}");
+ // Clear own output buffer
+ $GLOBALS['output'] = '';
+
+ // Load URL when headers are not sent
sendHeader('Location: '.str_replace('&', '&', $URL));
} else {
// Output error message
loadInclude('inc/header.php');
- LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
+ loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
loadInclude('inc/footer.php');
}
@@ -980,26 +981,54 @@ function redirectToConfiguredUrl ($configEntry) {
// Is this URL set?
if (is_null($URL)) {
// Then abort here
- trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
+ debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
} // END - if
- // Load the URL
- redirectToUrl($URL);
+ // Load the URL
+ redirectToUrl($URL);
+}
+
+// Compiles the given HTML/mail code
+function compileCode ($code, $simple = false, $constants = true, $full = true) {
+ // Is the code a string?
+ if (!is_string($code)) {
+ // Silently return it
+ return $code;
+ } // END - if
+
+ // Start couting
+ $startCompile = microtime(true);
+
+ // Comile the code
+ $code = compileRawCode($code, $simple, $constants, $full);
+
+ // Get timing
+ $compiled = microtime(true);
+
+ // Add timing
+ $code .= '';
+
+ // Return compiled code
+ return $code;
}
-//
-function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
+// Compiles the code (use compileCode() only for HTML because of the comments)
+// @TODO $simple is deprecated
+function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
// Is the code a string?
if (!is_string($code)) {
// Silently return it
return $code;
} // END - if
- // Init replacement-array with full security characters
- $secChars = $GLOBALS['security_chars'];
+ // Init replacement-array with smaller set of security characters
+ $secChars = $GLOBALS['url_chars'];
+
+ // Select full set of chars to replace when we e.g. want to compile URLs
+ if ($full === true) $secChars = $GLOBALS['security_chars'];
- // Select smaller set of chars to replace when we e.g. want to compile URLs
- if (!$full) $secChars = $GLOBALS['url_chars'];
+ // Compile more through a filter
+ $code = runFilterChain('compile_code', $code);
// Compile constants
if ($constants === true) {
@@ -1018,24 +1047,8 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
$code = str_replace($to, $secChars['from'][$k], $code);
} // END - foreach
- // But shall I keep simple quotes for later use?
- if ($simple) $code = str_replace("'", '{QUOT}', $code);
-
- // Compile {?some_var?} to getConfig('some_var')
- preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
-
- // Some entries found?
- if ((count($matches) > 0) && (count($matches[0]) > 0)) {
- // Replace all matches
- foreach ($matches[0] as $key => $match) {
- // Replace it
- //* DEBUG: */ if ($key == 0) { print ''; debug_print_backtrace(); print ' '; }
- //* DEBUG: */ print $match.'='.$matches[1][$key].' ('.$key.') ';
- $code = str_replace($match, getConfig($matches[1][$key]), $code);
- } // END - foreach
- } // END - if
-
// Find $content[bla][blub] entries
+ // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
// Are some matches found?
@@ -1052,10 +1065,10 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
$test = substr($found, 0, strlen($match));
// Does this entry exist?
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):found={$found},match={$match},set={$set} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):found={$found},match={$match},set={$set} ");
if ($test == $match) {
// Match found!
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):fuzzyFound! ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):fuzzyFound! ");
$fuzzyFound = true;
break;
} // END - if
@@ -1067,21 +1080,21 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
// Take all string elements
if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
// Replace it in the code
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):key={$key},match={$match} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):key={$key},match={$match} ");
$newMatch = str_replace('[', "['", str_replace(']', "']", $match));
- $code = str_replace($match, "\"." . $newMatch.".\"", $code);
+ $code = str_replace($match, '".' . $newMatch . '."', $code);
$matchesFound[$key . '_' . $matches[4][$key]] = 1;
$matchesFound[$match] = 1;
} elseif (!isset($matchesFound[$match])) {
// Not yet replaced!
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):match={$match} ");
- $code = str_replace($match, "\"." . $match.".\"", $code);
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):match={$match} ");
+ $code = str_replace($match, '".' . $match . '."', $code);
$matchesFound[$match] = 1;
}
} // END - foreach
} // END - if
- // Return compiled code
+ // Return it
return $code;
}
@@ -1101,13 +1114,13 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
* Sie, dass es doch nicht so schwer ist! :-) *
* *
************************************************************************/
-function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
+function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
$dummy = $array;
while ($primary_key < count($a_sort)) {
foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
$match = false;
- if (!$nums) {
+ if ($nums === false) {
// Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
} elseif ($key != $key2) {
@@ -1137,23 +1150,23 @@ function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
}
//
-function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
+function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
$OUT = '';
if ($type == 'yn') {
// This is a yes/no selection only!
if ($id > 0) $prefix .= "[" . $id."]";
- $OUT .= " \n";
+ $OUT .= " \n";
} else {
// Begin with regular selection box here
if (!empty($prefix)) $prefix .= "_";
$type2 = $type;
if ($id > 0) $type2 .= "[" . $id."]";
- $OUT .= " \n";
+ $OUT .= " \n";
}
switch ($type) {
- case "day": // Day
+ case 'day': // Day
for ($idx = 1; $idx < 32; $idx++) {
$OUT .= " $descr) {
$OUT .= " = '0.2.1') {
+ if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
// Configured
$startYear = $year - getConfig('min_age');
} else {
@@ -1202,7 +1215,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
// Get current year and subtract the configured minimum age
$OUT .= " <" . $minYear." \n";
// Calculate earliest year depending on extension version
- if (GET_EXT_VERSION('other') >= '0.2.1') {
+ if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
// Use configured minimum age
$year = date('Y', time()) - getConfig('min_age');
} else {
@@ -1219,9 +1232,9 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
}
break;
- case "sec":
- case "min":
- for ($idx = 0; $idx < 60; $idx+=5) {
+ case 'sec':
+ case 'min':
+ for ($idx = '0'; $idx < 60; $idx+=5) {
if (strlen($idx) == 1) $idx = '0' . $idx;
$OUT .= "{$num}");
+ debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
} // END - if
// Return result
@@ -1324,34 +1338,41 @@ function bigintval ($num, $castValue = true) {
}
// Insert the code in $img_code into jpeg or PNG image
-function GENERATE_IMAGE ($img_code, $headerSent=true) {
- if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
- // Stop execution of function here because of over-sized code length
- return;
- } elseif (!$headerSent) {
- // Return in an HTML code code
+function generateImageOrCode ($img_code, $headerSent = true) {
+ // Is the code size oversized or shouldn't we display it?
+ if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
+ // Stop2 execution of function here because of over-sized code length
+ debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
+ } elseif ($headerSent === false) {
+ // Return an HTML code here
return " \n";
}
// Load image
- $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
+ $img = sprintf("%s/theme/%s/images/code_bg.%s",
+ getConfig('PATH'),
+ getCurrentTheme(),
+ getConfig('img_type')
+ );
+
+ // Is it readable?
if (isFileReadable($img)) {
// Switch image type
switch (getConfig('img_type'))
{
case 'jpg':
// Okay, load image and hide all errors
- $image = @imagecreatefromjpeg($img);
+ $image = imagecreatefromjpeg($img);
break;
case 'png':
// Okay, load image and hide all errors
- $image = @imagecreatefrompng($img);
+ $image = imagecreatefrompng($img);
break;
}
} else {
// Exit function here
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
return;
}
@@ -1380,13 +1401,13 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
//* DEBUG: */ print("*" . $stamp.'/' . $timestamp."* ");
// Do we have a leap year?
- $SWITCH = 0;
+ $SWITCH = '0';
$TEST = date('Y', time()) / 4;
$M1 = date('m', time());
$M2 = date('m', (time() + $timestamp));
// If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
- if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
+ if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
// First of all years...
$Y = abs(floor($timestamp / (31536000 + $SWITCH)));
@@ -1395,23 +1416,23 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
$M = abs(floor($timestamp / 2628000 - $Y * 12));
//* DEBUG: */ print("M={$M} ");
// Next weeks
- $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
+ $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
//* DEBUG: */ print("W={$W} ");
// Next days...
- $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
+ $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
//* DEBUG: */ print("D={$D} ");
// Next hours...
- $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
+ $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
//* DEBUG: */ print("h={$h} ");
// Next minutes..
- $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
+ $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
//* DEBUG: */ print("m={$m} ");
// And at last seconds...
- $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
+ $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
//* DEBUG: */ print("s={$s} ");
// Is seconds zero and time is < 60 seconds?
- if (($s == 0) && ($timestamp < 60)) {
+ if (($s == '0') && ($timestamp < 60)) {
// Fix seconds
$s = round($timestamp);
} // END - if
@@ -1433,35 +1454,35 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
} else {
// Generate table
$OUT = "\n";
- $OUT .= "
\n";
+ $OUT .= "\n";
$OUT .= "\n";
if (ereg('Y', $display) || (empty($display))) {
- $OUT .= " {--_YEARS--}
\n";
+ $OUT .= " {--_YEARS--}
\n";
}
if (ereg('M', $display) || (empty($display))) {
- $OUT .= " {--_MONTHS--}
\n";
+ $OUT .= " {--_MONTHS--}
\n";
}
- if (ereg("W", $display) || (empty($display))) {
- $OUT .= " {--_WEEKS--}
\n";
+ if (ereg('W', $display) || (empty($display))) {
+ $OUT .= " {--_WEEKS--}
\n";
}
- if (ereg("D", $display) || (empty($display))) {
- $OUT .= " {--_DAYS--}
\n";
+ if (ereg('D', $display) || (empty($display))) {
+ $OUT .= " {--_DAYS--}
\n";
}
- if (ereg("h", $display) || (empty($display))) {
- $OUT .= " {--_HOURS--}
\n";
+ if (ereg('h', $display) || (empty($display))) {
+ $OUT .= " {--_HOURS--}
\n";
}
if (ereg('m', $display) || (empty($display))) {
- $OUT .= " {--_MINUTES--}
\n";
+ $OUT .= " {--_MINUTES--}
\n";
}
- if (ereg("s", $display) || (empty($display))) {
- $OUT .= " {--_SECONDS--}
\n";
+ if (ereg('s', $display) || (empty($display))) {
+ $OUT .= " {--_SECONDS--}
\n";
}
$OUT .= " \n";
@@ -1470,20 +1491,20 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
if (ereg('Y', $display) || (empty($display))) {
// Generate year selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 10; $idx++) {
+ for ($idx = '0'; $idx <= 10; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg('M', $display) || (empty($display))) {
// Generate month selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 11; $idx++)
+ for ($idx = '0'; $idx <= 11; $idx++)
{
$OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("W", $display) || (empty($display))) {
+ if (ereg('W', $display) || (empty($display))) {
// Generate week selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 4; $idx++) {
+ for ($idx = '0'; $idx <= 4; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("D", $display) || (empty($display))) {
+ if (ereg('D', $display) || (empty($display))) {
// Generate day selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 31; $idx++) {
+ for ($idx = '0'; $idx <= 31; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("h", $display) || (empty($display))) {
+ if (ereg('h', $display) || (empty($display))) {
// Generate hour selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 23; $idx++) {
+ for ($idx = '0'; $idx <= 23; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg('m', $display) || (empty($display))) {
// Generate minute selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 59; $idx++) {
+ for ($idx = '0'; $idx <= 59; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("s", $display) || (empty($display))) {
+ if (ereg('s', $display) || (empty($display))) {
// Generate second selection
$OUT .= " \n";
- for ($idx = 0; $idx <= 59; $idx++) {
+ for ($idx = '0'; $idx <= 59; $idx++) {
$OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
$OUT .= "\n";
$OUT .= "
\n";
@@ -1567,98 +1588,34 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
}
//
-function createTimestampFromSelections ($prefix, $POST) {
+function createTimestampFromSelections ($prefix, $postData) {
// Initial return value
- $ret = 0;
+ $ret = '0';
// Do we have a leap year?
- $SWITCH = 0;
+ $SWITCH = '0';
$TEST = date('Y', time()) / 4;
$M1 = date('m', time());
// If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
- if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
+ if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
// First add years...
- $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
+ $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
// Next months...
- $ret += $POST[$prefix."_mo"] * 2628000;
+ $ret += $postData[$prefix."_mo"] * 2628000;
// Next weeks
- $ret += $POST[$prefix."_we"] * 604800;
+ $ret += $postData[$prefix."_we"] * 604800;
// Next days...
- $ret += $POST[$prefix."_da"] * 86400;
+ $ret += $postData[$prefix."_da"] * 86400;
// Next hours...
- $ret += $POST[$prefix."_ho"] * 3600;
+ $ret += $postData[$prefix."_ho"] * 3600;
// Next minutes..
- $ret += $POST[$prefix."_mi"] * 60;
+ $ret += $postData[$prefix."_mi"] * 60;
// And at last seconds...
- $ret += $POST[$prefix."_se"];
+ $ret += $postData[$prefix."_se"];
// Return calculated value
return $ret;
}
-// Sends out mail to all administrators
-// IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
-function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
- // Trim template name
- $template = trim($template);
-
- // Load email template
- $message = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
-
- // Check which admin shall receive this mail
- $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
- array($template), __FUNCTION__, __LINE__);
- if (SQL_NUMROWS($result) == 0) {
- // Create new entry (to all admins)
- SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
- array($template), __FUNCTION__, __LINE__);
- } else {
- // Load admin IDs...
- // @TODO This can be, somehow, rewritten
- $adminIds = array();
- while ($content = SQL_FETCHARRAY($result)) {
- $adminIds[] = $content['admin_id'];
- } // END - while
-
- // Free memory
- SQL_FREERESULT($result);
-
- // Init result
- $result = false;
-
- // "implode" IDs and query string
- $aid = implode(',', $adminIds);
- if ($aid == '-1') {
- if (EXT_IS_ACTIVE('events')) {
- // Add line to user events
- EVENTS_ADD_LINE($subj, $message, $UID);
- } else {
- // Log error for debug
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
- $template,
- $subj,
- $UID
- ));
- }
- } elseif ($aid == '0') {
- // Select all email adresses
- $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
- __FUNCTION__, __LINE__);
- } else {
- // If Admin-ID is not "to-all" select
- $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
- array($aid), __FUNCTION__, __LINE__);
- }
- }
-
- // Load email addresses and send away
- while ($content = SQL_FETCHARRAY($result)) {
- sendEmail($content['email'], $subj, $message);
- } // END - while
-
- // Free memory
- SQL_FREERESULT($result);
-}
-
// Creates a 'fancy' human-readable timestamp from a Uni* stamp
function createFancyTime ($stamp) {
// Get data array with years/months/weeks/days/...
@@ -1667,8 +1624,7 @@ function createFancyTime ($stamp) {
foreach($data as $k => $v) {
if ($v > 0) {
// Value is greater than 0 "eval" data to return string
- $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
- eval($eval);
+ eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
break;
} // END - if
} // END - foreach
@@ -1686,10 +1642,10 @@ function createFancyTime ($stamp) {
return $ret;
}
-//
-function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
+// Generates a navigation row for listing emails
+function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
$SEP = ''; $TOP = '';
- if (!$show_form) {
+ if ($show_form === false) {
$TOP = " top2";
$SEP = " ";
}
@@ -1697,49 +1653,47 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
$NAV = '';
for ($page = 1; $page <= $PAGES; $page++) {
// Is the page currently selected or shall we generate a link to it?
- if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
+ if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
// Is currently selected, so only highlight it
- $NAV .= "-";
+ $NAV .= '-';
} else {
// Open anchor tag and add base URL
- $NAV .= " 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
+ if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
// Close open anchor tag
- $NAV .= "\">";
+ $NAV .= '">';
}
$NAV .= $page;
- if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
+ if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
// Is currently selected, so only highlight it
- $NAV .= "- ";
+ $NAV .= '- ';
} else {
// Close anchor tag
- $NAV .= "";
+ $NAV .= '';
}
// Add seperator if we have not yet reached total pages
- if ($page < $PAGES) $NAV .= " | ";
+ if ($page < $PAGES) $NAV .= ' | ';
} // END - for
// Define constants only once
- if (!defined('__NAV_OUTPUT')) {
- define('__NAV_OUTPUT' , $NAV);
- define('__NAV_COLSPAN', $colspan);
- define('__NAV_TOP' , $TOP);
- define('__NAV_SEP' , $SEP);
- } // END - if
+ $content['nav'] = $NAV;
+ $content['span'] = $colspan;
+ $content['top'] = $TOP;
+ $content['sep'] = $SEP;
// Load navigation template
- $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
+ $OUT = loadTemplate('admin_email_nav_row', true, $content);
if ($return === true) {
// Return generated HTML-Code
return $OUT;
} else {
// Output HTML-Code
- OUTPUT_HTML($OUT);
+ outputHtml($OUT);
}
}
@@ -1762,16 +1716,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
@@ -1779,25 +1733,37 @@ function extractHostnameFromUrl (&$script) {
}
// Send a GET request
-function sendGetRequest ($script) {
- // Compile the script name
- $script = COMPILE_CODE($script);
-
+function sendGetRequest ($script, $data = array()) {
// Extract host name from script
$host = extractHostnameFromUrl($script);
+ // Add data
+ $scriptData = 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;
+ } else {
+ // Ok, add &
+ $scriptData = '&' . $scriptData;
+ }
+
+ // Add script data
+ $script .= $scriptData;
+
// Generate GET request header
- $request = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
- $request .= "Host: " . $host . getConfig('HTTP_EOL');
- $request .= "Referer: " . getConfig('URL') . "/admin.php" . getConfig('HTTP_EOL');
+ $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
+ $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
+ $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
if (isConfigEntrySet('FULL_VERSION')) {
- $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
+ $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
} else {
- $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
+ $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
}
- $request .= "Content-Type: text/plain" . 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 .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+ $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
// Send the raw request
$response = sendRawRequest($host, $request);
@@ -1811,28 +1777,25 @@ function sendPostRequest ($script, $postData) {
// Is postData an array?
if (!is_array($postData)) {
// Abort here
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
return array('', '', '');
} // END - if
- // Compile the script name
- $script = COMPILE_CODE($script);
-
// Extract host name from script
$host = extractHostnameFromUrl($script);
// Construct request
- $data = http_build_query($postData, '','&');
+ $data = 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 = '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;
// Send the raw request
@@ -1845,7 +1808,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('', '', '');
@@ -1854,16 +1817,16 @@ function sendRawRequest ($host, $request) {
$useProxy = false;
// Are proxy settins set?
- if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
+ if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
// Then use it
$useProxy = true;
} // END - if
// Open connection
- //* DEBUG: */ die("SCRIPT=" . $script." ");
+ //* DEBUG: */ die("SCRIPT=" . $script.' ');
if ($useProxy === true) {
// Connect to host through proxy connection
- $fp = @fsockopen(COMPILE_CODE(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);
@@ -1884,7 +1847,7 @@ function sendRawRequest ($host, $request) {
// Use login data to proxy? (username at least!)
if (getConfig('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
+ $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
$proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
} // END - if
@@ -1958,9 +1921,6 @@ function sendRawRequest ($host, $request) {
// Taken from www.php.net eregi() user comments
function isEmailValid ($email) {
- // Compile email
- $email = COMPILE_CODE($email);
-
// Check first part of email address
$first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
@@ -1978,14 +1938,14 @@ function isEmailValid ($email) {
function isUrlValid ($URL, $compile=true) {
// Trim URL a little
$URL = trim(urldecode($URL));
- //* DEBUG: */ OUTPUT_HTML($URL." ");
+ //* DEBUG: */ outputHtml($URL.' ');
// Compile some chars out...
if ($compile === true) $URL = compileUriCode($URL, false, false, false);
- //* DEBUG: */ OUTPUT_HTML($URL." ");
+ //* DEBUG: */ outputHtml($URL.' ');
// Check for the extension filter
- if (EXT_IS_ACTIVE('filter')) {
+ if (isExtensionActive('filter')) {
// Use the extension's filter set
return FILTER_VALIDATE_URL($URL, false);
} // END - if
@@ -1996,37 +1956,39 @@ function isUrlValid ($URL, $compile=true) {
}
// Generate a list of administrative links to a given userid
-function generateMemberAdminActionLinks ($uid, $status = '') {
+function generateMemberAdminActionLinks ($userid, $status = '') {
+ // Make sure userid is a number
+ if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
+
// Define all main targets
- $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
+ $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
// Begin of navigation links
- $eval = "\$OUT = \"[ ";
+ $OUT = "[ ";
- foreach ($TARGETS as $tar) {
- $eval .= " ");
- if (($tar == "lock_user") && ($status == 'LOCKED')) {
+ foreach ($targetArray as $tar) {
+ $OUT .= " ");
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
// Locked accounts shall be unlocked
- $eval .= "UNLOCK_USER";
+ $OUT .= 'UNLOCK_USER';
} else {
// All other status is fine
- $eval .= strtoupper($tar);
+ $OUT .= strtoupper($tar);
}
- $eval .= "_TITLE--}\\\">{--ADMIN_";
- if (($tar == "lock_user") && ($status == 'LOCKED')) {
+ $OUT .= "_TITLE--}\">{--ADMIN_";
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
// Locked accounts shall be unlocked
- $eval .= "UNLOCK_USER";
+ $OUT .= 'UNLOCK_USER';
} else {
// All other status is fine
- $eval .= strtoupper($tar);
+ $OUT .= strtoupper($tar);
}
- $eval .= "--} | ";
+ $OUT .= "--} | ";
}
// Finish navigation link
- $eval = substr($eval, 0, -7)."]\";";
- eval($eval);
+ $OUT = substr($OUT, 0, -7) . ']';
// Return string
return $OUT;
@@ -2038,19 +2000,19 @@ function generateEmailLink ($email, $table = 'admins') {
$EMAIL = 'mailto:' . $email;
// Check for several extensions
- if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
+ if ((isExtensionActive('admins')) && ($table == 'admins')) {
// Create email link for contacting admin in guest area
$EMAIL = generateAdminEmailLink($email);
- } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
+ } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
// Create email link for contacting a member within admin area (or later in other areas, too?)
$EMAIL = generateUserEmailLink($email, 'admin');
- } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
+ } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
// Create email link to contact sponsor within admin area (or like the link above?)
$EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
}
// Shall I close the link when there is no admin?
- if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
+ if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
// Return email link
return $EMAIL;
@@ -2059,46 +2021,53 @@ 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 (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('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
// Do we miss an arry element here?
if (!isConfigEntrySet('file_hash')) {
- // Stop here
+ // Stop2 here
debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
} // END - if
// When the salt is empty build a new one, else use the first x configured characters as the salt
if (empty($salt)) {
// Build server string (inc/databases.php is no longer updated with every commit)
- $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
+ $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
// Build key string
- $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig('patch_ctime')).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
+ $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
// Additional data
- $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
+ $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
// Calculate number for generating the code
$a = time() + getConfig('_ADD') - 1;
// 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: */ OUTPUT_HTML("SHA1=" . $sha1." (".strlen($sha1).") ");
+ $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).") ");
$sha1 = scrambleString($sha1);
- //* DEBUG: */ OUTPUT_HTML("Scrambled=" . $sha1." (".strlen($sha1).") ");
+ //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).") ");
//* DEBUG: */ $sha1b = descrambleString($sha1);
- //* DEBUG: */ OUTPUT_HTML("Descrambled=" . $sha1b." (".strlen($sha1b).") ");
+ //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).") ");
// Generate the password salt string
$salt = substr($sha1, 0, getConfig('salt_length'));
- //* DEBUG: */ OUTPUT_HTML($salt." (".strlen($salt).") ");
+ //* DEBUG: */ outputHtml($salt." (".strlen($salt).") ");
} else {
// Use given salt
+ //* DEBUG: */ print 'salt=' . $salt . ' ';
$salt = substr($salt, 0, getConfig('salt_length'));
- //* DEBUG: */ OUTPUT_HTML("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
@@ -2123,8 +2092,8 @@ function scrambleString($str) {
}
// Scramble string here
- //* DEBUG: */ OUTPUT_HTML("***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);
@@ -2133,7 +2102,7 @@ function scrambleString($str) {
} // END - for
// Return scrambled string
- //* DEBUG: */ OUTPUT_HTML("***Scrambled=" . $scrambled."*** ");
+ //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."*** ");
return $scrambled;
}
@@ -2150,14 +2119,14 @@ function descrambleString($str) {
// Begin descrambling
$orig = str_repeat(' ', 40);
- //* DEBUG: */ OUTPUT_HTML("+++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: */ OUTPUT_HTML("+++Original=" . $orig."+++ ");
+ //* DEBUG: */ outputHtml("+++Original=" . $orig."+++ ");
return $orig;
}
@@ -2167,7 +2136,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));
@@ -2191,10 +2160,10 @@ function generatePassString ($passHash) {
$ret = $passHash;
// Is a secret key and master salt already initialized?
- if ((getConfig('secret_key') != '') && (getConfig('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);
@@ -2203,21 +2172,22 @@ 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: */ OUTPUT_HTML("*" . $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: */ OUTPUT_HTML("--" . $passHash."-- ");
+ //* DEBUG: */ outputHtml("--" . $passHash."-- ");
$ret = md5($passHash);
- //* DEBUG: */ OUTPUT_HTML("++" . $ret."++ ");
+ //* DEBUG: */ outputHtml("++" . $ret."++ ");
}
// Return result
@@ -2252,10 +2222,10 @@ function app_die ($F, $L, $message) {
$message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
// Better log this message away
- DEBUG_LOG($F, $L, $message);
+ logDebugMessage($F, $L, $message);
// Load the message template
- LOAD_TEMPLATE('admin_settings_saved', false, $message);
+ loadTemplate('admin_settings_saved', false, $message);
// Load footer
loadIncludeOnce('inc/footer.php');
@@ -2280,18 +2250,16 @@ function displayParsingTime() {
$start = explode(' ', $GLOBALS['startTime']);
$end = explode(' ', $endTime);
$runTime = $end[0] - $start[0];
- if ($runTime < 0) $runTime = 0;
- $runTime = translateComma($runTime);
+ if ($runTime < 0) $runTime = '0';
// Prepare output
$content = array(
- 'runtime' => $runTime,
- 'numSQLs' => (getConfig('sql_count') + 1),
- 'numTemplates' => (getConfig('num_templates') + 1)
+ 'runtime' => translateComma($runTime),
+ 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
);
// Load the template
- LOAD_TEMPLATE('show_timings', false, $content);
+ loadTemplate('show_timings', false, $content);
}
// Check wether a boolean constant is set
@@ -2303,14 +2271,14 @@ function isBooleanConstantAndTrue ($constName) { // : Boolean
// In cache?
if (isset($GLOBALS['cache_array']['const'][$constName])) {
// Use cache
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ): " . $constName."-CACHE! ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ): " . $constName."-CACHE! ");
$res = ($GLOBALS['cache_array']['const'][$constName] === true);
} else {
// Check constant
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ): " . $constName."-RESOLVE! ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ): " . $constName."-RESOLVE! ");
if (defined($constName)) {
// Found!
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ): " . $constName."-FOUND! ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ): " . $constName."-FOUND! ");
$res = (constant($constName) === true);
} // END - if
@@ -2330,66 +2298,66 @@ function isApacheModuleLoaded ($apacheModule) {
}
// Get current theme name
-function getCurrentTheme() {
+function getCurrentTheme () {
// The default theme is 'default'... ;-)
$ret = 'default';
// Load default theme if not empty from configuration
- if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
+ if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
if (!isSessionVariableSet('mxchange_theme')) {
// Set default theme
- setSession('mxchange_theme', $ret);
- } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
+ 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) {
+ if (getThemeId($ret) == '0') {
// Fix it to default
$ret = 'default';
} // END - if
- } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
+ } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
// Prepare FQFN for checking
- $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), REQUEST_GET('theme'));
+ $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
// Installation mode active
- if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
+ if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
// Set cookie from URL data
- setSession('mxchange_theme', REQUEST_GET('theme'));
- } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+ setTheme(getRequestElement('theme'));
+ } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), secureString(postRequestElement('theme'))))) {
// Set cookie from posted data
- setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
+ setTheme(secureString(postRequestElement('theme')));
}
// Set return value
$ret = getSession('mxchange_theme');
} else {
// Invalid design, reset cookie
- setSession('mxchange_theme', $ret);
+ setTheme($ret);
}
- // Add (maybe) found theme.php file to inclusion list
- $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
-
- // Try to load the requested include file
- if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
-
// 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 (!EXT_IS_ACTIVE('theme')) {
+ if (!isExtensionActive('theme')) {
// Then abort here
return 0;
} // END - if
// Default id
- $id = 0;
+ $id = '0';
// Is the cache entry there?
if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
@@ -2397,11 +2365,11 @@ function getThemeId ($name) {
$id = $GLOBALS['cache_array']['themes']['id'][$name];
// Count up
- incrementConfigEntry('cache_hits');
- } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
+ incrementStatsEntry('cache_hits');
+ } elseif (isExtensionInstalledAndNewer('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__);
+ $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) {
@@ -2418,26 +2386,26 @@ function getThemeId ($name) {
}
// 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("ID_%s", $status);
// Is the constant there?
- if (isCodeSet($constantName)) {
+ if (isCodeSet($codeName)) {
// Then get it!
- $errorCode = getCode($constantName);
+ $errorCode = getCode($codeName);
} else {
// Unknown status
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
}
// Return error code
@@ -2447,12 +2415,12 @@ function generateErrorCodeFromUserStatus ($status) {
// Function to search for the last modifified file
function searchDirsRecursive ($dir, &$last_changed) {
// Get dir as array
- //* DEBUG: */ OUTPUT_HTML(__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: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):ds[]=".count($ds)." ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):ds[]=".count($ds).' ');
// Walk through all entries
foreach ($ds as $d) {
@@ -2460,20 +2428,20 @@ function searchDirsRecursive ($dir, &$last_changed) {
$FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
// Is it a file and readable?
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):FQFN={$FQFN} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):FQFN={$FQFN} ");
if (isDirectory($FQFN)) {
// $FQFN is a directory so also crawl into this directory
$newDir = $d;
if (!empty($dir)) $newDir = $dir . '/'. $d;
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):DESCENT: " . $newDir." ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):DESCENT: " . $newDir.' ');
searchDirsRecursive($newDir, $last_changed);
} elseif (isFileReadable($FQFN)) {
// $FQFN is a filename and no directory
$time = filemtime($FQFN);
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):File: " . $d." found. (".($last_changed['time'] - $time).") ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):File: " . $d." found. (".($last_changed['time'] - $time).") ");
if ($last_changed['time'] < $time) {
// This file is newer as the file before
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ) - NEWER! ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ) - NEWER! ");
$last_changed['path_name'] = $FQFN;
$last_changed['time'] = $time;
} // END - if
@@ -2486,50 +2454,19 @@ function getActualVersion ($type = 'Revision') {
// By default nothing is new... ;-)
$new = false;
- if (EXT_IS_ACTIVE('cache')) {
- // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
- if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
- // Force rebuild by URL parameter
- $new = true;
- } elseif ((
- !isset($GLOBALS['cache_array']['revision'][$type])
- ) || (
- count($GLOBALS['cache_array']['revision']) < 3
- ) || (
- !$GLOBALS['cache_instance']->loadCacheFile('revision')
- )) {
- // Out-dated cache
- $new = true;
- } // END - if
-
- // Is the cache file outdated/invalid?
- if ($new === true) {
- // Reload the cache file
- $GLOBALS['cache_instance']->loadCacheFile('revision');
-
- // Destroy cache file
- $GLOBALS['cache_instance']->destroyCacheFile(false, true);
-
- // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
- unset($GLOBALS['cache_array']['revision']);
-
- // Reload load_cach-revison.php
- loadInclude('inc/loader/load_cache-revision.php');
-
- // Abort here
- return;
- } // END - if
+ // Is the cache entry there?
+ if (isset($GLOBALS['cache_array']['revision'][$type])) {
+ // Found so increase cache hit
+ incrementStatsEntry('cache_hits');
- // Return found value
+ // Return it
return $GLOBALS['cache_array']['revision'][$type][0];
} else {
- // Old Version without ext-cache active (deprecated ?)
-
// FQFN of revision file
- $FQFN = sprintf("%sinc/cache/.revision", getConfig('PATH'));
+ $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
- // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
- if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
+ // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
+ if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
// Forced rebuild of .revision file
$new = true;
} else {
@@ -2543,13 +2480,18 @@ function getActualVersion ($type = 'Revision') {
// Get array for mapping information
$mapper = array_flip(getSearchFor());
- //* DEBUG: */ print("".print_r($mapper, true).print_r($ins_vers, true)." ");
+ //* DEBUG: */ print('mapper='.print_r($mapper, true).' ins_vers='.print_r($ins_vers, true).' ');
// Is the content valid?
- if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
+ if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
// File needs update!
$new = true;
} else {
+ // Generate fake cache entry
+ foreach ($mapper as $map=>$idx) {
+ $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
+ } // END - foreach
+
// Return found value
return trim($ins_vers[$mapper[$type]]);
}
@@ -2558,7 +2500,11 @@ function getActualVersion ($type = 'Revision') {
// Has it been updated?
if ($new === true) {
+ // Write it
writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
+
+ // ... and call recursive
+ return getActualVersion($type);
} // END - if
}
}
@@ -2567,7 +2513,7 @@ function getActualVersion ($type = 'Revision') {
// The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
function getSearchFor () {
// Add Revision, Date, Tag and Author
- $searchFor = array('Revision', 'Date', 'Tag', 'Author');
+ $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
// Return the created array
return $searchFor;
@@ -2588,7 +2534,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);
@@ -2603,27 +2549,27 @@ function getArrayFromActualVersion () {
foreach ($searchFor as $search) {
// Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
$res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
- // This trimms the search-result and puts it in the $akt_vers-return array
- if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
+ // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
+ if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
} // END - foreach
// Save the last-changed filename for debugging
- $akt_vers['File'] = $last_changed['path_name'];
+ $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
// at least 3 keyword-Tags are needed for propper values
if ($res && $res >= 3
- && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
- && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
- && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
+ && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
+ && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
+ && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
// Prepare content witch need special treadment
// Prepare timestamp for date
- preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
- $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
+ preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
+ $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
// Add author to the Tag if the author is set and is not quix0r (lead coder)
- if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
- $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
+ if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
+ $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
} // END - if
} else {
@@ -2632,14 +2578,15 @@ function getArrayFromActualVersion () {
// Prepare content
// Only sets not setted or not proper values to the Online-Server-Fallback-Solution
- if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
- if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
- if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
- if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
+ if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
+ if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
+ if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
+ if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
+ if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
}
// Return prepared array
- return $akt_vers;
+ return $GLOBALS['cache_array']['revision'];
}
// Back-ported from the new ship-simu engine. :-)
@@ -2665,8 +2612,20 @@ function debug_get_printable_backtrace () {
// Output a debug backtrace to the user
function debug_report_bug ($message = '') {
+ // Is this already called?
+ if (isset($GLOBALS[__FUNCTION__])) {
+ // Other backtrace
+ print 'Message:'.$message.' Backtrace:';
+ debug_print_backtrace();
+ die(' ');
+ } // END - if
+
+ // Set this function as called
+ $GLOBALS[__FUNCTION__] = true;
+
// Init message
$debug = '';
+
// Is the optional message set?
if (!empty($message)) {
// Use and log it
@@ -2675,13 +2634,13 @@ function debug_report_bug ($message = '') {
);
// @TODO Add a little more infos here
- DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+ logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
} // END - if
// Add output
- $debug .= "Please report this bug at bugs.mxchange.org and include the logfile from inc/cache/debug.log in your report (you can now attach files):";
+ $debug .= "Please report this bug at 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: " . $_SERVER['REQUEST_URI']." \n";
+ $debug .= " \nRequest-URI: " . getRequestUri()." \n";
$debug .= "Thank you for finding bugs.";
// And abort here
@@ -2689,28 +2648,48 @@ function debug_report_bug ($message = '') {
die($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
-function convertCodeToMessage ($code) {
+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_NOT_FOUND'); 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('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); 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('ERROR_MAILID'):
- if (EXT_IS_ACTIVE($ext, true)) {
+ if (isExtensionActive('mailid', true)) {
$message = getMessage('ERROR_CONFIRMING_MAIL');
} else {
$message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
@@ -2718,24 +2697,46 @@ function convertCodeToMessage ($code) {
break;
case getCode('EXTENSION_PROBLEM'):
- if (REQUEST_ISSET_GET('ext')) {
- $message = generateExtensionInactiveNotInstalledMessage(REQUEST_GET('ext'));
+ if (isGetRequestElementSet('ext')) {
+ $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
} else {
$message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
}
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'), REQUEST_GET('mod')); break;
+ case getCode('URL_TLOCK'):
+ $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);
+
+ // Calculate hours...
+ $STD = round(getConfig('url_tlock') / 60 / 60);
+
+ // Minutes...
+ $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
+
+ // And seconds
+ $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
+
+ // Finally contruct the message
+ // @TODO Rewrite this old lost code to a template
+ $message = "{--MEMBER_URL_TIME_LOCK--} {--CONFIG_URL_TLOCK--} ".$STD."
+ {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}
+ {--MEMBER_LAST_TLOCK--}: ".$timestamp;
+ break;
default:
// Missing/invalid code
$message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
// Log it
- DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+ logDebugMessage(__FUNCTION__, __LINE__, $message);
break;
} // END - switch
@@ -2743,40 +2744,10 @@ function convertCodeToMessage ($code) {
return $message;
}
-// Generate a "link" for the given admin id (aid)
-function generateAdminLink ($aid) {
- // No assigned admin is default
- $admin = "{--ADMIN_NO_ADMIN_ASSIGNED--} ";
-
- // Zero? = Not assigned
- if (bigintval($aid) > 0) {
- // Load admin's login
- $login = getAdminLogin($aid);
-
- // Is the login valid?
- if ($login != '***') {
- // Is the extension there?
- if (EXT_IS_ACTIVE('admins')) {
- // Admin found
- $admin = "" . $login." ";
- } else {
- // Extension not found
- $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
- }
- } else {
- // Maybe deleted?
- $admin = "".sprintf(getMessage('ADMIN_ID_404'), $aid)."
";
- }
- } // END - if
-
- // Return result
- return $admin;
-}
-
// Compile characters which are allowed in URLs
function compileUriCode ($code, $simple = true) {
// Compile constants
- if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
+ if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
// Compile QUOT and other non-HTML codes
$code = str_replace('{DOT}', '.',
@@ -2798,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 = strip_tags(str_replace("\\", '', COMPILE_CODE(urldecode($url))));
+ $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
// Allows http and https
$http = "(http|https)+(:\/\/)";
@@ -2846,7 +2817,7 @@ function isUrlValidSimple ($url) {
// @TODO Are these convertions still required?
$pat = str_replace('.', "\.", $pat);
$pat = str_replace('@', "\@", $pat);
- //* DEBUG: */ OUTPUT_HTML($key."= " . $pat . " ");
+ //* DEBUG: */ outputHtml($key."= " . $pat . ' ');
} // END - if
// Check if expression matches
@@ -2875,20 +2846,24 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
$tmp = $FQFN . '.tmp';
// Open the source file
- $fp = fopen($FQFN, 'r') or OUTPUT_HTML('READ: ' . $FQFN . ' ');
+ $fp = fopen($FQFN, 'r') or outputHtml('READ: ' . $FQFN . ' ');
// Is the resource valid?
if (is_resource($fp)) {
// Open temporary file
- $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('WRITE: ' . $tmp . ' ');
+ $fp_tmp = fopen($tmp, 'w') or outputHtml('WRITE: ' . $tmp . ' ');
// Is the resource again valid?
if (is_resource($fp_tmp)) {
+ // Mark temporary file as readable
+ $GLOBALS['file_readable'][$tmp] = true;
+
+ // Start reading
while (!feof($fp)) {
// 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) {
@@ -2918,90 +2893,45 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
copyFileVerified($tmp, $FQFN, 0644);
return removeFile($tmp);
} elseif ($found === false) {
- OUTPUT_HTML('CHANGE: 404!');
+ outputHtml('CHANGE: 404!');
} else {
- OUTPUT_HTML('TMP: UNDONE!');
+ outputHtml('TMP: UNDONE!');
}
}
} else {
// File not found, not readable or writeable
- OUTPUT_HTML('404: ' . $FQFN . ' ');
+ outputHtml('404: ' . $FQFN . ' ');
}
// An error was detected!
return false;
}
// Send notification to admin
-function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
- if (GET_EXT_VERSION('admins') >= '0.4.1') {
+function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
+ if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
// Send new way
- SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
+ sendAdminsEmails($subject, $templateName, $content, $userid);
} else {
// Send out out-dated way
- $message = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
- SEND_ADMIN_EMAILS($subject, $message);
+ $message = loadEmailTemplate($templateName, $content, $userid);
+ sendAdminEmails($subject, $message);
}
}
// Debug message logger
-function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
+function logDebugMessage ($funcFile, $line, $message, $force=true) {
// Is debug mode enabled?
if ((isDebugModeEnabled()) || ($force === true)) {
// Remove CRLF
$message = str_replace("\r", '', str_replace("\n", '', $message));
// Log this message away, we better don't call app_die() here to prevent an endless loop
- $fp = fopen(getConfig('PATH') . 'inc/cache/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 . '|' . strip_tags($message) . "\n");
+ $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(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
fclose($fp);
} // END - if
}
-// Load more reset scripts
-function runResetIncludes () {
- // Is the reset set or old sql_patches?
- if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
- // Then abort here
- DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
- } // END - if
-
- // Get more daily reset scripts
- SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
-
- // Update database
- if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
-
- // Is the config entry set?
- if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
- // Create current week mark
- $currWeek = date('W', time());
-
- // Has it changed?
- if (getConfig('last_week') != $currWeek) {
- // Include weekly reset scripts
- MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
-
- // Update config
- if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
- } // END - if
-
- // Create current month mark
- $currMonth = date('m', time());
-
- // Has it changed?
- if (getConfig('last_month') != $currMonth) {
- // Include monthly reset scripts
- MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
-
- // Update config
- if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
- } // END - if
- } // END - if
-
- // Run the filter
- runFilterChain('load_includes');
-}
-
// Handle extra values
function handleExtraValues ($filterFunction, $value, $extraValue) {
// Default is the value itself
@@ -3036,8 +2966,9 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
}
// Converts timestamp selections into a timestamp
-function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
+function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
// Init test variable
+ $skip = false;
$test2 = '';
// Get last three chars
@@ -3047,24 +2978,23 @@ function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
// Found a multi-selection for timings?
$test = substr($id, 0, -3);
- if ((isset($POST[$test.'_ye'])) && (isset($POST[$test.'_mo'])) && (isset($POST[$test.'_we'])) && (isset($POST[$test.'_da'])) && (isset($POST[$test.'_ho'])) && (isset($POST[$test.'_mi'])) && (isset($POST[$test.'_se'])) && ($test != $test2)) {
+ 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
- $POST[$test] = createTimestampFromSelections($test, $POST);
- $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
+ $postData[$test] = createTimestampFromSelections($test, $postData);
+ $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($POST[$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
@@ -3093,7 +3023,7 @@ function convertCommaToDot ($str) {
}
// Handle menu-depending failed logins and return the rendered content
-function HANDLE_LOGIN_FAILTURES ($accessLevel) {
+function handleLoginFailtures ($accessLevel) {
// Default output is empty ;-)
$OUT = '';
@@ -3102,14 +3032,14 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
// Ignore zero values
if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
// Non-guest has login failures found, get both data and prepare it for template
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):accessLevel={$accessLevel} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):accessLevel={$accessLevel} ");
$content = array(
'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
- 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
+ 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
);
// Load template
- $OUT = LOAD_TEMPLATE('login_failures', true, $content);
+ $OUT = loadTemplate('login_failures', true, $content);
} // END - if
// Reset session data
@@ -3122,59 +3052,43 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
}
// Rebuild cache
-function rebuildCacheFiles ($cache, $inc = '') {
+function rebuildCacheFile ($cache, $inc = '', $force = false) {
+ // Debug message
+ /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
+
// Shall I remove the cache file?
- if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
+ if (isCacheInstanceValid()) {
// Rebuild cache
if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
// Destroy it
- $GLOBALS['cache_instance']->destroyCacheFile();
+ $GLOBALS['cache_instance']->removeCacheFile($force);
} // END - if
// Include file given?
if (!empty($inc)) {
// Construct FQFN
- $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
+ $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
// Is the include there?
- if (isIncludeReadable($INC)) {
+ if (isIncludeReadable($inc)) {
// And rebuild it from scratch
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ): inc={$inc} - LOADED! ");
- loadInclude($INC);
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ): inc={$inc} - LOADED! ");
+ loadInclude($inc);
} else {
// Include not found!
- DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
+ logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
}
} // END - if
} // END - if
}
-// Purge admin menu cache
-function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
- // Is the cache extension enabled or no cache instance or admin menu cache disabled?
- if (!EXT_IS_ACTIVE('cache')) {
- // Cache extension not active
- return false;
- } elseif (!isCacheInstanceValid()) {
- // No cache instance!
- DEBUG_LOG(__FUNCTION__, __LINE__, 'No cache instance found.');
- return false;
- } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
- // Caching disabled (currently experiemental!)
- return false;
- }
-
- // Experiemental feature!
- debug_report_bug("Experimental feature: You have to delete the admin_*.cache files by yourself at this point.");
-}
-
// Determines the real remote address
function determineRealRemoteAddress () {
// Is a proxy in use?
- if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
+ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Proxy was used
$address = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
+ } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
// Yet, another proxy
$address = $_SERVER['HTTP_CLIENT_IP'];
} else {
@@ -3183,7 +3097,7 @@ function determineRealRemoteAddress () {
}
// This strips out the real address from proxy output
- if (strstr($address, ',')){
+ if (strstr($address, ',')) {
$addressArray = explode(',', $address);
$address = $addressArray[0];
} // END - if
@@ -3217,47 +3131,70 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
);
// Mail inserted into bonus pool
- if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
+ if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
} elseif ($output) {
// More entered than can be reached!
- LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
+ loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
} else {
// Debug log
- DEBUG_LOG(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
+ 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 DETERMINE_REFID () {
+function determineReferalId () {
+ // 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 ((REQUEST_ISSET_GET('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
+ if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
+ // This is fine...
+ } elseif ((isGetRequestElementSet('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(REQUEST_GET('user'));
- } elseif (REQUEST_ISSET_POST('refid')) {
+ $GLOBALS['refid'] = bigintval(getRequestElement('user'));
+ } elseif (isPostRequestElementSet('refid')) {
// Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = strip_tags(REQUEST_POST('refid'));
- } elseif (REQUEST_ISSET_GET('refid')) {
+ $GLOBALS['refid'] = secureString(postRequestElement('refid'));
+ } elseif (isGetRequestElementSet('refid')) {
// Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = strip_tags(REQUEST_GET('refid'));
- } elseif (REQUEST_ISSET_GET('ref')) {
+ $GLOBALS['refid'] = secureString(getRequestElement('refid'));
+ } elseif (isGetRequestElementSet('ref')) {
// Set refid=ref (the referal link uses such variable)
- $GLOBALS['refid'] = strip_tags(REQUEST_GET('ref'));
+ $GLOBALS['refid'] = secureString(getRequestElement('ref'));
} elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
// Set session refid als global
$GLOBALS['refid'] = bigintval(getSession('refid'));
- } elseif ((GET_EXT_VERSION('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 ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
+ } 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') && (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 (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
@@ -3266,72 +3203,80 @@ function DETERMINE_REFID () {
return $GLOBALS['refid'];
}
-// Enables the reset mode. Only call this function if you really want the
-// reset to be run!
-function enableResetMode () {
+// Enables the reset mode and runs it
+function doReset () {
// Enable the reset mode
$GLOBALS['reset_enabled'] = true;
// Run filters
- runFilterChain('reset_enabled');
+ runFilterChain('reset');
}
// Our shutdown-function
function shutdown () {
// Call the filter chain 'shutdown'
- runFilterChain('shutdown', null, false);
+ runFilterChain('shutdown', null);
if (SQL_IS_LINK_UP()) {
// Close link
SQL_CLOSE(__FILE__, __LINE__);
- } elseif ((!isInstalling()) && (isInstalled())) {
+ } elseif (!isInstallationPhase()) {
// No database link
addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
}
- // Stop executing here
+ // Stop2 executing here
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
function handleCodeMessage () {
- if (REQUEST_ISSET_GET('msg')) {
+ if (isGetRequestElementSet('code')) {
// Default extension is 'unknown'
$ext = 'unknown';
// Is extension given?
- if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
+ if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
- // Convert the 'msg' parameter from URL to a human-readable message
- $message = convertCodeToMessage(REQUEST_GET('msg'));
+ // Convert the 'code' parameter from URL to a human-readable message
+ $message = getMessageFromErrorCode(getRequestElement('code'));
// Load message template
- LOAD_TEMPLATE('message', false, $message);
+ loadTemplate('message', false, $message);
} // END - if
}
@@ -3362,14 +3307,14 @@ function generateExtensionInactiveMessage ($ext_name) {
// Is the extension empty?
if (empty($ext_name)) {
// This should not happen
- trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+ debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
} // END - if
// Default message
$message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
// Is an admin logged in?
- if (IS_ADMIN()) {
+ if (isAdmin()) {
// Then output admin message
$message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
} // END - if
@@ -3383,14 +3328,14 @@ function generateExtensionNotInstalledMessage ($ext_name) {
// Is the extension empty?
if (empty($ext_name)) {
// This should not happen
- trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+ debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
} // END - if
// Default message
$message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
// Is an admin logged in?
- if (IS_ADMIN()) {
+ if (isAdmin()) {
// Then output admin message
$message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
} // END - if
@@ -3416,7 +3361,7 @@ function generateExtensionInactiveNotInstalledMessage ($ext_name) {
break;
default: // Should not happen!
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
+ 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
@@ -3435,7 +3380,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
$excludeArray[] = '.svn';
$excludeArray[] = '.htaccess';
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
// Init includes
$files = array();
@@ -3447,12 +3392,12 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Exclude '.', '..' and entries in $excludeArray automatically
if (in_array($baseFile, $excludeArray, true)) {
// Exclude them
- //* DEBUG: */ OUTPUT_HTML('excluded=' . $baseFile . " ");
+ //* DEBUG: */ outputHtml('excluded=' . $baseFile . ' ');
continue;
} // END - if
// Construct include filename and FQFN
- $fileName = $baseDir . '/' . $baseFile;
+ $fileName = $baseDir . $baseFile;
$FQFN = getConfig('PATH') . $fileName;
// Remove double slashes
@@ -3461,9 +3406,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Check if the base filename 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: */ OUTPUT_HTML('baseDir:' . $baseDir . " ");
- //* DEBUG: */ OUTPUT_HTML('baseFile:' . $baseFile . " ");
- //* DEBUG: */ OUTPUT_HTML('FQFN:' . $FQFN . " ");
+ //* DEBUG: */ outputHtml('baseDir:' . $baseDir . ' ');
+ //* DEBUG: */ outputHtml('baseFile:' . $baseFile . ' ');
+ //* DEBUG: */ outputHtml('FQFN:' . $FQFN . ' ');
// Exclude this one
continue;
@@ -3472,39 +3417,36 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// Skip also files with non-matching prefix genericly
if (($recursive === true) && (isDirectory($FQFN))) {
// Is a redirectory so read it as well
- $files = merge_array($files, getArrayFromDirectory ($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
+ $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
// And skip further processing
continue;
} elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
// Skip this file
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
continue;
} elseif (!isFileReadable($FQFN)) {
// Not readable so skip it
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
continue;
}
// Is the file a PHP script or other?
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
if ((substr($baseFile, -4, 4) == '.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);
- // Try to find it
- $extId = GET_EXT_ID($extName);
-
// Is the extension valid and active?
- if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
+ if (isExtensionNameValid($extName)) {
// Then add this file
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
$files[] = $fileName;
- } elseif ($extId == 0) {
+ } else {
// Add non-extension files as well
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
if ($addBaseDir === true) {
$files[] = $fileName;
} else {
@@ -3515,7 +3457,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
// We found .php file but should not search for them, why?
debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
}
- } else {
+ } elseif (substr($baseFile, -4, 4) == $extension) {
// Other, generic file found
$files[] = $fileName;
}
@@ -3528,10 +3470,351 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
asort($files);
// Return array with include files
- //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '- Left!');
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
return $files;
}
+// Maps a module name into a database table name
+function mapModuleToTable ($moduleName) {
+ // Map only these, still lame code...
+ switch ($moduleName) {
+ // 'index' is the guest's menu
+ case 'index': $moduleName = 'guest'; break;
+ // ... and 'login' the member's menu
+ case 'login': $moduleName = 'member'; break;
+ // Anything else will not be mapped, silently.
+ } // END - switch
+
+ // Return result
+ return $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'));
+ } // END - if
+
+ // Don't execute anything here if we don't need or ext-other is missing
+ if ($GLOBALS['debug_sql_available'] === false) {
+ return;
+ } // END - if
+
+ // Generate record
+ $record = array(
+ 'num_rows' => SQL_NUMROWS($result),
+ 'affected' => SQL_AFFECTEDROWS(),
+ 'sql_str' => $sqlString,
+ 'timing' => $timing,
+ 'file' => basename($F),
+ 'line' => $L
+ );
+
+ // Add it
+ $GLOBALS['debug_sqls'][] = $record;
+}
+
+// Initializes the cache instance
+function initCacheInstance () {
+ // 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') {
+ // Failed to initialize cache sustem
+ addFatalMessage(__FILE__, __LINE__, '(' . __LINE__ . ' ): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
+ } // END - if
+}
+
+// Getter for message from array or raw message
+function getMessageFromIndexedArray ($message, $pos, $array) {
+ // Check if the requested message was found in array
+ if (isset($array[$pos])) {
+ // ... if yes then use it!
+ $ret = $array[$pos];
+ } else {
+ // ... else use default message
+ $ret = $message;
+ }
+
+ // Return result
+ 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'))." ".getModuleDescription($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 = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+ } 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 $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);
+}
+
//////////////////////////////////////////////////
// AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
//////////////////////////////////////////////////
@@ -3545,5 +3828,29 @@ if (!function_exists('html_entity_decode')) {
}
} // END - if
+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 = '') {
+ $ret = array();
+ foreach ((array)$data as $k => $v) {
+ if (is_int($k) && $prefix != null) {
+ $k = urlencode($prefix . $k);
+ } // END - if
+
+ if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
+
+ if (is_array($v) || is_object($v)) {
+ array_push($ret, http_build_query($v, '', $sep, $k));
+ } else {
+ array_push($ret, $k.'='.urlencode($v));
+ }
+ } // END - foreach
+
+ if (empty($sep)) $sep = ini_get('arg_separator.output');
+
+ return implode($sep, $ret);
+ }
+} // END - if
+
// [EOF]
?>