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 (getOutputMode() != 0) {
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 = '---';
85 // Color-switch helper function
86 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
88 if (!isset($GLOBALS['color_switch'][$template])) {
90 initTemplateColorSwitch($template);
91 } elseif ($clear === false) {
92 // Switch color if called from loadTemplate()
93 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
94 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
97 // Return CSS class name
98 if ($return === true) {
99 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
100 return 'switch_sw' . $GLOBALS['color_switch'][$template];
105 function initTemplateColorSwitch ($template) {
106 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
107 $GLOBALS['color_switch'][$template] = 2;
110 // "Getter" for color switch code
111 function getColorSwitchCode ($template) {
113 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
119 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
120 function outputHtml ($htmlCode, $newLine = true) {
122 if (!isset($GLOBALS['output'])) {
123 $GLOBALS['output'] = '';
126 // Do we have HTML-Code here?
127 if (!empty($htmlCode)) {
128 // Yes, so we handle it as you have configured
129 switch (getConfig('OUTPUT_MODE')) {
131 // That's why you don't need any \n at the end of your HTML code... :-)
132 if (getPhpCaching() == 'on') {
133 // Output into PHP's internal buffer
134 outputRawCode($htmlCode);
136 // That's why you don't need any \n at the end of your HTML code... :-)
137 if ($newLine === true) print("\n");
139 // Render mode for old or lame servers...
140 $GLOBALS['output'] .= $htmlCode;
142 // That's why you don't need any \n at the end of your HTML code... :-)
143 if ($newLine === true) $GLOBALS['output'] .= "\n";
148 // If we are switching from render to direct output rendered code
149 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
151 // The same as above... ^
152 outputRawCode($htmlCode);
153 if ($newLine === true) print("\n");
157 // Huh, something goes wrong or maybe you have edited config.php ???
158 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
161 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
162 // Output cached HTML code
163 $GLOBALS['output'] = ob_get_contents();
165 // Clear output buffer for later output if output is found
166 if (!empty($GLOBALS['output'])) {
170 // Send all HTTP headers
173 // Compile and run finished rendered HTML code
174 compileFinalOutput();
176 // Output code here, DO NOT REMOVE! ;-)
177 outputRawCode($GLOBALS['output']);
178 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
179 // Send all HTTP headers
182 // Compile and run finished rendered HTML code
183 compileFinalOutput();
185 // Output code here, DO NOT REMOVE! ;-)
186 outputRawCode($GLOBALS['output']);
188 // And flush all headers
193 // Compiles the final output
194 function compileFinalOutput () {
195 // Add page header and footer
196 addPageHeaderFooter();
198 // Do the final compilation
199 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
201 // Extension 'rewrite' installed?
202 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
203 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
207 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
208 // Compress it for HTTP gzip
209 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
212 sendHeader('Content-Encoding: gzip');
213 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
214 // Compress it for HTTP deflate
215 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
218 sendHeader('Content-Encoding: deflate');
222 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
228 // Main compilation loop
229 function doFinalCompilation ($code, $insertComments = true) {
230 // Insert comments? (Only valid with HTML templates, of course)
231 enableTemplateHtml($insertComments);
237 while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 4)) {
238 // Init common variables
243 //* DEBUG: */ debugOutput('<pre>'.encodeEntities($code).'</pre>');
244 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code))) . '";';
245 //* DEBUG: */ if ($insertComments) die('<pre>'.linenumberCode($eval).'</pre>');
247 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
249 // Was that eval okay?
250 if (empty($newContent)) {
251 // Something went wrong!
252 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
262 // Return the compiled code
266 // Output the raw HTML code
267 function outputRawCode ($htmlCode) {
268 // Output stripped HTML code to avoid broken JavaScript code, etc.
269 print(str_replace('{BACK}', "\\", $htmlCode));
271 // Flush the output if only getPhpCaching() is not 'on'
272 if (getPhpCaching() != 'on') {
278 // Load a template file and return it's content (only it's name; do not use ' or ")
279 function loadTemplate ($template, $return = false, $content = array()) {
280 // @TODO Remove this sanity-check if all is fine
281 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
283 // Set current template
284 $GLOBALS['current_template'] = $template;
287 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
288 // Evaluate the cache
289 eval(readTemplateCache($template));
290 } elseif (!isset($GLOBALS['template_eval'][$template])) {
291 // Make all template names lowercase
292 $template = strtolower($template);
296 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
299 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
300 $extraPath = detectExtraTemplatePath($template);;
302 ////////////////////////
303 // Generate file name //
304 ////////////////////////
305 $FQFN = $basePath . $extraPath . $template . '.tpl';
307 // Does the special template exists?
308 if (!isFileReadable($FQFN)) {
309 // Reset to default template
310 $FQFN = $basePath . $template . '.tpl';
313 // Now does the final template exists?
314 if (isFileReadable($FQFN)) {
315 // Count the template load
316 incrementConfigEntry('num_templates');
318 // The local file does exists so we load it. :)
319 $GLOBALS['tpl_content'] = readFromFile($FQFN);
321 // Do we have to compile the code?
323 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
324 // Normal HTML output?
325 if (getOutputMode() == '0') {
326 // Add surrounding HTML comments to help finding bugs faster
327 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
329 // Prepare eval() command
330 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
331 } elseif (substr($template, 0, 3) == 'js_') {
332 // JavaScripts don't like entities and timings
333 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
335 // Prepare eval() command, other output doesn't like entities, maybe
336 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
339 // Add surrounding HTML comments to help finding bugs faster
340 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
341 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
343 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
344 // Only admins shall see this warning or when installation mode is active
345 $ret = '<div class="para">
346 <span class="guest_failed">{--TEMPLATE_404--}</span>
352 {--TEMPLATE_CONTENT--}
353 <pre>' . print_r($content, true) . '</pre>
355 <pre>' . print_r($DATA, true) . '</pre>
359 $GLOBALS['template_eval'][$template] = '404';
364 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
366 eval($GLOBALS['template_eval'][$template]);
369 // Do we have some content to output or return?
371 // Not empty so let's put it out! ;)
372 if ($return === true) {
373 // Return the HTML code
379 } elseif (isDebugModeEnabled()) {
380 // Warning, empty output!
381 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
385 // Detects the extra template path from given template name
386 function detectExtraTemplatePath ($template) {
391 if (!isset($GLOBALS['extra_path'][$template])) {
392 // Check for admin/guest/member/etc. templates
393 if (substr($template, 0, 6) == 'admin_') {
394 // Admin template found
395 $extraPath = 'admin/';
396 } elseif (substr($template, 0, 6) == 'guest_') {
397 // Guest template found
398 $extraPath = 'guest/';
399 } elseif (substr($template, 0, 7) == 'member_') {
400 // Member template found
401 $extraPath = 'member/';
402 } elseif (substr($template, 0, 7) == 'select_') {
403 // Selection template found
404 $extraPath = 'select/';
405 } elseif (substr($template, 0, 8) == 'install_') {
406 // Installation template found
407 $extraPath = 'install/';
408 } elseif (substr($template, 0, 4) == 'ext_') {
409 // Extension template found
411 } elseif (substr($template, 0, 3) == 'la_') {
412 // 'Logical-area' template found
414 } elseif (substr($template, 0, 3) == 'js_') {
415 // JavaScript template found
417 } elseif (substr($template, 0, 5) == 'menu_') {
418 // Menu template found
419 $extraPath = 'menu/';
421 // Test for extension
422 $test = substr($template, 0, strpos($template, '_'));
424 // Probe for valid extension name
425 if (isExtensionNameValid($test)) {
426 // Set extra path to extension's name
427 $extraPath = $test . '/';
432 $GLOBALS['extra_path'][$template] = $extraPath;
436 return $GLOBALS['extra_path'][$template];
439 // Loads an email template and compiles it
440 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
443 // Make sure all template names are lowercase!
444 $template = strtolower($template);
446 // Is content an array?
447 if (is_array($content)) {
448 // Add expiration to array
449 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
450 // Will never expire!
451 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
452 } elseif (isConfigEntrySet('auto_purge')) {
453 // Create nice date string
454 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
457 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
463 if (($userid > 0) && (is_array($content))) {
464 // If nickname extension is installed, fetch nickname as well
465 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
466 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
468 fetchUserData($userid, 'nickname');
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
472 fetchUserData($userid);
475 // Merge data if valid
476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
477 if (isUserDataValid()) {
478 $content = merge_array($content, getUserDataArray());
480 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
484 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
487 $extraPath = detectExtraTemplatePath($template);
489 // Generate full FQFN
490 $FQFN = $basePath . $extraPath . $template . '.tpl';
492 // Does the special template exists?
493 if (!isFileReadable($FQFN)) {
494 // Reset to default template
495 $FQFN = $basePath . $template . '.tpl';
498 // Now does the final template exists?
500 if (isFileReadable($FQFN)) {
501 // The local file does exists so we load it. :)
502 $GLOBALS['tpl_content'] = readFromFile($FQFN);
505 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
506 eval($GLOBALS['tpl_content']);
507 } elseif (!empty($template)) {
508 // Template file not found!
509 $newContent = '<div class="para">
510 {--TEMPLATE_404--}: ' . $template . '
513 {--TEMPLATE_CONTENT--}
514 <pre>' . print_r($content, true) . '</pre>
516 <pre>' . print_r($DATA, true) . '</pre>
519 // Debug mode not active? Then remove the HTML tags
520 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
522 // No template name supplied!
523 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
526 // Is there some content?
527 if (empty($newContent)) {
529 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
531 // Add last error if the required function exists
532 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
535 // Remove content and data
543 // "Getter" for menu CSS classes, mainly used in templates
544 function getMenuCssClasses ($data) {
545 // $data needs to be converted into an array
546 $content = explode('|', $data);
548 // Non-existent index 2 will happen in menu blocks
549 if (!isset($content[2])) $content[2] = '';
551 // Re-construct the array: 0=visible,1=locked,2=prefix
552 $content['visible'] = $content[0];
553 $content['locked'] = $content[1];
555 // Call our "translator" function
556 $content = translateMenuVisibleLocked($content, $content[2]);
558 // Return CSS classes
559 return ($content['visible_css'] . ' ' . $content['locked_css']);
562 // Generate XHTML code for the CAPTCHA
563 function generateCaptchaCode ($code, $type, $DATA, $userid) {
564 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
567 // Compiles the given HTML/mail code
568 function compileCode ($code, $simple = false, $constants = true, $full = true) {
569 // Is the code a string?
570 if (!is_string($code)) {
571 // Silently return it
576 $startCompile = microtime(true);
579 $code = compileRawCode($code, $simple, $constants, $full);
582 $compiled = microtime(true);
584 // Add timing if enabled
585 if (isTemplateHtml()) {
586 // Add timing, this should be disabled in
587 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
590 // Return compiled code
594 // Compiles the code (use compileCode() only for HTML because of the comments)
595 // @TODO $simple/$constants are deprecated
596 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
597 // Is the code a string?
598 if (!is_string($code)) {
599 // Silently return it
603 // Init replacement-array with smaller set of security characters
604 $secChars = $GLOBALS['url_chars'];
606 // Select full set of chars to replace when we e.g. want to compile URLs
607 if ($full === true) $secChars = $GLOBALS['security_chars'];
609 // Compile more through a filter
610 $code = runFilterChain('compile_code', $code);
612 // Compile message strings
613 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
615 // Compile QUOT and other non-HTML codes
616 foreach ($secChars['to'] as $k => $to) {
617 // Do the reversed thing as in inc/libs/security_functions.php
618 $code = str_replace($to, $secChars['from'][$k], $code);
621 // Find $content[bla][blub] entries
622 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
623 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
625 // Are some matches found?
626 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
627 // Replace all matches
628 $matchesFound = array();
629 foreach ($matches[0] as $key => $match) {
630 // Fuzzy look has failed by default
633 // Fuzzy look on match if already found
634 foreach ($matchesFound as $found => $set) {
636 $test = substr($found, 0, strlen($match));
638 // Does this entry exist?
639 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
640 if ($test == $match) {
642 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
649 if ($fuzzyFound === true) continue;
651 // Take all string elements
652 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
653 // Replace it in the code
654 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
655 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
656 $code = str_replace($match, '".' . $newMatch . '."', $code);
657 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
658 $matchesFound[$match] = 1;
659 } elseif (!isset($matchesFound[$match])) {
661 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
662 $code = str_replace($match, '".' . $match . '."', $code);
663 $matchesFound[$match] = 1;
673 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
677 // This is a yes/no selection only!
678 if ($id > 0) $prefix .= '[' . $id . ']';
679 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
681 // Begin with regular selection box here
682 if (!empty($prefix)) $prefix .= '_';
684 if ($id > 0) $type2 .= '[' . $id . ']';
685 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
690 for ($idx = 1; $idx < 32; $idx++) {
691 $OUT .= '<option value="' . $idx . '"';
692 if ($default == $idx) $OUT .= ' selected="selected"';
693 $OUT .= '>' . $idx . '</option>';
697 case 'month': // Month
698 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
699 $OUT .= '<option value="' . $idx . '"';
700 if ($default == $idx) $OUT .= ' selected="selected"';
701 $OUT .= '>' . $descr . '</option>';
709 // Use configured min age or fixed?
710 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
712 $startYear = $year - getConfig('min_age');
715 $startYear = $year - 16;
718 // Calculate earliest year (100 years old people can still enter Internet???)
719 $minYear = $year - 100;
721 // Check if the default value is larger than minimum and bigger than actual year
722 if (($default > $minYear) && ($default >= $year)) {
723 for ($idx = $year; $idx < ($year + 11); $idx++) {
724 $OUT .= '<option value="' . $idx . '"';
725 if ($default == $idx) $OUT .= ' selected="selected"';
726 $OUT .= '>' . $idx . '</option>';
728 } elseif ($default == -1) {
729 // Current year minus 1
730 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
731 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
734 // Get current year and subtract the configured minimum age
735 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
736 // Calculate earliest year depending on extension version
737 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
738 // Use configured minimum age
739 $year = getYear() - getConfig('min_age');
741 // Use fixed 16 years age
742 $year = getYear() - 16;
745 // Construct year selection list
746 for ($idx = $minYear; $idx <= $year; $idx++) {
747 $OUT .= '<option value="' . $idx . '"';
748 if ($default == $idx) $OUT .= ' selected="selected"';
749 $OUT .= '>' . $idx . '</option>';
756 for ($idx = 0; $idx < 60; $idx+=5) {
757 if (strlen($idx) == 1) $idx = '0' . $idx;
758 $OUT .= '<option value="' . $idx . '"';
759 if ($default == $idx) $OUT .= ' selected="selected"';
760 $OUT .= '>' . $idx . '</option>';
765 for ($idx = 0; $idx < 24; $idx++) {
766 if (strlen($idx) == 1) $idx = '0' . $idx;
767 $OUT .= '<option value="' . $idx . '"';
768 if ($default == $idx) $OUT .= ' selected="selected"';
769 $OUT .= '>' . $idx . '</option>';
774 $OUT .= '<option value="Y"';
775 if ($default == 'Y') $OUT .= ' selected="selected"';
776 $OUT .= '>{--YES--}</option><option value="N"';
777 if ($default != 'Y') $OUT .= ' selected="selected"';
778 $OUT .= '>{--NO--}</option>';
785 // Insert the code in $img_code into jpeg or PNG image
786 function generateImageOrCode ($img_code, $headerSent = true) {
787 // Is the code size oversized or shouldn't we display it?
788 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
789 // Stop execution of function here because of over-sized code length
790 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
791 } elseif ($headerSent === false) {
792 // Return an HTML code here
793 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
797 $img = sprintf("%s/theme/%s/images/code_bg.%s",
800 getConfig('img_type')
804 if (isFileReadable($img)) {
806 switch (getConfig('img_type')) {
808 // Okay, load image and hide all errors
809 $image = imagecreatefromjpeg($img);
813 // Okay, load image and hide all errors
814 $image = imagecreatefrompng($img);
818 // Exit function here
819 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
823 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
824 $text_color = imagecolorallocate($image, 0, 0, 0);
826 // Insert code into image
827 imagestring($image, 5, 14, 2, $img_code, $text_color);
830 sendHeader('Content-Type: image/' . getConfig('img_type'));
832 // Output image with matching image factory
833 switch (getConfig('img_type')) {
834 case 'jpg': imagejpeg($image); break;
835 case 'png': imagepng($image); break;
838 // Remove image from memory
839 imagedestroy($image);
841 // Create selection box or array of splitted timestamp
842 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
843 // Do not continue if ONE_DAY is absend
844 if (!isConfigEntrySet('ONE_DAY')) {
845 // And return the timestamp itself or empty array
846 if ($return_array === true) {
853 // Calculate 2-seconds timestamp
854 $stamp = round($timestamp);
855 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
857 // Do we have a leap year?
859 $TEST = getYear() / 4;
861 $M2 = getMonth(time() + $timestamp);
863 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
864 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
866 // First of all years...
867 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
868 //* DEBUG: */ debugOutput('Y=' . $Y);
870 $M = abs(floor($timestamp / 2628000 - $Y * 12));
871 //* DEBUG: */ debugOutput('M=' . $M);
873 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
874 //* DEBUG: */ debugOutput('W=' . $W);
876 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
877 //* DEBUG: */ debugOutput('D=' . $D);
879 $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));
880 //* DEBUG: */ debugOutput('h=' . $h);
882 $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));
883 //* DEBUG: */ debugOutput('m=' . $m);
884 // And at last seconds...
885 $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));
886 //* DEBUG: */ debugOutput('s=' . $s);
888 // Is seconds zero and time is < 60 seconds?
889 if (($s == '0') && ($timestamp < 60)) {
891 $s = round($timestamp);
895 // Now we convert them in seconds...
898 // Just put all data in an array for later use
910 $OUT = '<div align="' . $align . '">';
911 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
914 if (isInString('Y', $display) || (empty($display))) {
915 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
918 if (isInString('M', $display) || (empty($display))) {
919 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
922 if (isInString('W', $display) || (empty($display))) {
923 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
926 if (isInString('D', $display) || (empty($display))) {
927 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
930 if (isInString('h', $display) || (empty($display))) {
931 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
934 if (isInString('m', $display) || (empty($display))) {
935 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
938 if (isInString('s', $display) || (empty($display))) {
939 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
945 if (isInString('Y', $display) || (empty($display))) {
946 // Generate year selection
947 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
948 for ($idx = 0; $idx <= 10; $idx++) {
949 $OUT .= '<option class="mini_select" value="' . $idx . '"';
950 if ($idx == $Y) $OUT .= ' selected="selected"';
951 $OUT .= '>' . $idx . '</option>';
953 $OUT .= '</select></td>';
955 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
958 if (isInString('M', $display) || (empty($display))) {
959 // Generate month selection
960 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
961 for ($idx = 0; $idx <= 11; $idx++) {
962 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
963 if ($idx == $M) $OUT .= ' selected="selected"';
964 $OUT .= '>' . $idx . '</option>';
966 $OUT .= '</select></td>';
968 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
971 if (isInString('W', $display) || (empty($display))) {
972 // Generate week selection
973 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
974 for ($idx = 0; $idx <= 4; $idx++) {
975 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
976 if ($idx == $W) $OUT .= ' selected="selected"';
977 $OUT .= '>' . $idx . '</option>';
979 $OUT .= '</select></td>';
981 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
984 if (isInString('D', $display) || (empty($display))) {
985 // Generate day selection
986 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
987 for ($idx = 0; $idx <= 31; $idx++) {
988 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
989 if ($idx == $D) $OUT .= ' selected="selected"';
990 $OUT .= '>' . $idx . '</option>';
992 $OUT .= '</select></td>';
994 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
997 if (isInString('h', $display) || (empty($display))) {
998 // Generate hour selection
999 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1000 for ($idx = 0; $idx <= 23; $idx++) {
1001 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1002 if ($idx == $h) $OUT .= ' selected="selected"';
1003 $OUT .= '>' . $idx . '</option>';
1005 $OUT .= '</select></td>';
1007 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1010 if (isInString('m', $display) || (empty($display))) {
1011 // Generate minute selection
1012 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1013 for ($idx = 0; $idx <= 59; $idx++) {
1014 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1015 if ($idx == $m) $OUT .= ' selected="selected"';
1016 $OUT .= '>' . $idx . '</option>';
1018 $OUT .= '</select></td>';
1020 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1023 if (isInString('s', $display) || (empty($display))) {
1024 // Generate second selection
1025 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1026 for ($idx = 0; $idx <= 59; $idx++) {
1027 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1028 if ($idx == $s) $OUT .= ' selected="selected"';
1029 $OUT .= '>' . $idx . '</option>';
1031 $OUT .= '</select></td>';
1033 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1040 // Return generated HTML code
1044 // Generate a list of administrative links to a given userid
1045 function generateMemberAdminActionLinks ($userid) {
1046 // Make sure userid is a number
1047 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1049 // Define all main targets
1050 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1053 $status = getFetchedUserData('userid', $userid, 'status');
1055 // Begin of navigation links
1058 foreach ($targetArray as $tar) {
1059 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1060 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1061 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1062 // Locked accounts shall be unlocked
1063 $OUT .= 'UNLOCK_USER';
1065 // All other status is fine
1066 $OUT .= strtoupper($tar);
1068 $OUT .= '_TITLE--}">{--ADMIN_';
1069 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1070 // Locked accounts shall be unlocked
1071 $OUT .= 'UNLOCK_USER';
1073 // All other status is fine
1074 $OUT .= strtoupper($tar);
1076 $OUT .= '--}</a></span>|';
1079 // Finish navigation link
1080 $OUT = substr($OUT, 0, -1) . ']';
1086 // Generate an email link
1087 function generateEmailLink ($email, $table = 'admins') {
1088 // Default email link (INSECURE! Spammer can read this by harvester programs)
1089 $EMAIL = 'mailto:' . $email;
1091 // Check for several extensions
1092 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1093 // Create email link for contacting admin in guest area
1094 $EMAIL = generateAdminEmailLink($email);
1095 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1096 // Create email link for contacting a member within admin area (or later in other areas, too?)
1097 $EMAIL = generateUserEmailLink($email, 'admin');
1098 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1099 // Create email link to contact sponsor within admin area (or like the link above?)
1100 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1103 // Shall I close the link when there is no admin?
1104 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1106 // Return email link
1110 // Output error messages in a fasioned way and die...
1111 function app_die ($F, $L, $message) {
1112 // Check if Script is already dieing and not let it kill itself another 1000 times
1113 if (!isset($GLOBALS['app_died'])) {
1114 // Make sure, that the script realy realy diese here and now
1115 $GLOBALS['app_died'] = true;
1117 // Set content type as text/html
1118 setContentType('text/html');
1121 loadIncludeOnce('inc/header.php');
1123 // Rewrite message for output
1124 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1126 // Load the message template
1127 loadTemplate('app_die_message', false, $message);
1130 loadIncludeOnce('inc/footer.php');
1132 // Script tried to kill itself twice
1133 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1137 // Display parsing time and number of SQL queries in footer
1138 function displayParsingTime () {
1139 // Is the timer started?
1140 if (!isset($GLOBALS['startTime'])) {
1146 $endTime = microtime(true);
1148 // "Explode" both times
1149 $start = explode(' ', $GLOBALS['startTime']);
1150 $end = explode(' ', $endTime);
1151 $runTime = $end[0] - $start[0];
1152 if ($runTime < 0) $runTime = '0';
1155 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1157 'run_time' => $runTime,
1158 'sql_time' => (getConfig('sql_time') * 1000),
1161 // Load the template
1162 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1165 // Output a debug backtrace to the user
1166 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1167 // Is this already called?
1168 if (isset($GLOBALS[__FUNCTION__])) {
1170 print 'Message:'.$message.'<br />Backtrace:<pre>';
1171 debug_print_backtrace();
1175 // Set this function as called
1176 $GLOBALS[__FUNCTION__] = true;
1181 // Is the optional message set?
1182 if (!empty($message)) {
1184 $debug = sprintf("Note: %s<br />\n",
1188 // @TODO Add a little more infos here
1189 logDebugMessage($F, $L, strip_tags($message));
1193 $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>';
1194 $debug .= debug_get_printable_backtrace();
1196 $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
1197 $debug .= '<div>Thank you for finding bugs.</div>';
1199 // Send an email? (e.g. not wanted for evaluation errors)
1200 if (($sendEmail === true) && (!isInstallationPhase())) {
1203 'message' => trim($message),
1204 'backtrace' => trim(debug_get_mailable_backtrace())
1207 // Send email to webmaster
1208 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1212 app_die($F, $L, $debug);
1215 // Compile characters which are allowed in URLs
1216 function compileUriCode ($code, $simple = true) {
1217 // Compile constants
1218 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1220 // Compile QUOT and other non-HTML codes
1221 $code = str_replace('{DOT}', '.',
1222 str_replace('{SLASH}', '/',
1223 str_replace('{QUOT}', "'",
1224 str_replace('{DOLLAR}', '$',
1225 str_replace('{OPEN_ANCHOR}', '(',
1226 str_replace('{CLOSE_ANCHOR}', ')',
1227 str_replace('{OPEN_SQR}', '[',
1228 str_replace('{CLOSE_SQR}', ']',
1229 str_replace('{PER}', '%',
1233 // Return compiled code
1237 // Handle message codes from URL
1238 function handleCodeMessage () {
1239 if (isGetRequestParameterSet('code')) {
1240 // Default extension is 'unknown'
1243 // Is extension given?
1244 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1246 // Convert the 'code' parameter from URL to a human-readable message
1247 $message = getMessageFromErrorCode(getRequestParameter('code'));
1249 // Load message template
1250 loadTemplate('message', false, $message);
1254 // Generates a 'extension foo inactive' message
1255 function generateExtensionInactiveMessage ($ext_name) {
1256 // Is the extension empty?
1257 if (empty($ext_name)) {
1258 // This should not happen
1259 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1263 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1265 // Is an admin logged in?
1267 // Then output admin message
1268 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1271 // Return prepared message
1275 // Generates a 'extension foo not installed' message
1276 function generateExtensionNotInstalledMessage ($ext_name) {
1277 // Is the extension empty?
1278 if (empty($ext_name)) {
1279 // This should not happen
1280 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1284 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1286 // Is an admin logged in?
1288 // Then output admin message
1289 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1292 // Return prepared message
1296 // Generates a message depending on if the extension is not installed or not
1298 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1302 // Is the extension not installed or just deactivated?
1303 switch (isExtensionInstalled($ext_name)) {
1304 case true; // Deactivated!
1305 $message = generateExtensionInactiveMessage($ext_name);
1308 case false; // Not installed!
1309 $message = generateExtensionNotInstalledMessage($ext_name);
1312 default: // Should not happen!
1313 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1314 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1318 // Return the message
1322 // Print code with line numbers
1323 function linenumberCode ($code) {
1324 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1325 $count_lines = count($codeE);
1327 $r = 'Line | Code:<br />';
1328 foreach($codeE as $line => $c) {
1329 $r .= '<div class="line"><span class="linenum">';
1330 if ($count_lines == 1) {
1333 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1338 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1341 return '<div class="code">' . $r . '</div>';
1344 // Determines the right page title
1345 function determinePageTitle () {
1346 // Config and database connection valid?
1347 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1351 // Title decoration enabled?
1352 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1354 // Do we have some extra title?
1355 if (isExtraTitleSet()) {
1357 $TITLE .= getExtraTitle() . ' by ';
1361 $TITLE .= getConfig('MAIN_TITLE');
1363 // Add title of module? (middle decoration will also be added!)
1364 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1365 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
1368 // Add title from what file
1370 if (getModule() == 'login') $mode = 'member';
1371 elseif (getModule() == 'index') $mode = 'guest';
1372 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1374 // Add title decorations? (right)
1375 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1377 // Remember title in constant for the template
1378 $pageTitle = $TITLE;
1379 } elseif ((isInstalled()) && (isAdminRegistered())) {
1380 // Installed, admin registered but no ext-sql_patches
1381 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
1382 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1383 // Installed but no admin registered
1384 $pageTitle = '{--SETUP_OF_MAILER--}';
1385 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1386 // Installation mode
1387 $pageTitle = '{--INSTALLATION_OF_MAILER--}';
1389 // Configuration not found!
1390 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1392 // Do not add the fatal message in installation mode
1393 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1397 return decodeEntities($pageTitle);
1400 // Checks wethere there is a cache file there. This function is cached.
1401 function isTemplateCached ($template) {
1402 // Do we have cached this result?
1403 if (!isset($GLOBALS['template_cache'][$template])) {
1405 $FQFN = generateCacheFqfn($template);
1408 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1412 return $GLOBALS['template_cache'][$template];
1415 // Flushes non-flushed template cache to disk
1416 function flushTemplateCache ($template, $eval) {
1417 // Is this cache flushed?
1418 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1420 $FQFN = generateCacheFqfn($template);
1423 writeToFile($FQFN, $eval, true);
1427 // Reads a template cache
1428 function readTemplateCache ($template) {
1430 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1431 // This should not happen
1432 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1436 if (!isset($GLOBALS['template_eval'][$template])) {
1438 $FQFN = generateCacheFqfn($template);
1441 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1445 return $GLOBALS['template_eval'][$template];
1448 // Escapes quotes (default is only double-quotes)
1449 function escapeQuotes ($str, $single = false) {
1450 // Should we escape all?
1451 if ($single === true) {
1452 // Escape all (including null)
1453 $str = addslashes($str);
1455 // Escape only double-quotes but prevent double-quoting
1456 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1459 // Return the escaped string
1463 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1464 function escapeJavaScriptQuotes ($str) {
1465 // Replace all double-quotes and secure back-ticks
1466 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1472 // Send out mails depending on the 'mod/modes' combination
1473 // @TODO Lame description for this function
1474 function sendModeMails ($mod, $modes) {
1476 if (fetchUserData(getMemberId())) {
1477 // Extract salt from cookie
1478 $salt = substr(getSession('u_hash'), 0, -40);
1480 // Now let's compare passwords
1481 $hash = encodeHashForCookie(getUserData('password'));
1483 // Does the hash match or should we change it?
1484 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1486 $content = getUserDataArray();
1488 // Clear/init the content variable
1489 $content['message'] = '';
1492 // @TODO Move this in a filter
1495 foreach ($modes as $mode) {
1497 case 'normal': break; // Do not add any special lines
1498 case 'email': // Email was changed!
1499 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1502 case 'pass': // Password was changed
1503 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1507 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1508 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1513 if (isExtensionActive('country')) {
1514 // Replace code with description
1515 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1518 // Merge content with data from POST
1519 $content = merge_array($content, postRequestArray());
1522 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1524 if (getConfig('admin_notify') == 'Y') {
1525 // The admin needs to be notified about a profile change
1526 $message_admin = 'admin_mydata_notify';
1527 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1530 $message_admin = '';
1534 // Set subject lines
1535 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1537 // Output success message
1538 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1541 default: // Unsupported module!
1542 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1543 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
1547 // Passwords mismatch
1548 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
1551 // Could not load profile
1552 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1555 // Send email to user if required
1556 if ((!empty($sub_mem)) && (!empty($message))) {
1558 sendEmail($content['email'], $sub_mem, $message);
1561 // Send only if no other error has occured
1562 if (empty($content)) {
1563 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1565 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1566 } elseif (getConfig('admin_notify') == 'Y') {
1567 // Cannot send mails to admin!
1568 $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1571 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1576 loadTemplate('admin_settings_saved', false, $content);
1579 // Generates a 'selection box' from given array
1580 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1582 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
1583 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1585 // Walk through all options
1586 foreach ($options as $option) {
1587 // Add the <option> entry
1588 if (empty($optionContent)) {
1589 // ... from template
1590 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1593 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1597 // Finish selection box
1598 $OUT .= '</select>';
1602 'selection_box' => $OUT,
1605 // Load template and return it
1606 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1609 // Prepares the header for HTML output
1610 function loadHtmlHeader () {
1612 // 1.) pre_page_header (mainly loads the page_header template and includes
1613 // meta description)
1614 runFilterChain('pre_page_header');
1616 // Here can be something be added, but normally one of the two filters
1617 // around this line should do the job for you.
1619 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1620 // to close the head-tag)
1621 // Include more header data here
1622 runFilterChain('post_page_header');
1625 // Adds page header and footer to output array element
1626 function addPageHeaderFooter () {
1630 // Add them all together. This is maybe to simple
1631 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1632 // Add page part if set
1633 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1636 // Transfer $OUT to 'output'
1637 $GLOBALS['output'] = $OUT;
1640 // Generates meta description for current module and 'what' value
1641 function generateMetaDescriptionCode () {
1642 // Only include from guest area and if sql_patches has correct version
1643 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1644 // Construct dynamic description
1645 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1647 // Output it directly
1648 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1652 unset($GLOBALS['ref_level']);
1655 // Generates an FQFN for template cache from the given template name
1656 function generateCacheFqfn ($template, $mode = 'html') {
1658 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1659 // Generate the FQFN
1660 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1661 "%s_compiled/%s/%s.tpl.cache",
1662 getConfig('CACHE_PATH'),
1669 return $GLOBALS['template_cache_fqfn'][$template];
1672 // "Fixes" null or empty string to count of dashes
1673 function fixNullEmptyToDashes ($str, $num) {
1674 // Use str as default
1678 if ((is_null($str)) || (trim($str) == '')) {
1680 $return = str_repeat('-', $num);
1683 // Return final string