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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Wrapper until we merged to the EL branch
44 function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
45 return compileCode($code, false, true, $full);
48 // Setter for 'is_template_html'
49 function enableTemplateHtml ($enable = true) {
50 $GLOBALS['is_template_html'] = (bool) $enable;
53 // Checks wether the template is HTML or not by previously set flag
55 function isTemplateHtml () {
56 // Is the output_mode other than 0 (HTML), then no comments are enabled
57 if (!isHtmlOutputMode()) {
62 return $GLOBALS['is_template_html'];
66 // Wrapper for writing debug informations to the browser
67 function debugOutput ($message) {
68 outputHtml('<div class="debug_message">' . $message . '</div>');
71 // "Fixes" an empty string into three dashes (use for templates)
72 function fixEmptyContentToDashes ($str) {
76 // Is the string empty?
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)) && ($count < 7)) {
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(), $compileCode = true) {
265 if (!is_bool($return)) {
266 // @TODO Remove this sanity-check if all is fine
267 debug_report_bug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
268 } elseif (!is_string($template)) {
269 // $template has to be string
270 debug_report_bug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
273 // Set current template
274 $GLOBALS['current_template'] = $template;
277 if ((!isDebuggingTemplateCache()) && (isTemplateCached($template))) {
278 // Evaluate the cache
279 eval(readTemplateCache($template));
280 } elseif (!isset($GLOBALS['template_eval'][$template])) {
281 // Make all template names lowercase
282 $template = strtolower($template);
288 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
289 $extraPath = detectExtraTemplatePath($template);
292 $FQFN = $basePath . $extraPath . $template . '.tpl';
294 // Does the special template exists?
295 if (!isFileReadable($FQFN)) {
296 // Reset to default template
297 $FQFN = $basePath . $template . '.tpl';
300 // Now does the final template exists?
301 if (isFileReadable($FQFN)) {
302 // Count the template load
303 incrementConfigEntry('num_templates');
305 // The local file does exists so we load it. :)
306 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
308 // Do we have to compile the code?
310 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)) {
311 // Normal HTML output?
312 if (isHtmlOutputMode()) {
313 // Add surrounding HTML comments to help finding bugs faster
314 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
316 // Prepare eval() command
317 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
318 } elseif (substr($template, 0, 3) == 'js_') {
319 // JavaScripts don't like entities and timings
320 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
322 // Prepare eval() command, other output doesn't like entities, maybe
323 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
325 } elseif (isHtmlOutputMode()) {
326 // Add surrounding HTML comments to help finding bugs faster
327 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
328 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
331 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
333 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
334 // Only admins shall see this warning or when installation mode is active
335 $ret = '<div class="para">
336 <span class="notice">{--TEMPLATE_404--}</span>
342 {--TEMPLATE_CONTENT--}:
343 <pre>' . print_r($content, true) . '</pre>
347 $GLOBALS['template_eval'][$template] = '404';
352 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
354 eval($GLOBALS['template_eval'][$template]);
357 // Do we have some content to output or return?
359 // Not empty so let's put it out! ;)
360 if ($return === true) {
361 // Return the HTML code
367 } elseif (isDebugModeEnabled()) {
368 // Warning, empty output!
369 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
373 // Detects the extra template path from given template name
374 function detectExtraTemplatePath ($template) {
379 if (!isset($GLOBALS['extra_path'][$template])) {
380 // Check for admin/guest/member/etc. templates
381 if (substr($template, 0, 6) == 'admin_') {
382 // Admin template found
383 $extraPath = 'admin/';
384 } elseif (substr($template, 0, 6) == 'guest_') {
385 // Guest template found
386 $extraPath = 'guest/';
387 } elseif (substr($template, 0, 7) == 'member_') {
388 // Member template found
389 $extraPath = 'member/';
390 } elseif (substr($template, 0, 7) == 'select_') {
391 // Selection template found
392 $extraPath = 'select/';
393 } elseif (substr($template, 0, 8) == 'install_') {
394 // Installation template found
395 $extraPath = 'install/';
396 } elseif (substr($template, 0, 4) == 'ext_') {
397 // Extension template found
399 } elseif (substr($template, 0, 3) == 'la_') {
400 // 'Logical-area' template found
402 } elseif (substr($template, 0, 3) == 'js_') {
403 // JavaScript template found
405 } elseif (substr($template, 0, 5) == 'menu_') {
406 // Menu template found
407 $extraPath = 'menu/';
409 // Test for extension
410 $test = substr($template, 0, strpos($template, '_'));
412 // Probe for valid extension name
413 if (isExtensionNameValid($test)) {
414 // Set extra path to extension's name
415 $extraPath = $test . '/';
420 $GLOBALS['extra_path'][$template] = $extraPath;
424 return $GLOBALS['extra_path'][$template];
427 // Loads an email template and compiles it
428 function loadEmailTemplate ($template, $content = array(), $userid = '0', $loadUserData = true) {
431 // Make sure all template names are lowercase!
432 $template = strtolower($template);
434 // Is content an array?
435 if (is_array($content)) {
436 // Add expiration to array
437 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
438 // Will never expire!
439 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
440 } elseif (isConfigEntrySet('auto_purge')) {
441 // Create nice date string
442 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
445 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
450 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
451 if ((isValidUserId($userid)) && (is_array($content))) {
452 // If nickname extension is installed, fetch nickname as well
453 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
456 fetchUserData($userid, 'nickname');
457 } elseif (isNicknameUsed($userid)) {
458 // Non-number characters entered but no ext-nickname found
459 debug_report_bug(__FUNCTION__, __LINE__, 'userid=' . $userid . ': is no id number and ext-nickname is gone.');
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
463 fetchUserData($userid);
466 // Merge data if valid
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
468 if ((isUserDataValid()) && ($loadUserData === true)) {
470 $content = merge_array($content, getUserDataArray());
472 // But we don't like hashed passwords be mailed
473 unset($content['password']);
476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
480 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
483 $extraPath = detectExtraTemplatePath($template);
485 // Generate full FQFN
486 $FQFN = $basePath . $extraPath . $template . '.tpl';
488 // Does the special template exists?
489 if (!isFileReadable($FQFN)) {
490 // Reset to default template
491 $FQFN = $basePath . $template . '.tpl';
494 // Now does the final template exists?
496 if (isFileReadable($FQFN)) {
497 // The local file does exists so we load it. :)
498 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
501 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
502 eval($GLOBALS['tpl_content'][$template]);
503 } elseif (!empty($template)) {
504 // Template file not found
505 $newContent = '<div class="para">
506 {--TEMPLATE_404--}: ' . $template . '
509 {--TEMPLATE_CONTENT--}:
510 <pre>' . print_r($content, true) . '</pre>
512 <pre>' . print_r($DATA, true) . '</pre>
515 // Debug mode not active? Then remove the HTML tags
516 if (!isDebugModeEnabled()) {
518 $newContent = secureString($newContent);
521 // No template name supplied!
522 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
525 // Is there some content?
526 if (empty($newContent)) {
528 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
530 // Add last error if the required function exists
531 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
534 // Remove content and data
542 // "Getter" for menu CSS classes, mainly used in templates
543 function getMenuCssClasses ($data) {
544 // $data needs to be converted into an array
545 $content = explode('|', $data);
547 // Non-existent index 2 will happen in menu blocks
548 if (!isset($content[2])) $content[2] = '';
550 // Re-construct the array: 0=visible,1=locked,2=prefix
551 $content['visible'] = $content[0];
552 $content['locked'] = $content[1];
554 // Call our "translator" function
555 $content = translateMenuVisibleLocked($content, $content[2]);
557 // Return CSS classes
558 return ($content['visible_css'] . ' ' . $content['locked_css']);
561 // Generate XHTML code for the CAPTCHA
562 function generateCaptchaCode ($code, $type, $type, $userid) {
563 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $type . '&mode=img&code=' . $code . '%}" />';
566 // Compiles the given HTML/mail code
567 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
568 // Is the code a string or should we not compile?
569 if ((!is_string($code)) || ($compileCode === false)) {
570 // Silently return it
575 $startCompile = microtime(true);
578 $code = compileRawCode($code, $simple, $constants, $full);
581 $compiled = microtime(true);
583 // Add timing if enabled
584 if (isTemplateHtml()) {
585 // Add timing, this should be disabled in
586 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
589 // Return compiled code
593 // Compiles the code (use compileCode() only for HTML because of the comments)
594 // @TODO $simple/$constants are deprecated
595 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
596 // Is the code a string or shall we not compile?
597 if ((!is_string($code)) || ($compileCode === false)) {
598 // Silently return it
602 // Init replacement-array with smaller set of security characters
603 $secChars = $GLOBALS['url_chars'];
605 // Select full set of chars to replace when we e.g. want to compile URLs
606 if ($full === true) {
607 $secChars = $GLOBALS['security_chars'];
610 // Compile more through a filter
611 $code = runFilterChain('compile_code', $code);
613 // Compile message strings
614 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
616 // Compile QUOT and other non-HTML codes
617 $code = str_replace($secChars['to'], $secChars['from'], $code);
619 // Find $content[bla][blub] entries
620 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
621 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
623 // Are some matches found?
624 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
625 // Replace all matches
626 $matchesFound = array();
627 foreach ($matches[0] as $key => $match) {
628 // Fuzzy look has failed by default
631 // Fuzzy look on match if already found
632 foreach ($matchesFound as $found => $set) {
634 $test = substr($found, 0, strlen($match));
636 // Does this entry exist?
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
638 if ($test == $match) {
640 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
647 if ($fuzzyFound === true) continue;
649 // Take all string elements
650 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
651 // Replace it in the code
652 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
653 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
654 $code = str_replace($match, '".' . $newMatch . '."', $code);
655 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
656 $matchesFound[$match] = 1;
657 } elseif (!isset($matchesFound[$match])) {
659 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
660 $code = str_replace($match, '".' . $match . '."', $code);
661 $matchesFound[$match] = 1;
671 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
675 // This is a yes/no selection only!
676 if ($id > 0) $prefix .= '[' . $id . ']';
677 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
679 // Begin with regular selection box here
680 if (!empty($prefix)) $prefix .= '_';
682 if ($id > 0) $type2 .= '[' . $id . ']';
683 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
688 for ($idx = 1; $idx < 32; $idx++) {
689 $OUT .= '<option value="' . $idx . '"';
690 if ($default == $idx) $OUT .= ' selected="selected"';
691 $OUT .= '>' . $idx . '</option>';
695 case 'month': // Month
696 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
697 $OUT .= '<option value="' . $idx . '"';
698 if ($default == $idx) $OUT .= ' selected="selected"';
699 $OUT .= '>' . $descr . '</option>';
707 // Use configured min age or fixed?
708 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
710 $startYear = $year - getConfig('min_age');
713 $startYear = $year - 16;
716 // Calculate earliest year (100 years old people can still enter Internet???)
717 $minYear = $year - 100;
719 // Check if the default value is larger than minimum and bigger than actual year
720 if (($default > $minYear) && ($default >= $year)) {
721 for ($idx = $year; $idx < ($year + 11); $idx++) {
722 $OUT .= '<option value="' . $idx . '"';
723 if ($default == $idx) $OUT .= ' selected="selected"';
724 $OUT .= '>' . $idx . '</option>';
726 } elseif ($default == -1) {
727 // Current year minus 1
728 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
729 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
732 // Get current year and subtract the configured minimum age
733 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
734 // Calculate earliest year depending on extension version
735 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
736 // Use configured minimum age
737 $year = getYear() - getConfig('min_age');
739 // Use fixed 16 years age
740 $year = getYear() - 16;
743 // Construct year selection list
744 for ($idx = $minYear; $idx <= $year; $idx++) {
745 $OUT .= '<option value="' . $idx . '"';
746 if ($default == $idx) $OUT .= ' selected="selected"';
747 $OUT .= '>' . $idx . '</option>';
754 for ($idx = 0; $idx < 60; $idx+=5) {
755 if (strlen($idx) == 1) $idx = '0' . $idx;
756 $OUT .= '<option value="' . $idx . '"';
757 if ($default == $idx) $OUT .= ' selected="selected"';
758 $OUT .= '>' . $idx . '</option>';
763 for ($idx = 0; $idx < 24; $idx++) {
764 if (strlen($idx) == 1) $idx = '0' . $idx;
765 $OUT .= '<option value="' . $idx . '"';
766 if ($default == $idx) $OUT .= ' selected="selected"';
767 $OUT .= '>' . $idx . '</option>';
772 $OUT .= '<option value="Y"';
773 if ($default == 'Y') $OUT .= ' selected="selected"';
774 $OUT .= '>{--YES--}</option><option value="N"';
775 if ($default != 'Y') $OUT .= ' selected="selected"';
776 $OUT .= '>{--NO--}</option>';
783 // Insert the code in $img_code into jpeg or PNG image
784 function generateImageOrCode ($img_code, $headerSent = true) {
785 // Is the code size oversized or shouldn't we display it?
786 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
787 // Stop execution of function here because of over-sized code length
788 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
789 } elseif ($headerSent === false) {
790 // Return an HTML code here
791 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
795 $img = sprintf("%s/theme/%s/images/code_bg.%s",
802 if (isFileReadable($img)) {
804 switch (getImgType()) {
805 case 'jpg': // Okay, load image and hide all errors
806 $image = imagecreatefromjpeg($img);
809 case 'png': // Okay, load image and hide all errors
810 $image = imagecreatefrompng($img);
814 // Silently log the error
815 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
819 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
820 $text_color = imagecolorallocate($image, 0, 0, 0);
822 // Insert code into image
823 imagestring($image, 5, 14, 2, $img_code, $text_color);
826 setContentType('image/' . getImgType());
828 // Output image with matching image factory
829 switch (getImgType()) {
830 case 'jpg': imagejpeg($image); break;
831 case 'png': imagepng($image); break;
834 // Remove image from memory
835 imagedestroy($image);
838 // Create selection box or array of splitted timestamp
839 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
840 // Do not continue if ONE_DAY is absend
841 if (!isConfigEntrySet('ONE_DAY')) {
842 // And return the timestamp itself or empty array
843 if ($return_array === true) {
850 // Calculate 2-seconds timestamp
851 $stamp = round($timestamp);
852 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
854 // Do we have a leap year?
856 $TEST = getYear() / 4;
858 $M2 = getMonth(time() + $timestamp);
860 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
861 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
862 $SWITCH = getOneDay();
865 // First of all years...
866 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
867 //* DEBUG: */ debugOutput('Y=' . $Y);
869 $M = abs(floor($timestamp / 2628000 - $Y * 12));
870 //* DEBUG: */ debugOutput('M=' . $M);
872 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
873 //* DEBUG: */ debugOutput('W=' . $W);
875 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
876 //* DEBUG: */ debugOutput('D=' . $D);
878 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
879 //* DEBUG: */ debugOutput('h=' . $h);
881 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getOneDay()) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
882 //* DEBUG: */ debugOutput('m=' . $m);
883 // And at last seconds...
884 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getOneDay()) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
885 //* DEBUG: */ debugOutput('s=' . $s);
887 // Is seconds zero and time is < 60 seconds?
888 if (($s == '0') && ($timestamp < 60)) {
890 $s = round($timestamp);
894 // Now we convert them in seconds...
897 // Just put all data in an array for later use
909 $OUT = '<div align="' . $align . '">';
910 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
913 if (isInString('Y', $display) || (empty($display))) {
914 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
917 if (isInString('M', $display) || (empty($display))) {
918 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
921 if (isInString('W', $display) || (empty($display))) {
922 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
925 if (isInString('D', $display) || (empty($display))) {
926 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
929 if (isInString('h', $display) || (empty($display))) {
930 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
933 if (isInString('m', $display) || (empty($display))) {
934 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
937 if (isInString('s', $display) || (empty($display))) {
938 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
944 if (isInString('Y', $display) || (empty($display))) {
945 // Generate year selection
946 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
947 for ($idx = 0; $idx <= 10; $idx++) {
948 $OUT .= '<option class="mini_select" value="' . $idx . '"';
949 if ($idx == $Y) $OUT .= ' selected="selected"';
950 $OUT .= '>' . $idx . '</option>';
952 $OUT .= '</select></td>';
954 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
957 if (isInString('M', $display) || (empty($display))) {
958 // Generate month selection
959 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
960 for ($idx = 0; $idx <= 11; $idx++) {
961 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
962 if ($idx == $M) $OUT .= ' selected="selected"';
963 $OUT .= '>' . $idx . '</option>';
965 $OUT .= '</select></td>';
967 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
970 if (isInString('W', $display) || (empty($display))) {
971 // Generate week selection
972 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
973 for ($idx = 0; $idx <= 4; $idx++) {
974 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
975 if ($idx == $W) $OUT .= ' selected="selected"';
976 $OUT .= '>' . $idx . '</option>';
978 $OUT .= '</select></td>';
980 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
983 if (isInString('D', $display) || (empty($display))) {
984 // Generate day selection
985 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
986 for ($idx = 0; $idx <= 31; $idx++) {
987 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
988 if ($idx == $D) $OUT .= ' selected="selected"';
989 $OUT .= '>' . $idx . '</option>';
991 $OUT .= '</select></td>';
993 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
996 if (isInString('h', $display) || (empty($display))) {
997 // Generate hour selection
998 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
999 for ($idx = 0; $idx <= 23; $idx++) {
1000 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1001 if ($idx == $h) $OUT .= ' selected="selected"';
1002 $OUT .= '>' . $idx . '</option>';
1004 $OUT .= '</select></td>';
1006 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1009 if (isInString('m', $display) || (empty($display))) {
1010 // Generate minute selection
1011 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1012 for ($idx = 0; $idx <= 59; $idx++) {
1013 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1014 if ($idx == $m) $OUT .= ' selected="selected"';
1015 $OUT .= '>' . $idx . '</option>';
1017 $OUT .= '</select></td>';
1019 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1022 if (isInString('s', $display) || (empty($display))) {
1023 // Generate second selection
1024 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1025 for ($idx = 0; $idx <= 59; $idx++) {
1026 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1027 if ($idx == $s) $OUT .= ' selected="selected"';
1028 $OUT .= '>' . $idx . '</option>';
1030 $OUT .= '</select></td>';
1032 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1039 // Return generated HTML code
1043 // Generate a list of administrative links to a given userid
1044 function generateMemberAdminActionLinks ($userid) {
1045 // Make sure userid is a number
1046 if ($userid != bigintval($userid)) {
1047 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1050 // Define all main targets
1051 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1054 $status = getFetchedUserData('userid', $userid, 'status');
1056 // Begin of navigation links
1059 foreach ($targetArray as $tar) {
1060 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1061 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1062 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1063 // Locked accounts shall be unlocked
1064 $OUT .= 'UNLOCK_USER';
1065 } elseif ($tar == 'del_user') {
1066 // @TODO Deprecate this thing
1067 $OUT .= 'DELETE_USER';
1069 // All other status is fine
1070 $OUT .= strtoupper($tar);
1072 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1073 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1074 // Locked accounts shall be unlocked
1075 $OUT .= 'UNLOCK_USER';
1076 } elseif ($tar == 'del_user') {
1077 // @TODO Deprecate this thing
1078 $OUT .= 'DELETE_USER';
1080 // All other status is fine
1081 $OUT .= strtoupper($tar);
1083 $OUT .= '--}</a></span>|';
1086 // Add special link, in case of the account is unconfirmed
1087 if ($status == 'UNCONFIRMED') {
1089 $OUT .= '<span class="admin_user_link"><a target="_blank" title="{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT_TITLE--}" href="{%url=confirm.php?hash=' . getFetchedUserData('userid', $userid, 'user_hash') . '%}">{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT--}</a></span>|';
1092 // Finish navigation link
1093 $OUT = substr($OUT, 0, -1) . ']';
1099 // Generate an email link
1100 function generateEmailLink ($email, $table = 'admins') {
1101 // Default email link (INSECURE! Spammer can read this by harvester programs)
1102 $EMAIL = 'mailto:' . $email;
1104 // Check for several extensions
1105 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1106 // Create email link for contacting admin in guest area
1107 $EMAIL = generateAdminEmailLink($email);
1108 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1109 // Create email link for contacting a member within admin area (or later in other areas, too?)
1110 $EMAIL = generateUserEmailLink($email);
1111 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1112 // Create email link to contact sponsor within admin area (or like the link above?)
1113 $EMAIL = generateSponsorEmailLink($email);
1116 // Shall I close the link when there is no admin?
1117 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1119 // Return email link
1123 // Output error messages in a fasioned way and die...
1124 function app_die ($F, $L, $message) {
1125 // Check if Script is already dieing and not let it kill itself another 1000 times
1126 if (isset($GLOBALS['app_died'])) {
1127 // Script tried to kill itself twice
1128 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1131 // Make sure, that the script realy realy diese here and now
1132 $GLOBALS['app_died'] = true;
1134 // Set content type as text/html
1135 setContentType('text/html');
1138 loadIncludeOnce('inc/header.php');
1140 // Rewrite message for output
1141 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1143 // Load the message template
1144 loadTemplate('app_die_message', false, $message);
1147 loadIncludeOnce('inc/footer.php');
1150 // Display parsing time and number of SQL queries in footer
1151 function displayParsingTime () {
1152 // Is the timer started?
1153 if (!isset($GLOBALS['startTime'])) {
1159 $endTime = microtime(true);
1161 // "Explode" both times
1162 $start = explode(' ', $GLOBALS['startTime']);
1163 $end = explode(' ', $endTime);
1164 $runTime = $end[0] - $start[0];
1170 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1172 'run_time' => $runTime,
1173 'sql_time' => (getConfig('sql_time') * 1000),
1176 // Load the template
1177 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1180 // Output a debug backtrace to the user
1181 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1182 // Is this already called?
1183 if (isset($GLOBALS[__FUNCTION__])) {
1185 print 'Message:' . $message . '<br />Backtrace:<pre>';
1186 debug_print_backtrace();
1190 // Set this function as called
1191 $GLOBALS[__FUNCTION__] = true;
1196 // Is the optional message set?
1197 if (!empty($message)) {
1199 $debug = sprintf("Note: %s<br />\n",
1203 // @TODO Add a little more infos here
1204 logDebugMessage($F, $L, strip_tags($message));
1208 $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>';
1209 $debug .= debug_get_printable_backtrace();
1211 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1212 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1214 // Send an email? (e.g. not wanted for evaluation errors)
1215 if (($sendEmail === true) && (!isInstallationPhase())) {
1218 'message' => trim($message),
1219 'backtrace' => trim(debug_get_mailable_backtrace())
1222 // Send email to webmaster
1223 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1227 app_die($F, $L, $debug);
1230 // Compile characters which are allowed in URLs
1231 function compileUriCode ($code, $simple = true) {
1232 // Compile constants
1233 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1235 // Compile QUOT and other non-HTML codes
1236 $code = str_replace('{DOT}', '.',
1237 str_replace('{SLASH}', '/',
1238 str_replace('{QUOT}', "'",
1239 str_replace('{DOLLAR}', '$',
1240 str_replace('{OPEN_ANCHOR}', '(',
1241 str_replace('{CLOSE_ANCHOR}', ')',
1242 str_replace('{OPEN_SQR}', '[',
1243 str_replace('{CLOSE_SQR}', ']',
1244 str_replace('{PER}', '%',
1248 // Return compiled code
1252 // Handle message codes from URL
1253 function handleCodeMessage () {
1254 if (isGetRequestParameterSet('code')) {
1255 // Default extension is 'unknown'
1258 // Is extension given?
1259 if (isGetRequestParameterSet('ext')) {
1260 $ext = getRequestParameter('ext');
1263 // Convert the 'code' parameter from URL to a human-readable message
1264 $message = getMessageFromErrorCode(getRequestParameter('code'));
1266 // Load message template
1267 loadTemplate('message', false, $message);
1271 // Generates a 'extension foo out-dated' message
1272 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1273 // Is the extension empty?
1274 if (empty($ext_name)) {
1275 // This should not happen
1276 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1280 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1282 // Is an admin logged in?
1284 // Then output admin message
1285 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1288 // Return prepared message
1292 // Generates a 'extension foo inactive' message
1293 function generateExtensionInactiveMessage ($ext_name) {
1294 // Is the extension empty?
1295 if (empty($ext_name)) {
1296 // This should not happen
1297 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1301 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1303 // Is an admin logged in?
1305 // Then output admin message
1306 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1309 // Return prepared message
1313 // Generates a 'extension foo not installed' message
1314 function generateExtensionNotInstalledMessage ($ext_name) {
1315 // Is the extension empty?
1316 if (empty($ext_name)) {
1317 // This should not happen
1318 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1322 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1324 // Is an admin logged in?
1326 // Then output admin message
1327 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1330 // Return prepared message
1334 // Generates a message depending on if the extension is not installed or not
1336 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1340 // Is the extension not installed or just deactivated?
1341 switch (isExtensionInstalled($ext_name)) {
1342 case true; // Deactivated!
1343 $message = generateExtensionInactiveMessage($ext_name);
1346 case false; // Not installed!
1347 $message = generateExtensionNotInstalledMessage($ext_name);
1350 default: // Should not happen!
1351 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1352 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1356 // Return the message
1360 // Print code with line numbers
1361 function linenumberCode ($code) {
1362 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1363 $count_lines = count($codeE);
1365 $r = 'Line | Code:<br />';
1366 foreach ($codeE as $line => $c) {
1367 $r .= '<div class="line"><span class="linenum">';
1368 if ($count_lines == 1) {
1371 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1376 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1379 return '<div class="code">' . $r . '</div>';
1382 // Determines the right page title
1383 function determinePageTitle () {
1384 // Config and database connection valid?
1385 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1389 // Title decoration enabled?
1390 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1392 // Do we have some extra title?
1393 if (isExtraTitleSet()) {
1395 $TITLE .= getExtraTitle() . ' by ';
1399 $TITLE .= getMainTitle();
1401 // Add title of module? (middle decoration will also be added!)
1402 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1403 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1406 // Add title from what file
1408 if (getModule() == 'login') $mode = 'member';
1409 elseif (getModule() == 'index') $mode = 'guest';
1410 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1412 // Add title decorations? (right)
1413 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1415 // Remember title in constant for the template
1416 $pageTitle = $TITLE;
1417 } elseif ((isInstalled()) && (isAdminRegistered())) {
1418 // Installed, admin registered but no ext-sql_patches
1419 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1420 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1421 // Installed but no admin registered
1422 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1423 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1424 // Installation mode
1425 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1427 // Configuration not found
1428 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1430 // Do not add the fatal message in installation mode
1431 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1435 return decodeEntities($pageTitle);
1438 // Checks wethere there is a cache file there. This function is cached.
1439 function isTemplateCached ($template) {
1440 // Do we have cached this result?
1441 if (!isset($GLOBALS['template_cache'][$template])) {
1443 $FQFN = generateCacheFqfn($template);
1446 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1450 return $GLOBALS['template_cache'][$template];
1453 // Flushes non-flushed template cache to disk
1454 function flushTemplateCache ($template, $eval) {
1455 // Is this cache flushed?
1456 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1458 $FQFN = generateCacheFqfn($template);
1461 writeToFile($FQFN, $eval, true);
1465 // Reads a template cache
1466 function readTemplateCache ($template) {
1468 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1469 // This should not happen
1470 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1474 if (!isset($GLOBALS['template_eval'][$template])) {
1476 $FQFN = generateCacheFqfn($template);
1479 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1483 return $GLOBALS['template_eval'][$template];
1486 // Escapes quotes (default is only double-quotes)
1487 function escapeQuotes ($str, $single = false) {
1488 // Should we escape all?
1489 if ($single === true) {
1490 // Escape all (including null)
1491 $str = addslashes($str);
1493 // Remove escaping of single quotes
1494 $str = str_replace("\\'", "'", $str);
1496 // Escape only double-quotes but prevent double-quoting
1497 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1500 // Return the escaped string
1504 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1505 function escapeJavaScriptQuotes ($str) {
1506 // Replace all double-quotes and secure back-ticks
1507 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1513 // Send out mails depending on the 'mod/modes' combination
1514 // @TODO Lame description for this function
1515 function sendModeMails ($mod, $modes) {
1517 $content = array ();
1520 if (fetchUserData(getMemberId())) {
1521 // Extract salt from cookie
1522 $salt = substr(getSession('u_hash'), 0, -40);
1524 // Now let's compare passwords
1525 $hash = encodeHashForCookie(getUserData('password'));
1527 // Does the hash match or should we change it?
1528 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1530 $content = getUserDataArray();
1532 // Clear/init the content variable
1533 $content['message'] = '';
1536 // @TODO Move this in a filter
1539 foreach ($modes as $mode) {
1541 case 'normal': break; // Do not add any special lines
1542 case 'email': // Email was changed!
1543 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1546 case 'password': // Password was changed
1547 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1551 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1552 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1557 if (isExtensionActive('country')) {
1558 // Replace code with description
1559 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1562 // Merge content with data from POST
1563 $content = merge_array($content, postRequestArray());
1566 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1568 if (isAdminNotificationEnabled()) {
1569 // The admin needs to be notified about a profile change
1570 $message_admin = 'admin_mydata_notify';
1571 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1574 $message_admin = '';
1578 // Set subject lines
1579 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1581 // Output success message
1582 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1585 default: // Unsupported module!
1586 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1587 $content['message'] = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1591 // Passwords mismatch
1592 $content['message'] = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1595 // Could not load profile
1596 $content['message'] = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1599 // Send email to user if required
1600 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1602 sendEmail($content['userid'], $sub_mem, $message);
1605 // Send only if no other error has occured
1606 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1608 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1609 } elseif (isAdminNotificationEnabled()) {
1610 // Cannot send mails to admin!
1611 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1614 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1618 displayMessage($content['message']);
1621 // Generates a 'selection box' from given array
1622 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1624 $OUT = '<select name="' . $name . '" size="1" class="form_select">
1625 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1627 // Walk through all options
1628 foreach ($options as $option) {
1629 // Add the <option> entry from ...
1630 if (empty($optionContent)) {
1632 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1634 // ... direct HTML code
1635 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1639 // Finish selection box
1640 $OUT .= '</select>';
1644 'selection_box' => $OUT,
1647 // Load template and return it
1648 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1651 // Prepares the header for HTML output
1652 function loadHtmlHeader () {
1654 // 1.) pre_page_header (mainly loads the page_header template and includes
1655 // meta description)
1656 runFilterChain('pre_page_header');
1658 // Here can be something be added, but normally one of the two filters
1659 // around this line should do the job for you.
1661 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1662 // to close the head-tag)
1663 // Include more header data here
1664 runFilterChain('post_page_header');
1667 // Adds page header and footer to output array element
1668 function addPageHeaderFooter () {
1672 // Add them all together. This is maybe to simple
1673 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1674 // Add page part if set
1675 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1678 // Transfer $OUT to 'output'
1679 $GLOBALS['output'] = $OUT;
1682 // Generates meta description for current module and 'what' value
1683 function generateMetaDescriptionCode () {
1684 // Only include from guest area and if sql_patches has correct version
1685 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1686 // Construct dynamic description
1687 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1689 // Output it directly
1690 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1694 unset($GLOBALS['ref_level']);
1697 // Generates an FQFN for template cache from the given template name
1698 function generateCacheFqfn ($template, $mode = 'html') {
1700 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1701 // Generate the FQFN
1702 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1703 "%s_compiled/%s/%s.tpl.cache",
1711 return $GLOBALS['template_cache_fqfn'][$template];
1714 // "Fixes" null or empty string to count of dashes
1715 function fixNullEmptyToDashes ($str, $num) {
1716 // Use str as default
1720 if ((is_null($str)) || (trim($str) == '')) {
1722 $return = str_repeat('-', $num);
1725 // Return final string
1729 // Translates the "pool type" into human-readable
1730 function translatePoolType ($type) {
1731 // Return "translation"
1732 return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1735 // Displays given message in admin_settings_saved template
1736 function displayMessage ($message, $return = false) {
1737 // Load the template
1738 return loadTemplate('admin_settings_saved', $return, $message);
1741 // Generates a selection box for (maybe) given gender
1742 function generateGenderSelectionBox ($selectedGender = '') {
1743 // Start the HTML code
1744 $out = '<select name="gender" size="1" class="form_select">';
1747 $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1750 $out .= '</select>';
1756 //-----------------------------------------------------------------------------
1757 // Template helper functions for EL
1758 //-----------------------------------------------------------------------------
1760 // Color-switch helper function
1761 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1763 if (!isset($GLOBALS['color_switch'][$template])) {
1765 initTemplateColorSwitch($template);
1766 } elseif ($clear === false) {
1767 // Switch color if called from loadTemplate()
1768 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1769 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1772 // Return CSS class name
1773 if ($return === true) {
1774 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1775 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1779 // Helper function for extension registration link
1780 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1781 // Default is all non-productive
1782 $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>';
1784 // Is the given extension non-productive?
1785 if (isExtensionProductive($ext_name)) {
1787 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1794 // Helper function to create bonus mail admin links
1795 function doTemplateAdminBonusMailLinks ($template, $dummy, $bonusId) {
1796 // Call the inner function
1797 return generateAdminMailLinks('bid', $bonusId);
1800 // Helper function to create member mail admin links
1801 function doTemplateAdminMemberMailLinks ($template, $dummy, $mailId) {
1802 // Call the inner function
1803 return generateAdminMailLinks('mid', $mailId);