+<?php
+/************************************************************************
+ * Mailer v0.2.1-FINAL Start: 04/04/2009 *
+ * =================== Last change: 04/04/2009 *
+ * *
+ * -------------------------------------------------------------------- *
+ * File : template-functions.php *
+ * -------------------------------------------------------------------- *
+ * Short description : Template functions *
+ * -------------------------------------------------------------------- *
+ * Kurzbeschreibung : Template-Funktionen *
+ * -------------------------------------------------------------------- *
+ * $Revision:: $ *
+ * $Date:: $ *
+ * $Tag:: 0.2.1-FINAL $ *
+ * $Author:: $ *
+ * Needs to be in all Files and every File needs "svn propset *
+ * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
+ * -------------------------------------------------------------------- *
+ * Copyright (c) 2003 - 2009 by Roland Haeder *
+ * Copyright (c) 2009, 2010 by Mailer Developer Team *
+ * For more information visit: http://www.mxchange.org *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
+ * MA 02110-1301 USA *
+ ************************************************************************/
+
+// Some security stuff...
+if (!defined('__SECURITY')) {
+ die();
+} // END - if
+
+// Wrapper until we merged to the EL branch
+function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
+ return compileCode($code, false, true, $full);
+}
+
+// Setter for 'is_template_html'
+function enableTemplateHtml ($enable = true) {
+ $GLOBALS['is_template_html'] = (bool) $enable;
+}
+
+// Checks wether the template is HTML or not by previously set flag
+// Default: true
+function isTemplateHtml () {
+ // Is the output_mode other than 0 (HTML), then no comments are enabled
+ if (getOutputMode() != 0) {
+ // No HTML
+ return false;
+ } else {
+ // Maybe HTML?
+ return $GLOBALS['is_template_html'];
+ }
+}
+
+// Wrapper for writing debug informations to the browser
+function debugOutput ($message) {
+ outputHtml('<div class="debug_message">' . $message . '</div>');
+}
+
+// "Fixes" an empty string into three dashes (use for templates)
+function fixEmptyContentToDashes ($str) {
+ // Trim the string
+ $str = trim($str);
+
+ // Is the string empty?
+ if (empty($str)) $str = '---';
+
+ // Return string
+ return $str;
+}
+
+// Color-switch helper function
+function doTemplateColorSwitch ($template, $clear = false, $return = true) {
+ // Is it there?
+ if (!isset($GLOBALS['color_switch'][$template])) {
+ // Initialize it
+ initTemplateColorSwitch($template);
+ } elseif ($clear === false) {
+ // Switch color if called from loadTemplate()
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
+ $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
+ } // END - if
+
+ // Return CSS class name
+ if ($return === true) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
+ return 'switch_sw' . $GLOBALS['color_switch'][$template];
+ } // END - if
+}
+
+// Init color switch
+function initTemplateColorSwitch ($template) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
+ $GLOBALS['color_switch'][$template] = 2;
+}
+
+// "Getter" for color switch code
+function getColorSwitchCode ($template) {
+ // Prepare the code
+ $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
+
+ // And return it
+ return $code;
+}
+
+// Output HTML code directly or 'render' it. You addionally switch the new-line character off
+function outputHtml ($htmlCode, $newLine = true) {
+ // Init output
+ if (!isset($GLOBALS['output'])) {
+ $GLOBALS['output'] = '';
+ } // END - if
+
+ // Do we have HTML-Code here?
+ if (!empty($htmlCode)) {
+ // Yes, so we handle it as you have configured
+ switch (getConfig('OUTPUT_MODE')) {
+ case 'render':
+ // That's why you don't need any \n at the end of your HTML code... :-)
+ if (getPhpCaching() == 'on') {
+ // Output into PHP's internal buffer
+ outputRawCode($htmlCode);
+
+ // That's why you don't need any \n at the end of your HTML code... :-)
+ if ($newLine === true) print("\n");
+ } else {
+ // Render mode for old or lame servers...
+ $GLOBALS['output'] .= $htmlCode;
+
+ // That's why you don't need any \n at the end of your HTML code... :-)
+ if ($newLine === true) $GLOBALS['output'] .= "\n";
+ }
+ break;
+
+ case 'direct':
+ // If we are switching from render to direct output rendered code
+ if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
+
+ // The same as above... ^
+ outputRawCode($htmlCode);
+ if ($newLine === true) print("\n");
+ break;
+
+ default:
+ // Huh, something goes wrong or maybe you have edited config.php ???
+ debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
+ break;
+ } // END - switch
+ } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
+ // Output cached HTML code
+ $GLOBALS['output'] = ob_get_contents();
+
+ // Clear output buffer for later output if output is found
+ if (!empty($GLOBALS['output'])) {
+ clearOutputBuffer();
+ } // END - if
+
+ // Send all HTTP headers
+ sendHttpHeaders();
+
+ // Compile and run finished rendered HTML code
+ compileFinalOutput();
+
+ // Output code here, DO NOT REMOVE! ;-)
+ outputRawCode($GLOBALS['output']);
+ } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
+ // Send all HTTP headers
+ sendHttpHeaders();
+
+ // Compile and run finished rendered HTML code
+ compileFinalOutput();
+
+ // Output code here, DO NOT REMOVE! ;-)
+ outputRawCode($GLOBALS['output']);
+ } else {
+ // And flush all headers
+ flushHeaders();
+ }
+}
+
+// Compiles the final output
+function compileFinalOutput () {
+ // Add page header and footer
+ addPageHeaderFooter();
+
+ // Do the final compilation
+ $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
+
+ // Extension 'rewrite' installed?
+ if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
+ $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
+ } // END - if
+
+ // Compress it?
+ if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+ // Compress it for HTTP gzip
+ $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
+
+ // Add header
+ sendHeader('Content-Encoding: gzip');
+ } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+ // Compress it for HTTP deflate
+ $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
+
+ // Add header
+ sendHeader('Content-Encoding: deflate');
+ }
+
+ // Add final length
+ sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
+
+ // Flush all headers
+ flushHeaders();
+}
+
+// Main compilation loop
+function doFinalCompilation ($code, $insertComments = true) {
+ // Insert comments? (Only valid with HTML templates, of course)
+ enableTemplateHtml($insertComments);
+
+ // Init counter
+ $cnt = 0;
+
+ // Compile all out
+ while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 4)) {
+ // Init common variables
+ $content = array();
+ $newContent = '';
+
+ // Compile it
+ //* DEBUG: */ debugOutput('<pre>'.encodeEntities($code).'</pre>');
+ $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code))) . '";';
+ //* DEBUG: */ if ($insertComments) die('<pre>'.linenumberCode($eval).'</pre>');
+ eval($eval);
+ //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
+
+ // Was that eval okay?
+ if (empty($newContent)) {
+ // Something went wrong!
+ debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
+ } // END - if
+
+ // Use it again
+ $code = $newContent;
+
+ // Count round
+ $cnt++;
+ } // END - while
+
+ // Return the compiled code
+ return $code;
+}
+
+// Output the raw HTML code
+function outputRawCode ($htmlCode) {
+ // Output stripped HTML code to avoid broken JavaScript code, etc.
+ print(str_replace('{BACK}', "\\", $htmlCode));
+
+ // Flush the output if only getPhpCaching() is not 'on'
+ if (getPhpCaching() != 'on') {
+ // Flush it
+ flush();
+ } // END - if
+}
+
+// Load a template file and return it's content (only it's name; do not use ' or ")
+function loadTemplate ($template, $return = false, $content = array()) {
+ // @TODO Remove this sanity-check if all is fine
+ if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
+
+ // Set current template
+ $GLOBALS['current_template'] = $template;
+
+ // Do we have cache?
+ if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
+ // Evaluate the cache
+ eval(readTemplateCache($template));
+ } elseif (!isset($GLOBALS['template_eval'][$template])) {
+ // Make all template names lowercase
+ $template = strtolower($template);
+
+ // Init some data
+ $ret = '';
+ if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
+
+ // Base directory
+ $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
+ $extraPath = detectExtraTemplatePath($template);;
+
+ ////////////////////////
+ // Generate file name //
+ ////////////////////////
+ $FQFN = $basePath . $extraPath . $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?
+ if (isFileReadable($FQFN)) {
+ // Count the template load
+ incrementConfigEntry('num_templates');
+
+ // The local file does exists so we load it. :)
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
+
+ // Do we have to compile the code?
+ $ret = '';
+ if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
+ // Normal HTML output?
+ if (getOutputMode() == '0') {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
+
+ // Prepare eval() command
+ $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
+ } elseif (substr($template, 0, 3) == 'js_') {
+ // JavaScripts don't like entities and timings
+ $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
+ } else {
+ // Prepare eval() command, other output doesn't like entities, maybe
+ $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
+ }
+ } else {
+ // Add surrounding HTML comments to help finding bugs faster
+ $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
+ $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
+ } // END - if
+ } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
+ // Only admins shall see this warning or when installation mode is active
+ $ret = '<div class="para">
+ <span class="guest_failed">{--TEMPLATE_404--}</span>
+</div>
+<div class="para">
+ (' . $template . ')
+</div>
+<div class="para">
+ {--TEMPLATE_CONTENT--}
+ <pre>' . print_r($content, true) . '</pre>
+ {--TEMPLATE_DATA--}
+ <pre>' . print_r($DATA, true) . '</pre>
+</div>';
+ } else {
+ // No file!
+ $GLOBALS['template_eval'][$template] = '404';
+ }
+ }
+
+ // Code set?
+ if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
+ // Eval the code
+ eval($GLOBALS['template_eval'][$template]);
+ } // END - if
+
+ // Do we have some content to output or return?
+ if (!empty($ret)) {
+ // Not empty so let's put it out! ;)
+ if ($return === true) {
+ // Return the HTML code
+ return $ret;
+ } else {
+ // Output directly
+ outputHtml($ret);
+ }
+ } elseif (isDebugModeEnabled()) {
+ // Warning, empty output!
+ return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
+ }
+}
+
+// Detects the extra template path from given template name
+function detectExtraTemplatePath ($template) {
+ // Default is empty
+ $extraPath = '';
+
+ // Do we have cache?
+ if (!isset($GLOBALS['extra_path'][$template])) {
+ // Check for admin/guest/member/etc. templates
+ if (substr($template, 0, 6) == 'admin_') {
+ // Admin template found
+ $extraPath = 'admin/';
+ } elseif (substr($template, 0, 6) == 'guest_') {
+ // Guest template found
+ $extraPath = 'guest/';
+ } elseif (substr($template, 0, 7) == 'member_') {
+ // Member template found
+ $extraPath = 'member/';
+ } elseif (substr($template, 0, 7) == 'select_') {
+ // Selection template found
+ $extraPath = 'select/';
+ } elseif (substr($template, 0, 8) == 'install_') {
+ // Installation template found
+ $extraPath = 'install/';
+ } elseif (substr($template, 0, 4) == 'ext_') {
+ // Extension template found
+ $extraPath = 'ext/';
+ } elseif (substr($template, 0, 3) == 'la_') {
+ // 'Logical-area' template found
+ $extraPath = 'la/';
+ } elseif (substr($template, 0, 3) == 'js_') {
+ // JavaScript template found
+ $extraPath = 'js/';
+ } elseif (substr($template, 0, 5) == 'menu_') {
+ // Menu template found
+ $extraPath = '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
+ $extraPath = $test . '/';
+ } // END - if
+ }
+
+ // Store it in cache
+ $GLOBALS['extra_path'][$template] = $extraPath;
+ } // END - if
+
+ // Return result
+ return $GLOBALS['extra_path'][$template];
+}
+
+// Loads an email template and compiles it
+function loadEmailTemplate ($template, $content = array(), $userid = '0') {
+ global $DATA;
+
+ // Make sure all template names are lowercase!
+ $template = strtolower($template);
+
+ // Is content an array?
+ if (is_array($content)) {
+ // Add expiration to array
+ if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
+ // Will never expire!
+ $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
+ } elseif (isConfigEntrySet('auto_purge')) {
+ // Create nice date string
+ $content['expiration'] = createFancyTime(getConfig('auto_purge'));
+ } else {
+ // Missing entry
+ $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
+ }
+ } // END - if
+
+ // Load user's data
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
+ if (($userid > 0) && (is_array($content))) {
+ // If nickname extension is installed, fetch nickname as well
+ if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
+ // Load by nickname
+ fetchUserData($userid, 'nickname');
+ } else {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
+ /// Load by userid
+ fetchUserData($userid);
+ }
+
+ // Merge data if valid
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
+ if (isUserDataValid()) {
+ $content = merge_array($content, getUserDataArray());
+ } // END - if
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
+ } // END - if
+
+ // Base directory
+ $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
+
+ // Detect extra path
+ $extraPath = detectExtraTemplatePath($template);
+
+ // Generate full FQFN
+ $FQFN = $basePath . $extraPath . $template . '.tpl';
+
+ // Does the special template exists?
+ if (!isFileReadable($FQFN)) {
+ // Reset to default template
+ $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. :)
+ $GLOBALS['tpl_content'] = readFromFile($FQFN);
+
+ // Run code
+ $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
+ eval($GLOBALS['tpl_content']);
+ } elseif (!empty($template)) {
+ // Template file not found!
+ $newContent = '<div class="para">
+ {--TEMPLATE_404--}: ' . $template . '
+</div>
+<div class="para">
+ {--TEMPLATE_CONTENT--}
+ <pre>' . print_r($content, true) . '</pre>
+ {--TEMPLATE_DATA--}
+ <pre>' . print_r($DATA, true) . '</pre>
+</div>';
+
+ // Debug mode not active? Then remove the HTML tags
+ if (!isDebugModeEnabled()) $newContent = secureString($newContent);
+ } else {
+ // No template name supplied!
+ $newContent = '{--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);
+
+ // Return content
+ return $newContent;
+}
+
+// "Getter" for menu CSS classes, mainly used in templates
+function getMenuCssClasses ($data) {
+ // $data needs to be converted into an array
+ $content = explode('|', $data);
+
+ // Non-existent index 2 will happen in menu blocks
+ if (!isset($content[2])) $content[2] = '';
+
+ // Re-construct the array: 0=visible,1=locked,2=prefix
+ $content['visible'] = $content[0];
+ $content['locked'] = $content[1];
+
+ // Call our "translator" function
+ $content = translateMenuVisibleLocked($content, $content[2]);
+
+ // Return CSS classes
+ return ($content['visible_css'] . ' ' . $content['locked_css']);
+}
+
+// Generate XHTML code for the CAPTCHA
+function generateCaptchaCode ($code, $type, $DATA, $userid) {
+ return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
+}
+
+// Compiles the given HTML/mail code
+function compileCode ($code, $simple = false, $constants = true, $full = true) {
+ // Is the code a string?
+ if (!is_string($code)) {
+ // Silently return it
+ return $code;
+ } // END - if
+
+ // Start couting
+ $startCompile = microtime(true);
+
+ // Comile the code
+ $code = compileRawCode($code, $simple, $constants, $full);
+
+ // Get timing
+ $compiled = microtime(true);
+
+ // Add timing if enabled
+ if (isTemplateHtml()) {
+ // Add timing, this should be disabled in
+ $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
+ } // END - if
+
+ // Return compiled code
+ return $code;
+}
+
+// Compiles the code (use compileCode() only for HTML because of the comments)
+// @TODO $simple/$constants are deprecated
+function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
+ // Is the code a string?
+ if (!is_string($code)) {
+ // Silently return it
+ return $code;
+ } // END - if
+
+ // Init replacement-array with smaller set of security characters
+ $secChars = $GLOBALS['url_chars'];
+
+ // Select full set of chars to replace when we e.g. want to compile URLs
+ if ($full === true) $secChars = $GLOBALS['security_chars'];
+
+ // Compile more through a filter
+ $code = runFilterChain('compile_code', $code);
+
+ // Compile message strings
+ $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
+
+ // Compile QUOT and other non-HTML codes
+ foreach ($secChars['to'] as $k => $to) {
+ // Do the reversed thing as in inc/libs/security_functions.php
+ $code = str_replace($to, $secChars['from'][$k], $code);
+ } // END - foreach
+
+ // Find $content[bla][blub] entries
+ // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
+ preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
+
+ // Are some matches found?
+ if ((count($matches) > 0) && (count($matches[0]) > 0)) {
+ // Replace all matches
+ $matchesFound = array();
+ foreach ($matches[0] as $key => $match) {
+ // Fuzzy look has failed by default
+ $fuzzyFound = false;
+
+ // Fuzzy look on match if already found
+ foreach ($matchesFound as $found => $set) {
+ // Get test part
+ $test = substr($found, 0, strlen($match));
+
+ // Does this entry exist?
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
+ if ($test == $match) {
+ // Match found!
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
+ $fuzzyFound = true;
+ break;
+ } // END - if
+ } // END - foreach
+
+ // Skip this entry?
+ 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: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
+ $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
+ $code = str_replace($match, '".' . $newMatch . '."', $code);
+ $matchesFound[$key . '_' . $matches[4][$key]] = 1;
+ $matchesFound[$match] = 1;
+ } elseif (!isset($matchesFound[$match])) {
+ // Not yet replaced!
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
+ $code = str_replace($match, '".' . $match . '."', $code);
+ $matchesFound[$match] = 1;
+ }
+ } // END - foreach
+ } // END - if
+
+ // Return it
+ return $code;
+}
+
+//
+function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
+ $OUT = '';
+
+ if ($type == 'yn') {
+ // This is a yes/no selection only!
+ if ($id > 0) $prefix .= '[' . $id . ']';
+ $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
+ } else {
+ // Begin with regular selection box here
+ if (!empty($prefix)) $prefix .= '_';
+ $type2 = $type;
+ if ($id > 0) $type2 .= '[' . $id . ']';
+ $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
+ }
+
+ switch ($type) {
+ case 'day': // Day
+ for ($idx = 1; $idx < 32; $idx++) {
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ break;
+
+ case 'month': // Month
+ foreach ($GLOBALS['month_descr'] as $idx => $descr) {
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $descr . '</option>';
+ } // END - for
+ break;
+
+ case 'year': // Year
+ // Get current year
+ $year = date('Y', time());
+
+ // Use configured min age or fixed?
+ if (isExtensionInstalledAndNewer('order', '0.2.1')) {
+ // Configured
+ $startYear = $year - getConfig('min_age');
+ } else {
+ // Fixed 16 years
+ $startYear = $year - 16;
+ }
+
+ // Calculate earliest year (100 years old people can still enter Internet???)
+ $minYear = $year - 100;
+
+ // Check if the default value is larger than minimum and bigger than actual year
+ if (($default > $minYear) && ($default >= $year)) {
+ for ($idx = $year; $idx < ($year + 11); $idx++) {
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ } elseif ($default == -1) {
+ // Current year minus 1
+ for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
+ $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
+ } // END - for
+ } else {
+ // Get current year and subtract the configured minimum age
+ $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
+ // Calculate earliest year depending on extension version
+ if (isExtensionInstalledAndNewer('order', '0.2.1')) {
+ // Use configured minimum age
+ $year = date('Y', time()) - getConfig('min_age');
+ } else {
+ // Use fixed 16 years age
+ $year = date('Y', time()) - 16;
+ }
+
+ // Construct year selection list
+ for ($idx = $minYear; $idx <= $year; $idx++) {
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ }
+ break;
+
+ case 'sec':
+ case 'min':
+ for ($idx = 0; $idx < 60; $idx+=5) {
+ if (strlen($idx) == 1) $idx = '0' . $idx;
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ break;
+
+ case 'hour':
+ for ($idx = 0; $idx < 24; $idx++) {
+ if (strlen($idx) == 1) $idx = '0' . $idx;
+ $OUT .= '<option value="' . $idx . '"';
+ if ($default == $idx) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ break;
+
+ case 'yn':
+ $OUT .= '<option value="Y"';
+ if ($default == 'Y') $OUT .= ' selected="selected"';
+ $OUT .= '>{--YES--}</option><option value="N"';
+ if ($default != 'Y') $OUT .= ' selected="selected"';
+ $OUT .= '>{--NO--}</option>';
+ break;
+ }
+ $OUT .= '</select>';
+ return $OUT;
+}
+
+// Insert the code in $img_code into jpeg or PNG image
+function generateImageOrCode ($img_code, $headerSent = true) {
+ // Is the code size oversized or shouldn't we display it?
+ if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
+ // Stop execution of function here because of over-sized code length
+ debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
+ } elseif ($headerSent === false) {
+ // Return an HTML code here
+ return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
+ }
+
+ // Load image
+ $img = sprintf("%s/theme/%s/images/code_bg.%s",
+ getConfig('PATH'),
+ getCurrentTheme(),
+ getConfig('img_type')
+ );
+
+ // Is it readable?
+ if (isFileReadable($img)) {
+ // Switch image type
+ switch (getConfig('img_type')) {
+ case 'jpg':
+ // Okay, load image and hide all errors
+ $image = imagecreatefromjpeg($img);
+ break;
+
+ case 'png':
+ // Okay, load image and hide all errors
+ $image = imagecreatefrompng($img);
+ break;
+ } // END - switch
+ } else {
+ // Exit function here
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
+ return;
+ }
+
+ // Generate text color (red/green/blue; 0 = dark, 255 = bright)
+ $text_color = imagecolorallocate($image, 0, 0, 0);
+
+ // Insert code into image
+ imagestring($image, 5, 14, 2, $img_code, $text_color);
+
+ // Return to browser
+ sendHeader('Content-Type: image/' . getConfig('img_type'));
+
+ // Output image with matching image factory
+ switch (getConfig('img_type')) {
+ case 'jpg': imagejpeg($image); break;
+ case 'png': imagepng($image); break;
+ } // END - switch
+
+ // Remove image from memory
+ imagedestroy($image);
+}
+// Create selection box or array of splitted timestamp
+function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
+ // Do not continue if ONE_DAY is absend
+ if (!isConfigEntrySet('ONE_DAY')) {
+ // And return the timestamp itself or empty array
+ if ($return_array === true) {
+ return array();
+ } else {
+ return $timestamp;
+ }
+ } // END - if
+
+ // Calculate 2-seconds timestamp
+ $stamp = round($timestamp);
+ //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
+
+ // Do we have a leap year?
+ $SWITCH = '0';
+ $TEST = date('Y', time()) / 4;
+ $M1 = date('m', time());
+ $M2 = date('m', (time() + $timestamp));
+
+ // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
+ if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
+
+ // First of all years...
+ $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
+ //* DEBUG: */ debugOutput('Y=' . $Y);
+ // Next months...
+ $M = abs(floor($timestamp / 2628000 - $Y * 12));
+ //* DEBUG: */ debugOutput('M=' . $M);
+ // Next weeks
+ $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
+ //* DEBUG: */ debugOutput('W=' . $W);
+ // Next days...
+ $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
+ //* DEBUG: */ debugOutput('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));
+ //* DEBUG: */ debugOutput('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));
+ //* DEBUG: */ debugOutput('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));
+ //* DEBUG: */ debugOutput('s=' . $s);
+
+ // Is seconds zero and time is < 60 seconds?
+ if (($s == '0') && ($timestamp < 60)) {
+ // Fix seconds
+ $s = round($timestamp);
+ } // END - if
+
+ //
+ // Now we convert them in seconds...
+ //
+ if ($return_array) {
+ // Just put all data in an array for later use
+ $OUT = array(
+ 'YEARS' => $Y,
+ 'MONTHS' => $M,
+ 'WEEKS' => $W,
+ 'DAYS' => $D,
+ 'HOURS' => $h,
+ 'MINUTES' => $m,
+ 'SECONDS' => $s
+ );
+ } else {
+ // Generate table
+ $OUT = '<div align="' . $align . '">';
+ $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
+ $OUT .= '<tr>';
+
+ if (isInString('Y', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
+ } // END - if
+
+ if (isInString('M', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
+ } // END - if
+
+ if (isInString('W', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
+ } // END - if
+
+ if (isInString('D', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
+ } // END - if
+
+ if (isInString('h', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
+ } // END - if
+
+ if (isInString('m', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
+ } // END - if
+
+ if (isInString('s', $display) || (empty($display))) {
+ $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
+ } // END - if
+
+ $OUT .= '</tr>';
+ $OUT .= '<tr>';
+
+ if (isInString('Y', $display) || (empty($display))) {
+ // Generate year selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
+ for ($idx = 0; $idx <= 10; $idx++) {
+ $OUT .= '<option class="mini_select" value="' . $idx . '"';
+ if ($idx == $Y) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
+ }
+
+ if (isInString('M', $display) || (empty($display))) {
+ // Generate month selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
+ for ($idx = 0; $idx <= 11; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $M) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
+ }
+
+ if (isInString('W', $display) || (empty($display))) {
+ // Generate week selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
+ for ($idx = 0; $idx <= 4; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $W) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
+ }
+
+ if (isInString('D', $display) || (empty($display))) {
+ // Generate day selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
+ for ($idx = 0; $idx <= 31; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $D) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
+ }
+
+ if (isInString('h', $display) || (empty($display))) {
+ // Generate hour selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
+ for ($idx = 0; $idx <= 23; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $h) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
+ }
+
+ if (isInString('m', $display) || (empty($display))) {
+ // Generate minute selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
+ for ($idx = 0; $idx <= 59; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $m) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
+ }
+
+ if (isInString('s', $display) || (empty($display))) {
+ // Generate second selection
+ $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
+ for ($idx = 0; $idx <= 59; $idx++) {
+ $OUT .= ' <option class="mini_select" value="' . $idx . '"';
+ if ($idx == $s) $OUT .= ' selected="selected"';
+ $OUT .= '>' . $idx . '</option>';
+ } // END - for
+ $OUT .= '</select></td>';
+ } else {
+ $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
+ }
+ $OUT .= '</tr>';
+ $OUT .= '</table>';
+ $OUT .= '</div>';
+ }
+
+ // Return generated HTML code
+ return $OUT;
+}
+
+// Generate a list of administrative links to a given userid
+function generateMemberAdminActionLinks ($userid) {
+ // Make sure userid is a number
+ if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
+
+ // Define all main targets
+ $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
+
+ // Get user status
+ $status = getFetchedUserData('userid', $userid, 'status');
+
+ // Begin of navigation links
+ $OUT = '[';
+
+ foreach ($targetArray as $tar) {
+ $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
+ //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
+ // Locked accounts shall be unlocked
+ $OUT .= 'UNLOCK_USER';
+ } else {
+ // All other status is fine
+ $OUT .= strtoupper($tar);
+ }
+ $OUT .= '_TITLE--}">{--ADMIN_';
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
+ // Locked accounts shall be unlocked
+ $OUT .= 'UNLOCK_USER';
+ } else {
+ // All other status is fine
+ $OUT .= strtoupper($tar);
+ }
+ $OUT .= '--}</a></span>|';
+ } // END - foreach
+
+ // Finish navigation link
+ $OUT = substr($OUT, 0, -1) . ']';
+
+ // Return string
+ return $OUT;
+}
+
+// Generate an email link
+function generateEmailLink ($email, $table = 'admins') {
+ // Default email link (INSECURE! Spammer can read this by harvester programs)
+ $EMAIL = 'mailto:' . $email;
+
+ // Check for several extensions
+ if ((isExtensionActive('admins')) && ($table == 'admins')) {
+ // Create email link for contacting admin in guest area
+ $EMAIL = generateAdminEmailLink($email);
+ } elseif ((isExtensionInstalledAndNewer('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 ((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 ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
+
+ // Return email link
+ return $EMAIL;
+}
+
+// Output error messages in a fasioned way and die...
+function app_die ($F, $L, $message) {
+ // Check if Script is already dieing and not let it kill itself another 1000 times
+ if (!isset($GLOBALS['app_died'])) {
+ // Make sure, that the script realy realy diese here and now
+ $GLOBALS['app_died'] = true;
+
+ // Set content type as text/html
+ setContentType('text/html');
+
+ // Load header
+ loadIncludeOnce('inc/header.php');
+
+ // Rewrite message for output
+ $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
+
+ // Load the message template
+ loadTemplate('app_die_message', false, $message);
+
+ // Load footer
+ loadIncludeOnce('inc/footer.php');
+ } else {
+ // Script tried to kill itself twice
+ die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
+ }
+}
+
+// Display parsing time and number of SQL queries in footer
+function displayParsingTime () {
+ // Is the timer started?
+ if (!isset($GLOBALS['startTime'])) {
+ // Abort here
+ return false;
+ } // END - if
+
+ // Get end time
+ $endTime = microtime(true);
+
+ // "Explode" both times
+ $start = explode(' ', $GLOBALS['startTime']);
+ $end = explode(' ', $endTime);
+ $runTime = $end[0] - $start[0];
+ if ($runTime < 0) $runTime = '0';
+
+ // Prepare output
+ // @TODO This can be easily moved out after the merge from EL branch to this is complete
+ $content = array(
+ 'run_time' => $runTime,
+ 'sql_time' => translateComma(getConfig('sql_time') * 1000),
+ );
+
+ // Load the template
+ $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
+}
+
+// Output a debug backtrace to the user
+function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
+ // Is this already called?
+ if (isset($GLOBALS[__FUNCTION__])) {
+ // Other backtrace
+ print 'Message:'.$message.'<br />Backtrace:<pre>';
+ debug_print_backtrace();
+ die('</pre>');
+ } // END - if
+
+ // Set this function as called
+ $GLOBALS[__FUNCTION__] = true;
+
+ // Init message
+ $debug = '';
+
+ // Is the optional message set?
+ if (!empty($message)) {
+ // Use and log it
+ $debug = sprintf("Note: %s<br />\n",
+ $message
+ );
+
+ // @TODO Add a little more infos here
+ logDebugMessage($F, $L, strip_tags($message));
+ } // END - if
+
+ // Add output
+ $debug .= 'Please report this bug at <a title="Direct link to the bug-tracker" href="http://bugs.mxchange.org" rel="external" target="_blank">http://bugs.mxchange.org</a> and include the logfile from <strong>' . str_replace(getConfig('PATH'), '', getConfig('CACHE_PATH')) . 'debug.log</strong> in your report (you can now attach files):<pre>';
+ $debug .= debug_get_printable_backtrace();
+ $debug .= '</pre>';
+ $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
+ $debug .= '<div>Thank you for finding bugs.</div>';
+
+ // Send an email? (e.g. not wanted for evaluation errors)
+ if (($sendEmail === true) && (!isInstallationPhase())) {
+ // Prepare content
+ $content = array(
+ 'message' => trim($message),
+ 'backtrace' => trim(debug_get_mailable_backtrace())
+ );
+
+ // Send email to webmaster
+ sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
+ } // END - if
+
+ // And abort here
+ app_die($F, $L, $debug);
+}
+
+// Compile characters which are allowed in URLs
+function compileUriCode ($code, $simple = true) {
+ // Compile constants
+ if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
+
+ // Compile QUOT and other non-HTML codes
+ $code = str_replace('{DOT}', '.',
+ str_replace('{SLASH}', '/',
+ str_replace('{QUOT}', "'",
+ str_replace('{DOLLAR}', '$',
+ str_replace('{OPEN_ANCHOR}', '(',
+ str_replace('{CLOSE_ANCHOR}', ')',
+ str_replace('{OPEN_SQR}', '[',
+ str_replace('{CLOSE_SQR}', ']',
+ str_replace('{PER}', '%',
+ $code
+ )))))))));
+
+ // Return compiled code
+ return $code;
+}
+
+// Handle message codes from URL
+function handleCodeMessage () {
+ if (isGetRequestParameterSet('code')) {
+ // Default extension is 'unknown'
+ $ext = 'unknown';
+
+ // Is extension given?
+ if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
+
+ // Convert the 'code' parameter from URL to a human-readable message
+ $message = getMessageFromErrorCode(getRequestParameter('code'));
+
+ // Load message template
+ loadTemplate('message', false, $message);
+ } // END - if
+}
+
+// Generates a 'extension foo inactive' message
+function generateExtensionInactiveMessage ($ext_name) {
+ // Is the extension empty?
+ if (empty($ext_name)) {
+ // This should not happen
+ debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
+ } // END - if
+
+ // Default message
+ $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
+
+ // Is an admin logged in?
+ if (isAdmin()) {
+ // Then output admin message
+ $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
+ } // END - if
+
+ // Return prepared message
+ return $message;
+}
+
+// Generates a 'extension foo not installed' message
+function generateExtensionNotInstalledMessage ($ext_name) {
+ // Is the extension empty?
+ if (empty($ext_name)) {
+ // This should not happen
+ debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
+ } // END - if
+
+ // Default message
+ $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
+
+ // Is an admin logged in?
+ if (isAdmin()) {
+ // Then output admin message
+ $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
+ } // END - if
+
+ // Return prepared message
+ return $message;
+}
+
+// Generates a message depending on if the extension is not installed or not
+// just activated
+function generateExtensionInactiveNotInstalledMessage ($ext_name) {
+ // Init message
+ $message = '';
+
+ // Is the extension not installed or just deactivated?
+ switch (isExtensionInstalled($ext_name)) {
+ case true; // Deactivated!
+ $message = generateExtensionInactiveMessage($ext_name);
+ break;
+
+ case false; // Not installed!
+ $message = generateExtensionNotInstalledMessage($ext_name);
+ break;
+
+ default: // Should not happen!
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
+ $message = sprintf("Invalid state of extension %s detected.", $ext_name);
+ break;
+ } // END - switch
+
+ // Return the message
+ return $message;
+}
+
+// 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:<br />';
+ foreach($codeE as $line => $c) {
+ $r .= '<div class="line"><span class="linenum">';
+ if ($count_lines == 1) {
+ $r .= 1;
+ } else {
+ $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
+ }
+ $r .= '</span>|';
+
+ // Add code
+ $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
+ }
+
+ return '<div class="code">' . $r . '</div>';
+}
+
+// Determines the right page title
+function determinePageTitle () {
+ // Config and database connection valid?
+ if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+ // Init title
+ $TITLE = '';
+
+ // Title decoration enabled?
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
+
+ // Do we have some extra title?
+ if (isExtraTitleSet()) {
+ // Then prepent it
+ $TITLE .= getExtraTitle() . ' by ';
+ } // END - if
+
+ // Add main title
+ $TITLE .= getConfig('MAIN_TITLE');
+
+ // Add title of module? (middle decoration will also be added!)
+ if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+ $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+ } // END - if
+
+ // Add title from what file
+ $mode = '';
+ if (getModule() == 'login') $mode = 'member';
+ elseif (getModule() == 'index') $mode = 'guest';
+ if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
+
+ // Add title decorations? (right)
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
+
+ // Remember title in constant for the template
+ $pageTitle = $TITLE;
+ } elseif ((isInstalled()) && (isAdminRegistered())) {
+ // Installed, admin registered but no ext-sql_patches
+ $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
+ } elseif ((isInstalled()) && (!isAdminRegistered())) {
+ // Installed but no admin registered
+ $pageTitle = '{--SETUP_OF_MAILER--}';
+ } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+ // Installation mode
+ $pageTitle = '{--INSTALLATION_OF_MAILER--}';
+ } else {
+ // Configuration not found!
+ $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
+
+ // Do not add the fatal message in installation mode
+ if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
+ }
+
+ // Return title
+ return decodeEntities($pageTitle);
+}
+
+// Checks wethere there is a cache file there. This function is cached.
+function isTemplateCached ($template) {
+ // Do we have cached this result?
+ if (!isset($GLOBALS['template_cache'][$template])) {
+ // Generate FQFN
+ $FQFN = generateCacheFqfn($template);
+
+ // Is it there?
+ $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
+ } // END - if
+
+ // Return it
+ return $GLOBALS['template_cache'][$template];
+}
+
+// Flushes non-flushed template cache to disk
+function flushTemplateCache ($template, $eval) {
+ // Is this cache flushed?
+ if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
+ // Generate FQFN
+ $FQFN = generateCacheFqfn($template);
+
+ // And flush it
+ writeToFile($FQFN, $eval, true);
+ } // END - if
+}
+
+// Reads a template cache
+function readTemplateCache ($template) {
+ // Check it again
+ if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
+ // This should not happen
+ debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
+ } // END - if
+
+ // Is it cached?
+ if (!isset($GLOBALS['template_eval'][$template])) {
+ // Generate FQFN
+ $FQFN = generateCacheFqfn($template);
+
+ // And read from it
+ $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
+ } // END - if
+
+ // And return it
+ return $GLOBALS['template_eval'][$template];
+}
+
+// Escapes quotes (default is only double-quotes)
+function escapeQuotes ($str, $single = false) {
+ // Should we escape all?
+ if ($single === true) {
+ // Escape all (including null)
+ $str = addslashes($str);
+ } else {
+ // Escape only double-quotes but prevent double-quoting
+ $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
+ }
+
+ // Return the escaped string
+ return $str;
+}
+
+// Escapes the JavaScript code, prevents \r and \n becoming char 10/13
+function escapeJavaScriptQuotes ($str) {
+ // Replace all double-quotes and secure back-ticks
+ $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
+
+ // Return it
+ return $str;
+}
+
+// Send out mails depending on the 'mod/modes' combination
+// @TODO Lame description for this function
+function sendModeMails ($mod, $modes) {
+ // Load hash
+ if (fetchUserData(getMemberId())) {
+ // Extract salt from cookie
+ $salt = substr(getSession('u_hash'), 0, -40);
+
+ // Now let's compare passwords
+ $hash = encodeHashForCookie(getUserData('password'));
+
+ // Does the hash match or should we change it?
+ if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
+ // Load the data
+ $content = getUserDataArray();
+
+ // Clear/init the content variable
+ $content['message'] = '';
+
+ // Which mail?
+ // @TODO Move this in a filter
+ switch ($mod) {
+ case 'mydata':
+ foreach ($modes as $mode) {
+ switch ($mode) {
+ case 'normal': break; // Do not add any special lines
+ case 'email': // Email was changed!
+ $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
+ break;
+
+ case 'pass': // Password was changed
+ $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
+ break;
+
+ default:
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
+ $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
+ break;
+ } // END - switch
+ } // END - foreach
+
+ if (isExtensionActive('country')) {
+ // Replace code with description
+ $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
+ } // END - if
+
+ // Merge content with data from POST
+ $content = merge_array($content, postRequestArray());
+
+ // Load template
+ $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
+
+ if (getConfig('admin_notify') == 'Y') {
+ // The admin needs to be notified about a profile change
+ $message_admin = 'admin_mydata_notify';
+ $sub_adm = '{--ADMIN_CHANGED_DATA--}';
+ } else {
+ // No mail to admin
+ $message_admin = '';
+ $sub_adm = '';
+ }
+
+ // Set subject lines
+ $sub_mem = '{--MEMBER_CHANGED_DATA--}';
+
+ // Output success message
+ $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
+ break;
+
+ default: // Unsupported module!
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
+ $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
+ break;
+ } // END - switch
+ } else {
+ // Passwords mismatch
+ $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
+ }
+ } else {
+ // Could not load profile
+ $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
+ }
+
+ // Send email to user if required
+ if ((!empty($sub_mem)) && (!empty($message))) {
+ // Send member mail
+ sendEmail($content['email'], $sub_mem, $message);
+ } // END - if
+
+ // Send only if no other error has occured
+ if (empty($content)) {
+ if ((!empty($sub_adm)) && (!empty($message_admin))) {
+ // Send admin mail
+ sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
+ } elseif (getConfig('admin_notify') == 'Y') {
+ // Cannot send mails to admin!
+ $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
+ } else {
+ // No mail to admin
+ $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
+ }
+ } // END - if
+
+ // Load template
+ loadTemplate('admin_settings_saved', false, $content);
+}
+
+// Generates a 'selection box' from given array
+function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
+ // Start the output
+ $OUT = '<select name="' . $name . '" size="1" class="admin_select">
+<option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
+
+ // Walk through all options
+ foreach ($options as $option) {
+ // Add the <option> entry
+ if (empty($optionContent)) {
+ // ... from template
+ $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
+ } else {
+ // Direct HTML code
+ $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
+ }
+ } // END - foreach
+
+ // Finish selection box
+ $OUT .= '</select>';
+
+ // Prepare output
+ $content = array(
+ 'selection_box' => $OUT,
+ 'module' => getModule(),
+ 'what' => getWhat()
+ );
+
+ // Load template and return it
+ return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
+}
+
+// Prepares the header for HTML output
+function loadHtmlHeader () {
+ // Run two filters:
+ // 1.) pre_page_header (mainly loads the page_header template and includes
+ // meta description)
+ runFilterChain('pre_page_header');
+
+ // Here can be something be added, but normally one of the two filters
+ // around this line should do the job for you.
+
+ // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
+ // to close the head-tag)
+ // Include more header data here
+ runFilterChain('post_page_header');
+}
+
+// Adds page header and footer to output array element
+function addPageHeaderFooter () {
+ // Init output
+ $OUT = '';
+
+ // Add them all together. This is maybe to simple
+ foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
+ // Add page part if set
+ if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
+ } // END - foreach
+
+ // Transfer $OUT to 'output'
+ $GLOBALS['output'] = $OUT;
+}
+
+// Generates meta description for current module and 'what' value
+function generateMetaDescriptionCode () {
+ // Only include from guest area and if sql_patches has correct version
+ if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+ // Construct dynamic description
+ $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
+
+ // Output it directly
+ $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
+ } // END - if
+
+ // Remove depth
+ unset($GLOBALS['ref_level']);
+}
+
+// Generates an FQFN for template cache from the given template name
+function generateCacheFqfn ($template, $mode = 'html') {
+ // Is this cached?
+ if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
+ // Generate the FQFN
+ $GLOBALS['template_cache_fqfn'][$template] = sprintf(
+ "%s_compiled/%s/%s.tpl.cache",
+ getConfig('CACHE_PATH'),
+ $mode,
+ $template
+ );
+ } // END - if
+
+ // Return it
+ return $GLOBALS['template_cache_fqfn'][$template];
+}
+
+// "Fixes" null or empty string to count of dashes
+function fixNullEmptyToDashes ($str, $num) {
+ // Use str as default
+ $return = $str;
+
+ // Is it empty?
+ if ((is_null($str)) || (trim($str) == '')) {
+ // Set it
+ $return = str_repeat('-', $num);
+ } // END - if
+
+ // Return final string
+ return $return;
+}
+
+// [EOF]
+?>