2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 04/04/2009 *
4 * =================== Last change: 04/04/2009 *
6 * -------------------------------------------------------------------- *
7 * File : template-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Template functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Template-Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Wrapper until we merged to the EL branch
46 function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
47 return compileCode($code, false, true, $full);
50 // Setter for 'is_template_html'
51 function enableTemplateHtml ($enable = true) {
52 $GLOBALS['is_template_html'] = (bool) $enable;
55 // Checks wether the template is HTML or not by previously set flag
57 function isTemplateHtml () {
58 // Is the output_mode other than 0 (HTML), then no comments are enabled
59 if (!isHtmlOutputMode()) {
64 return $GLOBALS['is_template_html'];
68 // Wrapper for writing debug informations to the browser
69 function debugOutput ($message) {
70 outputHtml('<div class="debug_message">' . $message . '</div>');
73 // "Fixes" an empty string into three dashes (use for templates)
74 function fixEmptyContentToDashes ($str) {
78 // Is the string empty?
79 if (empty($str)) $str = '---';
86 function initTemplateColorSwitch ($template) {
87 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
88 $GLOBALS['color_switch'][$template] = 2;
91 // "Getter" for color switch code
92 function getColorSwitchCode ($template) {
94 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
100 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
101 function outputHtml ($htmlCode, $newLine = true) {
103 if (!isset($GLOBALS['output'])) {
104 $GLOBALS['output'] = '';
107 // Do we have HTML-Code here?
108 if (!empty($htmlCode)) {
109 // Yes, so we handle it as you have configured
110 switch (getOutputMode()) {
112 // That's why you don't need any \n at the end of your HTML code... :-)
113 if (getPhpCaching() == 'on') {
114 // Output into PHP's internal buffer
115 outputRawCode($htmlCode);
117 // That's why you don't need any \n at the end of your HTML code... :-)
118 if ($newLine === true) print("\n");
120 // Render mode for old or lame servers...
121 $GLOBALS['output'] .= $htmlCode;
123 // That's why you don't need any \n at the end of your HTML code... :-)
124 if ($newLine === true) $GLOBALS['output'] .= "\n";
129 // If we are switching from render to direct output rendered code
130 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
132 // The same as above... ^
133 outputRawCode($htmlCode);
134 if ($newLine === true) print("\n");
138 // Huh, something goes wrong or maybe you have edited config.php ???
139 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
142 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
143 // Output cached HTML code
144 $GLOBALS['output'] = ob_get_contents();
146 // Clear output buffer for later output if output is found
147 if (!empty($GLOBALS['output'])) {
151 // Send all HTTP headers
154 // Compile and run finished rendered HTML code
155 compileFinalOutput();
157 // Output code here, DO NOT REMOVE! ;-)
158 outputRawCode($GLOBALS['output']);
159 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
160 // Send all HTTP headers
163 // Compile and run finished rendered HTML code
164 compileFinalOutput();
166 // Output code here, DO NOT REMOVE! ;-)
167 outputRawCode($GLOBALS['output']);
169 // And flush all headers
174 // Compiles the final output
175 function compileFinalOutput () {
176 // Add page header and footer
177 addPageHeaderFooter();
179 // Do the final compilation
180 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
182 // Extension 'rewrite' installed?
183 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
184 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
189 * @TODO On some pages this is buggy
190 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
191 // Compress it for HTTP gzip
192 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9);
195 sendHeader('Content-Encoding: gzip');
196 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
197 // Compress it for HTTP deflate
198 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
201 sendHeader('Content-Encoding: deflate');
206 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
212 // Main compilation loop
213 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
214 // Insert comments? (Only valid with HTML templates, of course)
215 enableTemplateHtml($insertComments);
221 while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
222 // Init common variables
227 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
228 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
229 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
231 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
232 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
234 // Was that eval okay?
235 if (empty($newContent)) {
236 // Something went wrong!
237 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
247 // Return the compiled code
251 // Output the raw HTML code
252 function outputRawCode ($htmlCode) {
253 // Output stripped HTML code to avoid broken JavaScript code, etc.
254 print(str_replace('{BACK}', "\\", $htmlCode));
256 // Flush the output if only getPhpCaching() is not 'on'
257 if (getPhpCaching() != 'on') {
263 // Load a template file and return it's content (only it's name; do not use ' or ")
264 function loadTemplate ($template, $return = false, $content = array()) {
265 // @TODO Remove this sanity-check if all is fine
266 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
268 // Set current template
269 $GLOBALS['current_template'] = $template;
272 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
273 // Evaluate the cache
274 eval(readTemplateCache($template));
275 } elseif (!isset($GLOBALS['template_eval'][$template])) {
276 // Make all template names lowercase
277 $template = strtolower($template);
281 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
284 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
285 $extraPath = detectExtraTemplatePath($template);;
288 $FQFN = $basePath . $extraPath . $template . '.tpl';
290 // Does the special template exists?
291 if (!isFileReadable($FQFN)) {
292 // Reset to default template
293 $FQFN = $basePath . $template . '.tpl';
296 // Now does the final template exists?
297 if (isFileReadable($FQFN)) {
298 // Count the template load
299 incrementConfigEntry('num_templates');
301 // The local file does exists so we load it. :)
302 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
304 // Do we have to compile the code?
306 if ((strpos($GLOBALS['tpl_content'][$template], '$') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{--') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{?') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{%') !== false)) {
307 // Normal HTML output?
308 if (isHtmlOutputMode()) {
309 // Add surrounding HTML comments to help finding bugs faster
310 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
312 // Prepare eval() command
313 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
314 } elseif (substr($template, 0, 3) == 'js_') {
315 // JavaScripts don't like entities and timings
316 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template])) . '");';
318 // Prepare eval() command, other output doesn't like entities, maybe
319 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
322 // Add surrounding HTML comments to help finding bugs faster
323 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
324 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
326 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
327 // Only admins shall see this warning or when installation mode is active
328 $ret = '<div class="para">
329 <span class="notice">{--TEMPLATE_404--}</span>
335 {--TEMPLATE_CONTENT--}
336 <pre>' . print_r($content, true) . '</pre>
340 $GLOBALS['template_eval'][$template] = '404';
345 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
347 eval($GLOBALS['template_eval'][$template]);
350 // Do we have some content to output or return?
352 // Not empty so let's put it out! ;)
353 if ($return === true) {
354 // Return the HTML code
360 } elseif (isDebugModeEnabled()) {
361 // Warning, empty output!
362 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
366 // Detects the extra template path from given template name
367 function detectExtraTemplatePath ($template) {
372 if (!isset($GLOBALS['extra_path'][$template])) {
373 // Check for admin/guest/member/etc. templates
374 if (substr($template, 0, 6) == 'admin_') {
375 // Admin template found
376 $extraPath = 'admin/';
377 } elseif (substr($template, 0, 6) == 'guest_') {
378 // Guest template found
379 $extraPath = 'guest/';
380 } elseif (substr($template, 0, 7) == 'member_') {
381 // Member template found
382 $extraPath = 'member/';
383 } elseif (substr($template, 0, 7) == 'select_') {
384 // Selection template found
385 $extraPath = 'select/';
386 } elseif (substr($template, 0, 8) == 'install_') {
387 // Installation template found
388 $extraPath = 'install/';
389 } elseif (substr($template, 0, 4) == 'ext_') {
390 // Extension template found
392 } elseif (substr($template, 0, 3) == 'la_') {
393 // 'Logical-area' template found
395 } elseif (substr($template, 0, 3) == 'js_') {
396 // JavaScript template found
398 } elseif (substr($template, 0, 5) == 'menu_') {
399 // Menu template found
400 $extraPath = 'menu/';
402 // Test for extension
403 $test = substr($template, 0, strpos($template, '_'));
405 // Probe for valid extension name
406 if (isExtensionNameValid($test)) {
407 // Set extra path to extension's name
408 $extraPath = $test . '/';
413 $GLOBALS['extra_path'][$template] = $extraPath;
417 return $GLOBALS['extra_path'][$template];
420 // Loads an email template and compiles it
421 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
424 // Make sure all template names are lowercase!
425 $template = strtolower($template);
427 // Is content an array?
428 if (is_array($content)) {
429 // Add expiration to array
430 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
431 // Will never expire!
432 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
433 } elseif (isConfigEntrySet('auto_purge')) {
434 // Create nice date string
435 $content['expiration'] = createFancyTime(getAutoPurge());
438 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
443 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
444 if ((isValidUserId($userid)) && (is_array($content))) {
445 // If nickname extension is installed, fetch nickname as well
446 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
449 fetchUserData($userid, 'nickname');
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
453 fetchUserData($userid);
456 // Merge data if valid
457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
458 if (isUserDataValid()) {
459 $content = merge_array($content, getUserDataArray());
461 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
465 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
468 $extraPath = detectExtraTemplatePath($template);
470 // Generate full FQFN
471 $FQFN = $basePath . $extraPath . $template . '.tpl';
473 // Does the special template exists?
474 if (!isFileReadable($FQFN)) {
475 // Reset to default template
476 $FQFN = $basePath . $template . '.tpl';
479 // Now does the final template exists?
481 if (isFileReadable($FQFN)) {
482 // The local file does exists so we load it. :)
483 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
486 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
487 eval($GLOBALS['tpl_content'][$template]);
488 } elseif (!empty($template)) {
489 // Template file not found!
490 $newContent = '<div class="para">
491 {--TEMPLATE_404--}: ' . $template . '
494 {--TEMPLATE_CONTENT--}
495 <pre>' . print_r($content, true) . '</pre>
497 <pre>' . print_r($DATA, true) . '</pre>
500 // Debug mode not active? Then remove the HTML tags
501 if (!isDebugModeEnabled()) {
503 $newContent = secureString($newContent);
506 // No template name supplied!
507 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
510 // Is there some content?
511 if (empty($newContent)) {
513 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
515 // Add last error if the required function exists
516 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
519 // Remove content and data
527 // "Getter" for menu CSS classes, mainly used in templates
528 function getMenuCssClasses ($data) {
529 // $data needs to be converted into an array
530 $content = explode('|', $data);
532 // Non-existent index 2 will happen in menu blocks
533 if (!isset($content[2])) $content[2] = '';
535 // Re-construct the array: 0=visible,1=locked,2=prefix
536 $content['visible'] = $content[0];
537 $content['locked'] = $content[1];
539 // Call our "translator" function
540 $content = translateMenuVisibleLocked($content, $content[2]);
542 // Return CSS classes
543 return ($content['visible_css'] . ' ' . $content['locked_css']);
546 // Generate XHTML code for the CAPTCHA
547 function generateCaptchaCode ($code, $type, $DATA, $userid) {
548 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
551 // Compiles the given HTML/mail code
552 function compileCode ($code, $simple = false, $constants = true, $full = true) {
553 // Is the code a string?
554 if (!is_string($code)) {
555 // Silently return it
560 $startCompile = microtime(true);
563 $code = compileRawCode($code, $simple, $constants, $full);
566 $compiled = microtime(true);
568 // Add timing if enabled
569 if (isTemplateHtml()) {
570 // Add timing, this should be disabled in
571 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
574 // Return compiled code
578 // Compiles the code (use compileCode() only for HTML because of the comments)
579 // @TODO $simple/$constants are deprecated
580 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
581 // Is the code a string?
582 if (!is_string($code)) {
583 // Silently return it
587 // Init replacement-array with smaller set of security characters
588 $secChars = $GLOBALS['url_chars'];
590 // Select full set of chars to replace when we e.g. want to compile URLs
591 if ($full === true) $secChars = $GLOBALS['security_chars'];
593 // Compile more through a filter
594 $code = runFilterChain('compile_code', $code);
596 // Compile message strings
597 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
599 // Compile QUOT and other non-HTML codes
600 foreach ($secChars['to'] as $k => $to) {
601 // Do the reversed thing as in inc/libs/security_functions.php
602 $code = str_replace($to, $secChars['from'][$k], $code);
605 // Find $content[bla][blub] entries
606 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
607 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
609 // Are some matches found?
610 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
611 // Replace all matches
612 $matchesFound = array();
613 foreach ($matches[0] as $key => $match) {
614 // Fuzzy look has failed by default
617 // Fuzzy look on match if already found
618 foreach ($matchesFound as $found => $set) {
620 $test = substr($found, 0, strlen($match));
622 // Does this entry exist?
623 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
624 if ($test == $match) {
626 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
633 if ($fuzzyFound === true) continue;
635 // Take all string elements
636 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
637 // Replace it in the code
638 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
639 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
640 $code = str_replace($match, '".' . $newMatch . '."', $code);
641 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
642 $matchesFound[$match] = 1;
643 } elseif (!isset($matchesFound[$match])) {
645 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
646 $code = str_replace($match, '".' . $match . '."', $code);
647 $matchesFound[$match] = 1;
657 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
661 // This is a yes/no selection only!
662 if ($id > 0) $prefix .= '[' . $id . ']';
663 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
665 // Begin with regular selection box here
666 if (!empty($prefix)) $prefix .= '_';
668 if ($id > 0) $type2 .= '[' . $id . ']';
669 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
674 for ($idx = 1; $idx < 32; $idx++) {
675 $OUT .= '<option value="' . $idx . '"';
676 if ($default == $idx) $OUT .= ' selected="selected"';
677 $OUT .= '>' . $idx . '</option>';
681 case 'month': // Month
682 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
683 $OUT .= '<option value="' . $idx . '"';
684 if ($default == $idx) $OUT .= ' selected="selected"';
685 $OUT .= '>' . $descr . '</option>';
693 // Use configured min age or fixed?
694 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
696 $startYear = $year - getConfig('min_age');
699 $startYear = $year - 16;
702 // Calculate earliest year (100 years old people can still enter Internet???)
703 $minYear = $year - 100;
705 // Check if the default value is larger than minimum and bigger than actual year
706 if (($default > $minYear) && ($default >= $year)) {
707 for ($idx = $year; $idx < ($year + 11); $idx++) {
708 $OUT .= '<option value="' . $idx . '"';
709 if ($default == $idx) $OUT .= ' selected="selected"';
710 $OUT .= '>' . $idx . '</option>';
712 } elseif ($default == -1) {
713 // Current year minus 1
714 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
715 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
718 // Get current year and subtract the configured minimum age
719 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
720 // Calculate earliest year depending on extension version
721 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
722 // Use configured minimum age
723 $year = getYear() - getConfig('min_age');
725 // Use fixed 16 years age
726 $year = getYear() - 16;
729 // Construct year selection list
730 for ($idx = $minYear; $idx <= $year; $idx++) {
731 $OUT .= '<option value="' . $idx . '"';
732 if ($default == $idx) $OUT .= ' selected="selected"';
733 $OUT .= '>' . $idx . '</option>';
740 for ($idx = 0; $idx < 60; $idx+=5) {
741 if (strlen($idx) == 1) $idx = '0' . $idx;
742 $OUT .= '<option value="' . $idx . '"';
743 if ($default == $idx) $OUT .= ' selected="selected"';
744 $OUT .= '>' . $idx . '</option>';
749 for ($idx = 0; $idx < 24; $idx++) {
750 if (strlen($idx) == 1) $idx = '0' . $idx;
751 $OUT .= '<option value="' . $idx . '"';
752 if ($default == $idx) $OUT .= ' selected="selected"';
753 $OUT .= '>' . $idx . '</option>';
758 $OUT .= '<option value="Y"';
759 if ($default == 'Y') $OUT .= ' selected="selected"';
760 $OUT .= '>{--YES--}</option><option value="N"';
761 if ($default != 'Y') $OUT .= ' selected="selected"';
762 $OUT .= '>{--NO--}</option>';
769 // Insert the code in $img_code into jpeg or PNG image
770 function generateImageOrCode ($img_code, $headerSent = true) {
771 // Is the code size oversized or shouldn't we display it?
772 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
773 // Stop execution of function here because of over-sized code length
774 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
775 } elseif ($headerSent === false) {
776 // Return an HTML code here
777 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
781 $img = sprintf("%s/theme/%s/images/code_bg.%s",
784 getConfig('img_type')
788 if (isFileReadable($img)) {
790 switch (getConfig('img_type')) {
792 // Okay, load image and hide all errors
793 $image = imagecreatefromjpeg($img);
797 // Okay, load image and hide all errors
798 $image = imagecreatefrompng($img);
802 // Exit function here
803 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
807 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
808 $text_color = imagecolorallocate($image, 0, 0, 0);
810 // Insert code into image
811 imagestring($image, 5, 14, 2, $img_code, $text_color);
814 sendHeader('Content-Type: image/' . getConfig('img_type'));
816 // Output image with matching image factory
817 switch (getConfig('img_type')) {
818 case 'jpg': imagejpeg($image); break;
819 case 'png': imagepng($image); break;
822 // Remove image from memory
823 imagedestroy($image);
825 // Create selection box or array of splitted timestamp
826 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
827 // Do not continue if ONE_DAY is absend
828 if (!isConfigEntrySet('ONE_DAY')) {
829 // And return the timestamp itself or empty array
830 if ($return_array === true) {
837 // Calculate 2-seconds timestamp
838 $stamp = round($timestamp);
839 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
841 // Do we have a leap year?
843 $TEST = getYear() / 4;
845 $M2 = getMonth(time() + $timestamp);
847 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
848 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
850 // First of all years...
851 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
852 //* DEBUG: */ debugOutput('Y=' . $Y);
854 $M = abs(floor($timestamp / 2628000 - $Y * 12));
855 //* DEBUG: */ debugOutput('M=' . $M);
857 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
858 //* DEBUG: */ debugOutput('W=' . $W);
860 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
861 //* DEBUG: */ debugOutput('D=' . $D);
863 $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));
864 //* DEBUG: */ debugOutput('h=' . $h);
866 $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));
867 //* DEBUG: */ debugOutput('m=' . $m);
868 // And at last seconds...
869 $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));
870 //* DEBUG: */ debugOutput('s=' . $s);
872 // Is seconds zero and time is < 60 seconds?
873 if (($s == '0') && ($timestamp < 60)) {
875 $s = round($timestamp);
879 // Now we convert them in seconds...
882 // Just put all data in an array for later use
894 $OUT = '<div align="' . $align . '">';
895 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
898 if (isInString('Y', $display) || (empty($display))) {
899 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
902 if (isInString('M', $display) || (empty($display))) {
903 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
906 if (isInString('W', $display) || (empty($display))) {
907 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
910 if (isInString('D', $display) || (empty($display))) {
911 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
914 if (isInString('h', $display) || (empty($display))) {
915 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
918 if (isInString('m', $display) || (empty($display))) {
919 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
922 if (isInString('s', $display) || (empty($display))) {
923 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
929 if (isInString('Y', $display) || (empty($display))) {
930 // Generate year selection
931 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
932 for ($idx = 0; $idx <= 10; $idx++) {
933 $OUT .= '<option class="mini_select" value="' . $idx . '"';
934 if ($idx == $Y) $OUT .= ' selected="selected"';
935 $OUT .= '>' . $idx . '</option>';
937 $OUT .= '</select></td>';
939 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
942 if (isInString('M', $display) || (empty($display))) {
943 // Generate month selection
944 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
945 for ($idx = 0; $idx <= 11; $idx++) {
946 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
947 if ($idx == $M) $OUT .= ' selected="selected"';
948 $OUT .= '>' . $idx . '</option>';
950 $OUT .= '</select></td>';
952 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
955 if (isInString('W', $display) || (empty($display))) {
956 // Generate week selection
957 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
958 for ($idx = 0; $idx <= 4; $idx++) {
959 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
960 if ($idx == $W) $OUT .= ' selected="selected"';
961 $OUT .= '>' . $idx . '</option>';
963 $OUT .= '</select></td>';
965 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
968 if (isInString('D', $display) || (empty($display))) {
969 // Generate day selection
970 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
971 for ($idx = 0; $idx <= 31; $idx++) {
972 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
973 if ($idx == $D) $OUT .= ' selected="selected"';
974 $OUT .= '>' . $idx . '</option>';
976 $OUT .= '</select></td>';
978 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
981 if (isInString('h', $display) || (empty($display))) {
982 // Generate hour selection
983 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
984 for ($idx = 0; $idx <= 23; $idx++) {
985 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
986 if ($idx == $h) $OUT .= ' selected="selected"';
987 $OUT .= '>' . $idx . '</option>';
989 $OUT .= '</select></td>';
991 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
994 if (isInString('m', $display) || (empty($display))) {
995 // Generate minute selection
996 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
997 for ($idx = 0; $idx <= 59; $idx++) {
998 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
999 if ($idx == $m) $OUT .= ' selected="selected"';
1000 $OUT .= '>' . $idx . '</option>';
1002 $OUT .= '</select></td>';
1004 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1007 if (isInString('s', $display) || (empty($display))) {
1008 // Generate second selection
1009 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1010 for ($idx = 0; $idx <= 59; $idx++) {
1011 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1012 if ($idx == $s) $OUT .= ' selected="selected"';
1013 $OUT .= '>' . $idx . '</option>';
1015 $OUT .= '</select></td>';
1017 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1024 // Return generated HTML code
1028 // Generate a list of administrative links to a given userid
1029 function generateMemberAdminActionLinks ($userid) {
1030 // Make sure userid is a number
1031 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1033 // Define all main targets
1034 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1037 $status = getFetchedUserData('userid', $userid, 'status');
1039 // Begin of navigation links
1042 foreach ($targetArray as $tar) {
1043 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1044 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1045 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1046 // Locked accounts shall be unlocked
1047 $OUT .= 'UNLOCK_USER';
1049 // All other status is fine
1050 $OUT .= strtoupper($tar);
1052 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1053 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1054 // Locked accounts shall be unlocked
1055 $OUT .= 'UNLOCK_USER';
1057 // All other status is fine
1058 $OUT .= strtoupper($tar);
1060 $OUT .= '--}</a></span>|';
1063 // Finish navigation link
1064 $OUT = substr($OUT, 0, -1) . ']';
1070 // Generate an email link
1071 function generateEmailLink ($email, $table = 'admins') {
1072 // Default email link (INSECURE! Spammer can read this by harvester programs)
1073 $EMAIL = 'mailto:' . $email;
1075 // Check for several extensions
1076 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1077 // Create email link for contacting admin in guest area
1078 $EMAIL = generateAdminEmailLink($email);
1079 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1080 // Create email link for contacting a member within admin area (or later in other areas, too?)
1081 $EMAIL = generateUserEmailLink($email);
1082 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1083 // Create email link to contact sponsor within admin area (or like the link above?)
1084 $EMAIL = generateSponsorEmailLink($email);
1087 // Shall I close the link when there is no admin?
1088 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1090 // Return email link
1094 // Output error messages in a fasioned way and die...
1095 function app_die ($F, $L, $message) {
1096 // Check if Script is already dieing and not let it kill itself another 1000 times
1097 if (!isset($GLOBALS['app_died'])) {
1098 // Make sure, that the script realy realy diese here and now
1099 $GLOBALS['app_died'] = true;
1101 // Set content type as text/html
1102 setContentType('text/html');
1105 loadIncludeOnce('inc/header.php');
1107 // Rewrite message for output
1108 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1110 // Load the message template
1111 loadTemplate('app_die_message', false, $message);
1114 loadIncludeOnce('inc/footer.php');
1116 // Script tried to kill itself twice
1117 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1121 // Display parsing time and number of SQL queries in footer
1122 function displayParsingTime () {
1123 // Is the timer started?
1124 if (!isset($GLOBALS['startTime'])) {
1130 $endTime = microtime(true);
1132 // "Explode" both times
1133 $start = explode(' ', $GLOBALS['startTime']);
1134 $end = explode(' ', $endTime);
1135 $runTime = $end[0] - $start[0];
1141 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1143 'run_time' => $runTime,
1144 'sql_time' => (getConfig('sql_time') * 1000),
1147 // Load the template
1148 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1151 // Output a debug backtrace to the user
1152 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1153 // Is this already called?
1154 if (isset($GLOBALS[__FUNCTION__])) {
1156 print 'Message:' . $message . '<br />Backtrace:<pre>';
1157 debug_print_backtrace();
1161 // Set this function as called
1162 $GLOBALS[__FUNCTION__] = true;
1167 // Is the optional message set?
1168 if (!empty($message)) {
1170 $debug = sprintf("Note: %s<br />\n",
1174 // @TODO Add a little more infos here
1175 logDebugMessage($F, $L, strip_tags($message));
1179 $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(getPath(), '', getCachePath()) . 'debug.log</strong> in your report (you can now attach files):<pre>';
1180 $debug .= debug_get_printable_backtrace();
1182 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1183 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1185 // Send an email? (e.g. not wanted for evaluation errors)
1186 if (($sendEmail === true) && (!isInstallationPhase())) {
1189 'message' => trim($message),
1190 'backtrace' => trim(debug_get_mailable_backtrace())
1193 // Send email to webmaster
1194 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1198 app_die($F, $L, $debug);
1201 // Compile characters which are allowed in URLs
1202 function compileUriCode ($code, $simple = true) {
1203 // Compile constants
1204 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1206 // Compile QUOT and other non-HTML codes
1207 $code = str_replace('{DOT}', '.',
1208 str_replace('{SLASH}', '/',
1209 str_replace('{QUOT}', "'",
1210 str_replace('{DOLLAR}', '$',
1211 str_replace('{OPEN_ANCHOR}', '(',
1212 str_replace('{CLOSE_ANCHOR}', ')',
1213 str_replace('{OPEN_SQR}', '[',
1214 str_replace('{CLOSE_SQR}', ']',
1215 str_replace('{PER}', '%',
1219 // Return compiled code
1223 // Handle message codes from URL
1224 function handleCodeMessage () {
1225 if (isGetRequestParameterSet('code')) {
1226 // Default extension is 'unknown'
1229 // Is extension given?
1230 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1232 // Convert the 'code' parameter from URL to a human-readable message
1233 $message = getMessageFromErrorCode(getRequestParameter('code'));
1235 // Load message template
1236 loadTemplate('message', false, $message);
1240 // Generates a 'extension foo inactive' message
1241 function generateExtensionInactiveMessage ($ext_name) {
1242 // Is the extension empty?
1243 if (empty($ext_name)) {
1244 // This should not happen
1245 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1249 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1251 // Is an admin logged in?
1253 // Then output admin message
1254 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1257 // Return prepared message
1261 // Generates a 'extension foo not installed' message
1262 function generateExtensionNotInstalledMessage ($ext_name) {
1263 // Is the extension empty?
1264 if (empty($ext_name)) {
1265 // This should not happen
1266 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1270 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1272 // Is an admin logged in?
1274 // Then output admin message
1275 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1278 // Return prepared message
1282 // Generates a message depending on if the extension is not installed or not
1284 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1288 // Is the extension not installed or just deactivated?
1289 switch (isExtensionInstalled($ext_name)) {
1290 case true; // Deactivated!
1291 $message = generateExtensionInactiveMessage($ext_name);
1294 case false; // Not installed!
1295 $message = generateExtensionNotInstalledMessage($ext_name);
1298 default: // Should not happen!
1299 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1300 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1304 // Return the message
1308 // Print code with line numbers
1309 function linenumberCode ($code) {
1310 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1311 $count_lines = count($codeE);
1313 $r = 'Line | Code:<br />';
1314 foreach($codeE as $line => $c) {
1315 $r .= '<div class="line"><span class="linenum">';
1316 if ($count_lines == 1) {
1319 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1324 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1327 return '<div class="code">' . $r . '</div>';
1330 // Determines the right page title
1331 function determinePageTitle () {
1332 // Config and database connection valid?
1333 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1337 // Title decoration enabled?
1338 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1340 // Do we have some extra title?
1341 if (isExtraTitleSet()) {
1343 $TITLE .= getExtraTitle() . ' by ';
1347 $TITLE .= getMainTitle();
1349 // Add title of module? (middle decoration will also be added!)
1350 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1351 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1354 // Add title from what file
1356 if (getModule() == 'login') $mode = 'member';
1357 elseif (getModule() == 'index') $mode = 'guest';
1358 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1360 // Add title decorations? (right)
1361 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1363 // Remember title in constant for the template
1364 $pageTitle = $TITLE;
1365 } elseif ((isInstalled()) && (isAdminRegistered())) {
1366 // Installed, admin registered but no ext-sql_patches
1367 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1368 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1369 // Installed but no admin registered
1370 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1371 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1372 // Installation mode
1373 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1375 // Configuration not found!
1376 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1378 // Do not add the fatal message in installation mode
1379 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1383 return decodeEntities($pageTitle);
1386 // Checks wethere there is a cache file there. This function is cached.
1387 function isTemplateCached ($template) {
1388 // Do we have cached this result?
1389 if (!isset($GLOBALS['template_cache'][$template])) {
1391 $FQFN = generateCacheFqfn($template);
1394 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1398 return $GLOBALS['template_cache'][$template];
1401 // Flushes non-flushed template cache to disk
1402 function flushTemplateCache ($template, $eval) {
1403 // Is this cache flushed?
1404 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1406 $FQFN = generateCacheFqfn($template);
1409 writeToFile($FQFN, $eval, true);
1413 // Reads a template cache
1414 function readTemplateCache ($template) {
1416 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1417 // This should not happen
1418 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1422 if (!isset($GLOBALS['template_eval'][$template])) {
1424 $FQFN = generateCacheFqfn($template);
1427 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1431 return $GLOBALS['template_eval'][$template];
1434 // Escapes quotes (default is only double-quotes)
1435 function escapeQuotes ($str, $single = false) {
1436 // Should we escape all?
1437 if ($single === true) {
1438 // Escape all (including null)
1439 $str = addslashes($str);
1441 // Remove escaping of single quotes
1442 $str = str_replace("\'", "'", $str);
1444 // Escape only double-quotes but prevent double-quoting
1445 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1448 // Return the escaped string
1452 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1453 function escapeJavaScriptQuotes ($str) {
1454 // Replace all double-quotes and secure back-ticks
1455 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1461 // Send out mails depending on the 'mod/modes' combination
1462 // @TODO Lame description for this function
1463 function sendModeMails ($mod, $modes) {
1465 if (fetchUserData(getMemberId())) {
1466 // Extract salt from cookie
1467 $salt = substr(getSession('u_hash'), 0, -40);
1469 // Now let's compare passwords
1470 $hash = encodeHashForCookie(getUserData('password'));
1472 // Does the hash match or should we change it?
1473 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1475 $content = getUserDataArray();
1477 // Clear/init the content variable
1478 $content['message'] = '';
1481 // @TODO Move this in a filter
1484 foreach ($modes as $mode) {
1486 case 'normal': break; // Do not add any special lines
1487 case 'email': // Email was changed!
1488 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1491 case 'password': // Password was changed
1492 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1496 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1497 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1502 if (isExtensionActive('country')) {
1503 // Replace code with description
1504 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1507 // Merge content with data from POST
1508 $content = merge_array($content, postRequestArray());
1511 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1513 if (isAdminNotificationEnabled()) {
1514 // The admin needs to be notified about a profile change
1515 $message_admin = 'admin_mydata_notify';
1516 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1519 $message_admin = '';
1523 // Set subject lines
1524 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1526 // Output success message
1527 $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1530 default: // Unsupported module!
1531 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1532 $content = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1536 // Passwords mismatch
1537 $content = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1540 // Could not load profile
1541 $content = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1544 // Send email to user if required
1545 if ((!empty($sub_mem)) && (!empty($message))) {
1547 sendEmail($content['email'], $sub_mem, $message);
1550 // Send only if no other error has occured
1551 if (empty($content)) {
1552 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1554 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1555 } elseif (isAdminNotificationEnabled()) {
1556 // Cannot send mails to admin!
1557 $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1560 $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1565 loadTemplate('admin_settings_saved', false, $content);
1568 // Generates a 'selection box' from given array
1569 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1571 $OUT = '<select name="' . $name . '" size="1" class="form_select">
1572 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1574 // Walk through all options
1575 foreach ($options as $option) {
1576 // Add the <option> entry
1577 if (empty($optionContent)) {
1578 // ... from template
1579 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1582 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1586 // Finish selection box
1587 $OUT .= '</select>';
1591 'selection_box' => $OUT,
1594 // Load template and return it
1595 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1598 // Prepares the header for HTML output
1599 function loadHtmlHeader () {
1601 // 1.) pre_page_header (mainly loads the page_header template and includes
1602 // meta description)
1603 runFilterChain('pre_page_header');
1605 // Here can be something be added, but normally one of the two filters
1606 // around this line should do the job for you.
1608 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1609 // to close the head-tag)
1610 // Include more header data here
1611 runFilterChain('post_page_header');
1614 // Adds page header and footer to output array element
1615 function addPageHeaderFooter () {
1619 // Add them all together. This is maybe to simple
1620 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1621 // Add page part if set
1622 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1625 // Transfer $OUT to 'output'
1626 $GLOBALS['output'] = $OUT;
1629 // Generates meta description for current module and 'what' value
1630 function generateMetaDescriptionCode () {
1631 // Only include from guest area and if sql_patches has correct version
1632 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1633 // Construct dynamic description
1634 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1636 // Output it directly
1637 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1641 unset($GLOBALS['ref_level']);
1644 // Generates an FQFN for template cache from the given template name
1645 function generateCacheFqfn ($template, $mode = 'html') {
1647 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1648 // Generate the FQFN
1649 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1650 "%s_compiled/%s/%s.tpl.cache",
1658 return $GLOBALS['template_cache_fqfn'][$template];
1661 // "Fixes" null or empty string to count of dashes
1662 function fixNullEmptyToDashes ($str, $num) {
1663 // Use str as default
1667 if ((is_null($str)) || (trim($str) == '')) {
1669 $return = str_repeat('-', $num);
1672 // Return final string
1676 //-----------------------------------------------------------------------------
1677 // Template Helper Functions
1678 //-----------------------------------------------------------------------------
1680 // Color-switch helper function
1681 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1683 if (!isset($GLOBALS['color_switch'][$template])) {
1685 initTemplateColorSwitch($template);
1686 } elseif ($clear === false) {
1687 // Switch color if called from loadTemplate()
1688 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1689 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1692 // Return CSS class name
1693 if ($return === true) {
1694 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1695 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1699 // Helper function for extension registration link
1700 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1701 // Default is all productive
1702 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1704 // Is the given extension non-productive?
1705 if (!isExtensionProductive($ext_name)) {
1706 // Non-productive code
1707 $OUT = '<em style="cursor:help" class="notice" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</em>';