X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=inc%2Ffunctions.php;h=2d4fcf45df00abd20358f9515859241ca8e889f6;hb=247435718942b91af153c729c0347be3af1fecf9;hp=508112789ff98c0d85f315728fd3e445c60a5aea;hpb=c99de9d021ec0e3850ae00640dc9d0c6a6c36df5;p=mailer.git
diff --git a/inc/functions.php b/inc/functions.php
index 508112789f..2d4fcf45df 100644
--- a/inc/functions.php
+++ b/inc/functions.php
@@ -17,7 +17,7 @@
* Needs to be in all Files and every File needs "svn propset *
* svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
* -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder *
+ * Copyright (c) 2003 - 2009 by Roland Haeder *
* For more information visit: http://www.mxchange.org *
* *
* This program is free software; you can redistribute it and/or modify *
@@ -35,68 +35,68 @@
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
* MA 02110-1301 USA *
************************************************************************/
+
// Some security stuff...
if (!defined('__SECURITY')) {
- $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
- require($INC);
-}
+ die();
+} // END - if
// Output HTML code directly or 'render' it. You addionally switch the new-line character off
-function OUTPUT_HTML ($HTML, $newLine = true) {
- // Some global variables
- global $OUTPUT;
+function outputHtml ($htmlCode, $newLine = true) {
+ // Transfer username
+ $username = getMessage('USERNAME_UNKNOWN');
+ if (isset($GLOBALS['username'])) $username = getUsername();
// Do we have HTML-Code here?
- if (!empty($HTML)) {
+ if (!empty($htmlCode)) {
// Yes, so we handle it as you have configured
- switch (getConfig('OUTPUT_MODE'))
- {
+ switch (getConfig('OUTPUT_MODE')) {
case 'render':
// That's why you don't need any \n at the end of your HTML code... :-)
- if (constant('_OB_CACHING') == 'on') {
+ if (getPhpCaching() == 'on') {
// Output into PHP's internal buffer
- outputRawCode($HTML);
+ outputRawCode($htmlCode);
// That's why you don't need any \n at the end of your HTML code... :-)
- if ($newLine) print("\n");
+ if ($newLine === true) print("\n");
} else {
// Render mode for old or lame servers...
- $OUTPUT .= $HTML;
+ $GLOBALS['output'] .= $htmlCode;
// That's why you don't need any \n at the end of your HTML code... :-)
- if ($newLine) $OUTPUT .= "\n";
+ if ($newLine === true) $GLOBALS['output'] .= "\n";
}
break;
case 'direct':
// If we are switching from render to direct output rendered code
- if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
+ if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
// The same as above... ^
- outputRawCode($HTML);
+ outputRawCode($htmlCode);
if ($newLine) print("\n");
break;
default:
// Huh, something goes wrong or maybe you have edited config.php ???
- app_die(__FUNCTION__, __LINE__, "{--FATAL_ERROR--}: {--LANG_NO_RENDER_DIRECT--}");
+ app_die(__FUNCTION__, __LINE__, '{--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!");
+ 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
@@ -112,56 +112,63 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
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());
// 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);
+ // Init counter
+ $cnt = 0;
+ // Compile and run finished rendered HTML code
+ while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
// Prepare the content and eval() it...
+ $content = array();
$newContent = '';
- $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
+
+ // Compile it
+ $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
eval($eval);
// Was that eval okay?
if (empty($newContent)) {
// Something went wrong!
- app_die(__FUNCTION__, __LINE__, 'Evaluation error:
' . htmlentities($eval) . ' ');
+ debug_report_bug('Evaluation error:' . linenumberCode($eval) . ' ');
} // END - if
- $OUTPUT = $newContent;
+ $GLOBALS['output'] = $newContent;
+
+ // Count round
+ $cnt++;
} // END - while
// 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);
+ while (strpos($GLOBALS['output'], '{!') > 0) {
+ eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
} // END - while
// Output code here, DO NOT REMOVE! ;-)
- outputRawCode($OUTPUT);
+ outputRawCode($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(stripslashes(stripslashes($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
@@ -191,7 +198,8 @@ 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, " message={$message}");
}
// Getter for total fatal message count
@@ -210,200 +218,375 @@ 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) . ')');
- // Add more variables which you want to use in your template files
- global $DATA, $username;
+ // @TODO Try to rewrite all $DATA to $content
+ global $DATA;
+
+ // Do we have cache?
+ if (!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);
+
+ // Count the template load
+ incrementConfigEntry('num_templates');
+
+ // Init some data
+ $ret = '';
+ if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
+
+ // Generate date/time string
+ $date_time = generateDateTime(time(), 1);
+
+ // Is content an array
+ if (is_array($content)) $content['date_time'] = $date_time;
+
+ // @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__);
+
+ // Is content an array?
+ if (is_array($content)) {
+ // Merge data
+ $content = merge_array($content, SQL_FETCHARRAY($result));
+
+ // Translate gender
+ $content['gender'] = translateGender($content['gender']);
+ } 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);
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
+ }
+
+ // Free result
+ SQL_FREERESULT($result);
+ } // END - if
+
+ // Base directory
+ $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
+ $mode = '';
+
+ // Check for admin/guest/member templates
+ if (substr($template, 0, 6) == 'admin_') {
+ // Admin template found
+ $mode = 'admin/';
+ } elseif (substr($template, 0, 6) == 'guest_') {
+ // Guest template found
+ $mode = 'guest/';
+ } elseif (substr($template, 0, 7) == 'member_') {
+ // Member template found
+ $mode = 'member/';
+ } elseif (substr($template, 0, 8) == 'install_') {
+ // Installation template found
+ $mode = 'install/';
+ } elseif (substr($template, 0, 4) == 'ext_') {
+ // Extension template found
+ $mode = 'ext/';
+ } elseif (substr($template, 0, 3) == 'la_') {
+ // 'Logical-area' template found
+ $mode = 'la/';
+ } elseif (substr($template, 0, 3) == 'js_') {
+ // JavaScript template found
+ $mode = 'js/';
+ } elseif (substr($template, 0, 5) == 'menu_') {
+ // Menu template found
+ $mode = 'menu/';
+ } else {
+ // Test for extension
+ $test = substr($template, 0, strpos($template, '_'));
+
+ // Probe for valid extension name
+ if (isExtensionNameValid($test)) {
+ // Set extra path to extension's name
+ $mode = $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()
+ );
+
+ // Probe for it...
+ if (isFileReadable($file2)) $FQFN = $file2;
+
+ // Remove variable from memory
+ unset($file2);
+ } // END - if
+
+ // Does the special template exists?
+ if (!isFileReadable($FQFN)) {
+ // Reset to default template
+ $FQFN = $basePath . $template . '.tpl';
+ } // END - if
+
+ // Now does the final template exists?
+ if (isFileReadable($FQFN)) {
+ // The local file does exists so we load it. :)
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
+
+ // Replace ' to our own chars to preventing them being quoted
+ while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
+
+ // 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 ($GLOBALS['output_mode'] == 0) {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = "\n" . $GLOBALS['tpl_content'] . "\n";
+
+ // Prepare eval() command
+ $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
+ } else {
+ // Prepare eval() command
+ $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
+ }
+ } else {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = "\n" . $GLOBALS['tpl_content'] . "\n";
+ $eval = '$ret = "' . smartAddSlashes($ret) . '";';
+ } // END - if
+
+ // Cache the eval() command here
+ $GLOBALS['template_eval'][$template] = $eval;
+
+ // Eval the code
+ eval($GLOBALS['template_eval'][$template]);
+ } else {
+ // No file!
+ $GLOBALS['template_eval'][$template] = '404';
+ }
+ } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
+ // 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 {
+ // Eval the code
+ eval($GLOBALS['template_eval'][$template]);
+ }
+
+ // 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
+ outputHtml($ret);
+ }
+ } elseif (isDebugModeEnabled()) {
+ // Warning, empty output!
+ return 'E:' . $template . ',content=' . print_r($content, true) . ' ';
+ }
+}
- // Get whole config array
+// Loads an email template and compiles it
+function loadEmailTemplate ($template, $content = array(), $UID = 0) {
+ global $DATA;
+
+ // Our configuration is kept non-global here
$_CONFIG = getConfigArray();
- // Make all template names lowercase
+ // Make sure all template names are lowercase!
$template = strtolower($template);
- // Count the template load
- incrementConfigEntry('num_templates');
+ // Default 'nickname' if extension is not installed
+ $nick = '---';
// Prepare IP number and User Agent
$REMOTE_ADDR = detectRemoteAddr();
- if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
$HTTP_USER_AGENT = detectUserAgent();
- // Init some data
- $ret = '';
- if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
+ // 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
- // @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__);
+ // Neutral email address is default
+ $email = getConfig('WEBMASTER');
- // Is content an array?
- if (is_array($content)) {
- // Merge data
- $content = merge_array($content, SQL_FETCHARRAY($result));
+ // 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'));
+ }
- // Translate gender
- $content['gender'] = translateGender($content['gender']);
+ // 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 (isExtensionActive('nickname')) {
+ //* DEBUG: */ outputHtml(__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 {
- // @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));
+ //* DEBUG: */ outputHtml(__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: */ outputHtml(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - PRE ");
+ $content = merge_array($content, SQL_FETCHARRAY($result));
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):content()=".count($content)." - AFTER ");
+
// Free result
SQL_FREERESULT($result);
} // END - if
- // Generate date/time string
- $date_time = generateDateTime(time(), '1');
+ // 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/html/", constant('PATH'), getLanguage());
- $mode = '';
+ $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
// 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) {
+ $FQFN = $basePath.'admin/' . $template.'.tpl';
+ } elseif (substr($template, 0, 6) == 'guest_') {
// Guest template found
- $mode = 'guest/';
- } elseif (strpos($template, 'member_') > -1) {
+ $FQFN = $basePath.'guest/' . $template.'.tpl';
+ } elseif (substr($template, 0, 7) == 'member_') {
// Member template found
- $mode = 'member/';
- } elseif (strpos($template, 'install_') > -1) {
- // Installation template found
- $mode = 'install/';
- } elseif (strpos($template, 'ext_') > -1) {
- // Extension template found
- $mode = 'ext/';
- } elseif (strpos($template, 'la_') > -1) {
- // 'Logical-area' template found
- $mode = 'la/';
- } elseif (strpos($template, 'js_') > -1) {
- // JavaScript template found
- $mode = 'js/';
+ $FQFN = $basePath.'member/' . $template.'.tpl';
} else {
// Test for extension
$test = substr($template, 0, strpos($template, '_'));
- if (EXT_IS_ACTIVE($test)) {
+ if (isExtensionNameValid($test)) {
// Set extra path to extension's name
- $mode = $test . '/';
- } // END - if
+ $FQFN = $basePath . $test.'/' . $template.'.tpl';
+ } else {
+ // No special filename
+ $FQFN = $basePath . $template.'.tpl';
+ }
}
- ////////////////////////
- // 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()
- );
-
- // Probe for it...
- if (isFileReadable($file2)) $FQFN = $file2;
-
- // Remove variable from memory
- unset($file2);
- } // END - if
-
// Does the special template exists?
if (!isFileReadable($FQFN)) {
// Reset to default template
- $FQFN = $basePath . $template . '.tpl';
+ $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);
-
- // Replace ' to our own chars to preventing them being quoted
- while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
+ $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
- // Do we have to compile the code?
- $ret = '';
- if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
- // Okay, compile it!
- $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
- eval($tmpl_file);
- } else {
- // Simply return loaded code
- $ret = $tmpl_file;
- }
-
- // 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(\"".compileCode($GLOBALS['tpl_content'])."\");";
+ eval($GLOBALS['tpl_content']);
+ } 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 = 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";
- }
+ // Compile the code and eval it
+ $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
+ eval($eval);
+
+ // 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(\"".compileCode(smartAddSlashes($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",
+ $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)." ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):numRows=".SQL_NUMROWS($result_email)." ");
// Does the user exist?
if (SQL_NUMROWS($result_email)) {
@@ -411,65 +594,63 @@ function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '')
list($toEmail) = SQL_FETCHROW($result_email);
} else {
// Set webmaster
- $toEmail = constant('WEBMASTER');
+ $toEmail = getConfig('WEBMASTER');
}
// Free result
SQL_FREERESULT($result_email);
}
- } elseif ($toEmail == '0') {
+ } elseif ($toEmail == 0) {
// Is the webmaster!
- $toEmail = constant('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 = \"".compileCode(smartAddSlashes($toEmail))."\";");
// Compile "MSG"
- $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
- eval($eval);
+ eval("\$message = \"".compileCode(smartAddSlashes($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 : ' . htmlentities(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(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
+ sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
}
}
@@ -490,7 +671,7 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
// get new instance
$mail = new PHPMailer();
- $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
+ $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
$mail->IsSMTP();
$mail->SMTPAuth = true;
@@ -499,13 +680,13 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
$mail->Username = getConfig('SMTP_USER');
$mail->Password = getConfig('SMTP_PASSWORD');
if (empty($from)) {
- $mail->From = constant('WEBMASTER');
+ $mail->From = getConfig('WEBMASTER');
} else {
$mail->From = $from;
}
- $mail->FromName = constant('MAIN_TITLE');
+ $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;
@@ -514,9 +695,9 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
$mail->Body = decodeEntities($message);
}
$mail->AddAddress($toEmail, '');
- $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
- $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
- $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
+ $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
+ $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
+ $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
$mail->Send();
} else {
// Use legacy mail() command
@@ -550,7 +731,7 @@ function generatePassword ($length = 0) {
}
// Generates a human-readable timestamp from the Uni* stamp
-function generateDateTime ($time, $mode = '0') {
+function generateDateTime ($time, $mode = 0) {
// Filter out numbers
$time = bigintval($time);
@@ -560,44 +741,45 @@ function generateDateTime ($time, $mode = '0') {
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 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;
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;
}
@@ -614,7 +796,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
@@ -626,7 +808,7 @@ function translatePoolType ($type) {
// Translates the american decimal dot into a german comma
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');
@@ -635,7 +817,7 @@ 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) {
@@ -645,15 +827,15 @@ function translateComma ($dotted, $cut = true, $max = 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;
}
@@ -674,7 +856,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;
}
@@ -684,8 +866,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':
@@ -698,21 +880,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(constant('URL'))) != constant('URL')) {
+ 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
@@ -720,194 +902,58 @@ 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))
+ $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
+ 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 = constant('MAIN_TITLE');
-
- // Is the admin logged in?
- if (IS_ADMIN()) {
- // Get admin id
- $aid = getCurrentAdminId();
-
- // Load Admin data
- $ADMIN = getAdminEmail($aid);
+ // Integrity check
+ if (!is_array($array)) {
+ // Not an array!
+ debug_report_bug(__FUNCTION__.': No array provided.');
} // END - if
- // Neutral email address is default
- $email = constant('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: */ 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 ");
-
- // 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/", constant('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');
- }
+ // Init count
+ $ret = 0;
- // 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
@@ -918,38 +964,38 @@ function redirectToUrl ($URL) {
// Check if http(s):// is there
if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
// Make all URLs full-qualified
- $URL = constant('URL') . '/' . $URL;
+ $URL = getConfig('URL') . '/' . $URL;
} // END - if
// 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);
//* DEBUG: */ die($URL);
// Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
$rel = ' rel="external"';
// Do we have internal or external URL?
- if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
+ if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
// Own (=internal) URL
$rel = '';
} // 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}");
@@ -957,7 +1003,7 @@ function redirectToUrl ($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');
}
@@ -973,15 +1019,15 @@ 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);
}
-//
-function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
+// 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
@@ -992,17 +1038,20 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $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'];
+ if ($full === false) $secChars = $GLOBALS['url_chars'];
+
+ // Compile more through a filter
+ $code = runFilterChain('compile_code', $code);
// Compile constants
if ($constants === true) {
// BEFORE 0.2.1 : Language and data constants
// WITH 0.2.1+ : Only language constants
- $code = str_replace('{--','".', str_replace('--}','."', $code));
+ $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
// BEFORE 0.2.1 : Not used
// WITH 0.2.1+ : Data constants
- $code = str_replace('{!','".', str_replace("!}", '."', $code));
+ $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
} // END - if
// Compile QUOT and other non-HTML codes
@@ -1015,7 +1064,7 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
if ($simple) $code = str_replace("'", '{QUOT}', $code);
// Find $content[bla][blub] entries
- preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
+ preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
// Are some matches found?
if ((count($matches) > 0) && (count($matches[0]) > 0)) {
@@ -1031,29 +1080,29 @@ 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
} // END - foreach
// Skip this entry?
- if ($fuzzyFound) continue;
+ if ($fuzzyFound === true) continue;
// 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} ");
- $newMatch = str_replace("[" . $matches[4][$key]."]", "['" . $matches[4][$key]."']", $match);
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):key={$key},match={$match} ");
+ $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
$code = str_replace($match, "\"." . $newMatch.".\"", $code);
- $matchesFound[$key."_" . $matches[4][$key]] = 1;
+ $matchesFound[$key . '_' . $matches[4][$key]] = 1;
$matchesFound[$match] = 1;
} elseif (!isset($matchesFound[$match])) {
// Not yet replaced!
- //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(".__LINE__." ):match={$match} ");
+ //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__." ):match={$match} ");
$code = str_replace($match, "\"." . $match.".\"", $code);
$matchesFound[$match] = 1;
}
@@ -1086,7 +1135,7 @@ function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
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) {
@@ -1116,7 +1165,7 @@ 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) {
$OUT = '';
if ($type == 'yn') {
@@ -1132,7 +1181,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
}
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 {
@@ -1181,7 +1230,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 {
@@ -1198,19 +1247,19 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
}
break;
- case "sec":
- case "min":
+ case 'sec':
+ case 'min':
for ($idx = 0; $idx < 60; $idx+=5) {
- if (strlen($idx) == 1) $idx = '0' . $idx;
+ if (strlen($idx) == 1) $idx = 0 . $idx;
$OUT .= "\n";
} // END - for
break;
- case "hour":
+ case 'hour':
for ($idx = 0; $idx < 24; $idx++) {
- if (strlen($idx) == 1) $idx = '0' . $idx;
+ if (strlen($idx) == 1) $idx = 0 . $idx;
$OUT .= " \n";
@@ -1221,7 +1270,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
$OUT .= " 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
// Stop execution of function here because of over-sized code length
return;
- } elseif (!$headerSent) {
+ } elseif ($headerSent === false) {
// Return in an HTML code code
- return " \n";
+ return " \n";
}
// Load image
- $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
+ $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
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;
}
@@ -1369,7 +1416,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
$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)));
@@ -1378,19 +1425,19 @@ 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?
@@ -1550,7 +1597,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
}
//
-function createTimestampFromSelections ($prefix, $POST) {
+function createTimestampFromSelections ($prefix, $postData) {
// Initial return value
$ret = 0;
@@ -1559,89 +1606,25 @@ function createTimestampFromSelections ($prefix, $POST) {
$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/...
@@ -1650,8 +1633,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
@@ -1669,10 +1651,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 = " ";
}
@@ -1680,56 +1662,54 @@ 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);
}
}
// Extract host from script name
function extractHostnameFromUrl (&$script) {
// Use default SERVER_URL by default... ;) So?
- $url = constant('SERVER_URL');
+ $url = getConfig('SERVER_URL');
// Is this URL valid?
if (substr($script, 0, 7) == 'http://') {
@@ -1762,25 +1742,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: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
- if (defined('FULL_VERSION')) {
- $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . 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');
} else {
- $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . 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);
@@ -1794,28 +1786,28 @@ 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);
+ $script = compileCode($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: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
- $request .= "User-Agent: " . constant('TITLE') . '/' . constant('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
@@ -1837,7 +1829,7 @@ 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
@@ -1846,7 +1838,7 @@ function sendRawRequest ($host, $request) {
//* 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(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
} else {
// Connect to host directly
$fp = @fsockopen($host, 80, $errno, $errdesc, 30);
@@ -1867,7 +1859,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(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
$proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
} // END - if
@@ -1942,7 +1934,7 @@ function sendRawRequest ($host, $request) {
// Taken from www.php.net eregi() user comments
function isEmailValid ($email) {
// Compile email
- $email = COMPILE_CODE($email);
+ $email = compileCode($email);
// Check first part of email address
$first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
@@ -1961,14 +1953,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
@@ -1979,37 +1971,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;
@@ -2021,19 +2015,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;
@@ -2042,7 +2036,7 @@ function generateEmailLink ($email, $table = 'admins') {
// Generate a hash for extra-security for all passwords
function generateHash ($plainText, $salt = '') {
// Is the required extension 'sql_patches' there and a salt is not given?
- if (((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'))) && (empty($salt))) {
// Extension sql_patches is missing/outdated so we hash the plain text with MD5
return md5($plainText);
} // END - if
@@ -2056,32 +2050,32 @@ function generateHash ($plainText, $salt = '') {
// 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
$salt = substr($salt, 0, getConfig('salt_length'));
- //* DEBUG: */ OUTPUT_HTML("GIVEN={$salt} ");
+ //* DEBUG: */ outputHtml("GIVEN={$salt} ");
}
// Return hash
@@ -2106,7 +2100,7 @@ function scrambleString($str) {
}
// Scramble string here
- //* DEBUG: */ OUTPUT_HTML("***Original=" . $str."*** ");
+ //* DEBUG: */ outputHtml("***Original=" . $str."*** ");
for ($idx = 0; $idx < strlen($str); $idx++) {
// Get char on scrambled position
$char = substr($str, $scrambleNums[$idx], 1);
@@ -2116,7 +2110,7 @@ function scrambleString($str) {
} // END - for
// Return scrambled string
- //* DEBUG: */ OUTPUT_HTML("***Scrambled=" . $scrambled."*** ");
+ //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."*** ");
return $scrambled;
}
@@ -2133,14 +2127,14 @@ function descrambleString($str) {
// Begin descrambling
$orig = str_repeat(' ', 40);
- //* DEBUG: */ OUTPUT_HTML("+++Scrambled=" . $str."+++ ");
+ //* 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;
}
@@ -2174,7 +2168,7 @@ 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')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
// Only calculate when the secret key is generated
$newHash = ''; $start = 9;
for ($idx = 0; $idx < 10; $idx++) {
@@ -2187,8 +2181,8 @@ function generatePassString ($passHash) {
$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 = str_repeat(0, 4-strlen($mod)) . $mod;
+ //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."* ");
$start += 4;
$newHash .= $mod;
} // END - for
@@ -2198,9 +2192,9 @@ function generatePassString ($passHash) {
//* DEBUG: */ print($ret." ");
} else {
// Hash it simple
- //* DEBUG: */ OUTPUT_HTML("--" . $passHash."-- ");
+ //* DEBUG: */ outputHtml("--" . $passHash."-- ");
$ret = md5($passHash);
- //* DEBUG: */ OUTPUT_HTML("++" . $ret."++ ");
+ //* DEBUG: */ outputHtml("++" . $ret."++ ");
}
// Return result
@@ -2235,10 +2229,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');
@@ -2264,17 +2258,15 @@ function displayParsingTime() {
$end = explode(' ', $endTime);
$runTime = $end[0] - $start[0];
if ($runTime < 0) $runTime = 0;
- $runTime = translateComma($runTime);
// 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
@@ -2286,14 +2278,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
@@ -2313,7 +2305,7 @@ function isApacheModuleLoaded ($apacheModule) {
}
// Get current theme name
-function getCurrentTheme() {
+function getCurrentTheme () {
// The default theme is 'default'... ;-)
$ret = 'default';
@@ -2322,8 +2314,8 @@ function getCurrentTheme() {
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');
@@ -2333,40 +2325,40 @@ function getCurrentTheme() {
// 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", constant('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", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+ setTheme(getRequestElement('theme'));
+ } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
// Set cookie from posted data
- setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
+ setTheme(SQL_ESCAPE(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
@@ -2380,11 +2372,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 (getExtensionVersion('cache') != '0.1.8') {
// Check if current theme is already imported or not
- $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
- array($name), __FUNCTION__, __LINE__);
+ $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) {
@@ -2420,7 +2412,7 @@ function generateErrorCodeFromUserStatus ($status) {
$errorCode = getCode($constantName);
} 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
@@ -2430,33 +2422,33 @@ 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) {
// Generate proper FQFN
- $FQFN = str_replace('//', '/', constant('PATH') . $dir. '/'. $d);
+ $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
@@ -2469,50 +2461,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", constant('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 {
@@ -2526,13 +2487,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]]);
}
@@ -2541,7 +2507,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
}
}
@@ -2550,7 +2520,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;
@@ -2586,27 +2556,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 {
@@ -2615,14 +2585,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. :-)
@@ -2650,21 +2621,22 @@ function debug_get_printable_backtrace () {
function debug_report_bug ($message = '') {
// Init message
$debug = '';
+
// Is the optional message set?
if (!empty($message)) {
// Use and log it
$debug = sprintf("Note: %s \n",
- $message
+ $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 " . 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
@@ -2680,20 +2652,41 @@ function generateSeed () {
}
// 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('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');
@@ -2701,24 +2694,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
@@ -2726,29 +2741,29 @@ function convertCodeToMessage ($code) {
return $message;
}
-// Generate a "link" for the given admin id (aid)
-function generateAdminLink ($aid) {
+// Generate a "link" for the given admin id (admin_id)
+function generateAdminLink ($adminId) {
// No assigned admin is default
$admin = "{--ADMIN_NO_ADMIN_ASSIGNED--} ";
// Zero? = Not assigned
- if (bigintval($aid) > 0) {
+ if (bigintval($adminId) > 0) {
// Load admin's login
- $login = getAdminLogin($aid);
+ $login = getAdminLogin($adminId);
// Is the login valid?
if ($login != '***') {
// Is the extension there?
- if (EXT_IS_ACTIVE('admins')) {
+ if (isExtensionActive('admins')) {
// Admin found
- $admin = "" . $login." ";
+ $admin = "" . $login." ";
} else {
// Extension not found
$admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
}
} else {
// Maybe deleted?
- $admin = "".sprintf(getMessage('ADMIN_ID_404'), $aid)."
";
+ $admin = "".sprintf(getMessage('ADMIN_ID_404'), $adminId)."
";
}
} // END - if
@@ -2759,7 +2774,7 @@ function generateAdminLink ($aid) {
// 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}', '.',
@@ -2781,7 +2796,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("\\", '', compileCode(urldecode($url))));
// Allows http and https
$http = "(http|https)+(:\/\/)";
@@ -2829,7 +2844,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
@@ -2858,15 +2873,19 @@ 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);
@@ -2901,90 +2920,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 (getExtensionVersion('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(constant('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() . '|' . 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
@@ -3019,7 +2993,7 @@ 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
$test2 = '';
@@ -3030,14 +3004,14 @@ 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]);
// 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
@@ -3076,7 +3050,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 = '';
@@ -3085,14 +3059,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
@@ -3105,59 +3079,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 {
@@ -3166,7 +3124,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
@@ -3200,38 +3158,43 @@ 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
+ if (getOutputMode() != 0) 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 {
@@ -3240,7 +3203,7 @@ function DETERMINE_REFID () {
}
// 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) && (getConfig('def_refid') > 0))) {
// Set cookie
setSession('refid', $GLOBALS['refid']);
} // END - if
@@ -3249,25 +3212,24 @@ 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'));
}
@@ -3303,18 +3265,18 @@ function isUserIdSet () {
// 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
}
@@ -3345,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
@@ -3366,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
@@ -3399,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
@@ -3418,25 +3380,25 @@ 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();
// Open directory
- $dirPointer = opendir(constant('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
+ $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
// Read all entries
while ($baseFile = readdir($dirPointer)) {
// Exclude '.', '..' and entries in $excludeArray automatically
if (in_array($baseFile, $excludeArray, true)) {
// Exclude them
- //* DEBUG: */ OUTPUT_HTML('excluded=' . $baseFile . " ");
+ //* DEBUG: */ outputHtml('excluded=' . $baseFile . " ");
continue;
} // END - if
// Construct include filename and FQFN
- $fileName = $baseDir . '/' . $baseFile;
- $FQFN = constant('PATH') . $fileName;
+ $fileName = $baseDir . $baseFile;
+ $FQFN = getConfig('PATH') . $fileName;
// Remove double slashes
$FQFN = str_replace('//', '/', $FQFN);
@@ -3444,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;
@@ -3455,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 {
@@ -3498,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;
}
@@ -3511,10 +3470,99 @@ 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) {
+ // Don't execute anything here if we don't need
+ if (getConfig('display_debug_sqls') != 'Y') return;
+
+ // 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);
+}
+
//////////////////////////////////////////////////
// AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
//////////////////////////////////////////////////
@@ -3528,5 +3576,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]
?>