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://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) {
73 // Call inner function
74 $str = fixNullEmptyToDashes($str, 3);
81 function initTemplateColorSwitch ($template) {
82 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
83 $GLOBALS['color_switch'][$template] = 2;
86 // "Getter" for color switch code
87 function getColorSwitchCode ($template) {
89 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
95 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
96 function outputHtml ($htmlCode, $newLine = true) {
98 if (!isset($GLOBALS['output'])) {
99 $GLOBALS['output'] = '';
102 // Do we have HTML-Code here?
103 if (!empty($htmlCode)) {
104 // Yes, so we handle it as you have configured
105 switch (getOutputMode()) {
107 // That's why you don't need any \n at the end of your HTML code... :-)
108 if (getPhpCaching() == 'on') {
109 // Output into PHP's internal buffer
110 outputRawCode($htmlCode);
112 // That's why you don't need any \n at the end of your HTML code... :-)
113 if ($newLine === true) print("\n");
115 // Render mode for old or lame servers...
116 $GLOBALS['output'] .= $htmlCode;
118 // That's why you don't need any \n at the end of your HTML code... :-)
119 if ($newLine === true) $GLOBALS['output'] .= "\n";
124 // If we are switching from render to direct output rendered code
125 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
127 // The same as above... ^
128 outputRawCode($htmlCode);
129 if ($newLine === true) print("\n");
133 // Huh, something goes wrong or maybe you have edited config.php ???
134 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
137 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
138 // Output cached HTML code
139 $GLOBALS['output'] = ob_get_contents();
141 // Clear output buffer for later output if output is found
142 if (!empty($GLOBALS['output'])) {
146 // Send all HTTP headers
149 // Compile and run finished rendered HTML code
150 compileFinalOutput();
152 // Output code here, DO NOT REMOVE! ;-)
153 outputRawCode($GLOBALS['output']);
154 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
155 // Send all HTTP headers
158 // Compile and run finished rendered HTML code
159 compileFinalOutput();
161 // Output code here, DO NOT REMOVE! ;-)
162 outputRawCode($GLOBALS['output']);
164 // And flush all headers
169 // Compiles the final output
170 function compileFinalOutput () {
171 // Add page header and footer
172 addPageHeaderFooter();
174 // Do the final compilation
175 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
177 // Extension 'rewrite' installed?
178 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
179 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
184 * @TODO On some pages this is buggy
185 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
186 // Compress it for HTTP gzip
187 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9);
190 sendHeader('Content-Encoding: gzip');
191 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
192 // Compress it for HTTP deflate
193 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
196 sendHeader('Content-Encoding: deflate');
201 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
207 // Main compilation loop
208 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
209 // Insert comments? (Only valid with HTML templates, of course)
210 enableTemplateHtml($insertComments);
216 while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== false)) && ($count < 7)) {
217 // Init common variables
222 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
223 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
224 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
226 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
227 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
229 // Was that eval okay?
230 if (empty($newContent)) {
231 // Something went wrong!
232 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
238 // Compile the final code if insertComments is true
239 if ($insertComments == true) {
240 // ... because SQL queries shall keep OPEN_CONFIG and such in
241 $code = compileRawCode($code);
248 // Add debugging data in HTML code, if mode is enabled
249 if ((isDebugModeEnabled()) && ($insertComments === true)) {
251 $code .= '<!-- Total compilation loop=' . $count . ' //-->';
254 // Return the compiled code
258 // Output the raw HTML code
259 function outputRawCode ($htmlCode) {
260 // Output stripped HTML code to avoid broken JavaScript code, etc.
261 print(str_replace('{BACK}', "\\", $htmlCode));
263 // Flush the output if only getPhpCaching() is not 'on'
264 if (getPhpCaching() != 'on') {
270 // Load a template file and return it's content (only it's name; do not use ' or ")
271 function loadTemplate ($template, $return = false, $content = array(), $compileCode = true) {
272 if (!is_bool($return)) {
273 // @TODO Remove this sanity-check if all is fine
274 debug_report_bug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
275 } elseif (!is_string($template)) {
276 // $template has to be string
277 debug_report_bug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
280 // Set current template
281 $GLOBALS['current_template'] = $template;
284 if ((!isDebuggingTemplateCache()) && (isTemplateCached($template))) {
285 // Evaluate the cache
286 eval(readTemplateCache($template));
287 } elseif (!isset($GLOBALS['template_eval'][$template])) {
288 // Make all template names lowercase
289 $template = strtolower($template);
295 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
296 $extraPath = detectExtraTemplatePath($template);
299 $FQFN = $basePath . $extraPath . $template . '.tpl';
301 // Does the special template exists?
302 if (!isFileReadable($FQFN)) {
303 // Reset to default template
304 $FQFN = $basePath . $template . '.tpl';
307 // Now does the final template exists?
308 if (isFileReadable($FQFN)) {
309 // Count the template load
310 incrementConfigEntry('num_templates');
312 // The local file does exists so we load it. :)
313 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
315 // Do we have to compile the code?
317 if ((isInString('$', $GLOBALS['tpl_content'][$template])) || (isInString('{--', $GLOBALS['tpl_content'][$template])) || (isInString('{?', $GLOBALS['tpl_content'][$template])) || (isInString('{%', $GLOBALS['tpl_content'][$template]))) {
318 // Normal HTML output?
319 if (isHtmlOutputMode()) {
320 // Add surrounding HTML comments to help finding bugs faster
321 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
323 // Prepare eval() command
324 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
325 } elseif (substr($template, 0, 3) == 'js_') {
326 // JavaScripts don't like entities and timings
327 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
329 // Prepare eval() command, other output doesn't like entities, maybe
330 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
332 } elseif (isHtmlOutputMode()) {
333 // Add surrounding HTML comments to help finding bugs faster
334 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
335 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
338 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
340 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
341 // Only admins shall see this warning or when installation mode is active
342 $ret = '<div class="para">
343 <span class="notice">{--TEMPLATE_404--}</span>
349 {--TEMPLATE_CONTENT--}:
350 <pre>' . print_r($content, true) . '</pre>
354 $GLOBALS['template_eval'][$template] = '404';
359 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
361 eval($GLOBALS['template_eval'][$template]);
364 // Do we have some content to output or return?
366 // Not empty so let's put it out! ;)
367 if ($return === true) {
368 // Return the HTML code
374 } elseif (isDebugModeEnabled()) {
375 // Warning, empty output!
376 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
380 // Detects the extra template path from given template name
381 function detectExtraTemplatePath ($template) {
386 if (!isset($GLOBALS['extra_path'][$template])) {
387 // Check for admin/guest/member/etc. templates
388 if (substr($template, 0, 6) == 'admin_') {
389 // Admin template found
390 $extraPath = 'admin/';
391 } elseif (substr($template, 0, 6) == 'guest_') {
392 // Guest template found
393 $extraPath = 'guest/';
394 } elseif (substr($template, 0, 7) == 'member_') {
395 // Member template found
396 $extraPath = 'member/';
397 } elseif (substr($template, 0, 7) == 'select_') {
398 // Selection template found
399 $extraPath = 'select/';
400 } elseif (substr($template, 0, 8) == 'install_') {
401 // Installation template found
402 $extraPath = 'install/';
403 } elseif (substr($template, 0, 4) == 'ext_') {
404 // Extension template found
406 } elseif (substr($template, 0, 3) == 'la_') {
407 // 'Logical-area' template found
409 } elseif (substr($template, 0, 3) == 'js_') {
410 // JavaScript template found
412 } elseif (substr($template, 0, 5) == 'menu_') {
413 // Menu template found
414 $extraPath = 'menu/';
416 // Test for extension
417 $test = substr($template, 0, strpos($template, '_'));
419 // Probe for valid extension name
420 if (isExtensionNameValid($test)) {
421 // Set extra path to extension's name
422 $extraPath = $test . '/';
427 $GLOBALS['extra_path'][$template] = $extraPath;
431 return $GLOBALS['extra_path'][$template];
434 // Loads an email template and compiles it
435 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = true) {
436 // Make sure all template names are lowercase!
437 $template = strtolower($template);
439 // Is content an array?
440 if (is_array($content)) {
441 // Add expiration to array
442 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
443 // Will never expire!
444 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
445 } elseif (isConfigEntrySet('auto_purge')) {
446 // Create nice date string
447 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
450 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UID=' . $userid . ',template=' . $template . ',content[]=' . gettype($content));
456 if ((isValidUserId($userid)) && (is_array($content))) {
457 // If nickname extension is installed, fetch nickname as well
458 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - NICKNAME!');
461 fetchUserData($userid, 'nickname');
462 } elseif (isNicknameUsed($userid)) {
463 // Non-number characters entered but no ext-nickname found
464 debug_report_bug(__FUNCTION__, __LINE__, 'userid=' . $userid . ': is no id number and ext-nickname is gone.');
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - USERID!');
468 fetchUserData($userid);
471 // Merge data if valid
472 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - PRE!');
473 if ((isUserDataValid()) && ($loadUserData === true)) {
475 $content = merge_array($content, getUserDataArray());
477 // But we don't like hashed passwords be mailed
478 unset($content['password']);
481 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - AFTER!');
485 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
488 $extraPath = detectExtraTemplatePath($template);
490 // Generate full FQFN
491 $FQFN = $basePath . $extraPath . $template . '.tpl';
493 // Does the special template exists?
494 if (!isFileReadable($FQFN)) {
495 // Reset to default template
496 $FQFN = $basePath . $template . '.tpl';
499 // Now does the final template exists?
501 if (isFileReadable($FQFN)) {
502 // The local file does exists so we load it. :)
503 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
506 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
507 eval($GLOBALS['tpl_content'][$template]);
508 } elseif (!empty($template)) {
509 // Template file not found
510 $newContent = '<div class="para">
511 {--TEMPLATE_404--}: ' . $template . '
514 {--TEMPLATE_CONTENT--}:
515 <pre>' . print_r($content, true) . '</pre>
518 // Debug mode not active? Then remove the HTML tags
519 if (!isDebugModeEnabled()) {
521 $newContent = secureString($newContent);
524 // No template name supplied!
525 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
528 // Is there some content?
529 if (empty($newContent)) {
531 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
533 // Add last error if the required function exists
534 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
537 // Remove content and data
544 // "Getter" for menu CSS classes, mainly used in templates
545 function getMenuCssClasses ($data) {
546 // $data needs to be converted into an array
547 $content = explode('|', $data);
549 // Non-existent index 2 will happen in menu blocks
550 if (!isset($content[2])) {
554 // Re-construct the array: 0=visible,1=locked,2=prefix
555 $content['visible'] = $content[0];
556 $content['locked'] = $content[1];
558 // Call our "translator" function
559 $content = translateMenuVisibleLocked($content, $content[2]);
561 // Return CSS classes
562 return ($content['visible_css'] . ' ' . $content['locked_css']);
565 // Generate XHTML code for the CAPTCHA
566 function generateCaptchaCode ($code, $type, $type, $userid) {
567 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $type . '&mode=img&code=' . $code . '%}" />';
570 // Compiles the given HTML/mail code
571 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
572 // Is the code a string or should we not compile?
573 if ((!is_string($code)) || ($compileCode === false)) {
574 // Silently return it
579 $startCompile = microtime(true);
582 $code = compileRawCode($code, $simple, $constants, $full);
585 $compiled = microtime(true);
587 // Add timing if enabled
588 if (isTemplateHtml()) {
589 // Add timing, this should be disabled in
590 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
593 // Return compiled code
598 // @TODO $simple/$constants are deprecated
599 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
600 // Is the code a string or shall we not compile?
601 if ((!is_string($code)) || ($compileCode === false)) {
602 // Silently return it
606 // Init replacement-array with smaller set of security characters
607 $secChars = $GLOBALS['url_chars'];
609 // Select full set of chars to replace when we e.g. want to compile URLs
610 if ($full === true) {
611 $secChars = $GLOBALS['security_chars'];
614 // Compile more through a filter
615 $code = runFilterChain('compile_code', $code);
617 // Compile message strings
618 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
620 // Compile QUOT and other non-HTML codes
621 $code = str_replace($secChars['to'], $secChars['from'], $code);
623 // Find $content[bla][blub] entries
624 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
626 // Are some matches found?
627 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
628 // Replace all matches
629 $matchesFound = array();
630 foreach ($matches[0] as $key => $match) {
631 // Fuzzy look has failed by default
634 // Fuzzy look on match if already found
635 foreach ($matchesFound as $found => $set) {
637 $test = substr($found, 0, strlen($match));
639 // Does this entry exist?
640 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
641 if ($test == $match) {
643 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
650 if ($fuzzyFound === true) {
654 // Take all string elements
655 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
656 // Replace it in the code
657 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
658 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
659 $code = str_replace($match, '".' . $newMatch . '."', $code);
660 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
661 $matchesFound[$match] = true;
662 } elseif (!isset($matchesFound[$match])) {
664 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
665 $code = str_replace($match, '".' . $match . '."', $code);
666 $matchesFound[$match] = 1;
668 // Everthing else should be a least logged
669 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
679 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
683 // This is a yes/no selection only!
684 if ($id > 0) $prefix .= '[' . $id . ']';
685 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
687 // Begin with regular selection box here
688 if (!empty($prefix)) $prefix .= '_';
690 if ($id > 0) $type2 .= '[' . $id . ']';
691 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
696 for ($idx = 1; $idx < 32; $idx++) {
697 $OUT .= '<option value="' . $idx . '"';
698 if ($default == $idx) $OUT .= ' selected="selected"';
699 $OUT .= '>' . $idx . '</option>';
703 case 'month': // Month
704 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
705 $OUT .= '<option value="' . $idx . '"';
706 if ($default == $idx) $OUT .= ' selected="selected"';
707 $OUT .= '>' . $descr . '</option>';
715 // Use configured min age or fixed?
716 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
718 $startYear = $year - getConfig('min_age');
721 $startYear = $year - 16;
724 // Calculate earliest year (100 years old people can still enter Internet???)
725 $minYear = $year - 100;
727 // Check if the default value is larger than minimum and bigger than actual year
728 if (($default > $minYear) && ($default >= $year)) {
729 for ($idx = $year; $idx < ($year + 11); $idx++) {
730 $OUT .= '<option value="' . $idx . '"';
731 if ($default == $idx) $OUT .= ' selected="selected"';
732 $OUT .= '>' . $idx . '</option>';
734 } elseif ($default == -1) {
735 // Current year minus 1
736 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
737 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
740 // Get current year and subtract the configured minimum age
741 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
742 // Calculate earliest year depending on extension version
743 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
744 // Use configured minimum age
745 $year = getYear() - getConfig('min_age');
747 // Use fixed 16 years age
748 $year = getYear() - 16;
751 // Construct year selection list
752 for ($idx = $minYear; $idx <= $year; $idx++) {
753 $OUT .= '<option value="' . $idx . '"';
754 if ($default == $idx) $OUT .= ' selected="selected"';
755 $OUT .= '>' . $idx . '</option>';
762 for ($idx = 0; $idx < 60; $idx+=5) {
763 if (strlen($idx) == 1) $idx = '0' . $idx;
764 $OUT .= '<option value="' . $idx . '"';
765 if ($default == $idx) $OUT .= ' selected="selected"';
766 $OUT .= '>' . $idx . '</option>';
771 for ($idx = 0; $idx < 24; $idx++) {
772 if (strlen($idx) == 1) $idx = '0' . $idx;
773 $OUT .= '<option value="' . $idx . '"';
774 if ($default == $idx) $OUT .= ' selected="selected"';
775 $OUT .= '>' . $idx . '</option>';
780 $OUT .= '<option value="Y"';
781 if ($default == 'Y') $OUT .= ' selected="selected"';
782 $OUT .= '>{--YES--}</option><option value="N"';
783 if ($default != 'Y') $OUT .= ' selected="selected"';
784 $OUT .= '>{--NO--}</option>';
791 // Insert the code in $img_code into jpeg or PNG image
792 function generateImageOrCode ($img_code, $headerSent = true) {
793 // Is the code size oversized or shouldn't we display it?
794 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
795 // Stop execution of function here because of over-sized code length
796 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
797 } elseif ($headerSent === false) {
798 // Return an HTML code here
799 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
803 $img = sprintf("%s/theme/%s/images/code_bg.%s",
810 if (isFileReadable($img)) {
812 switch (getImgType()) {
813 case 'jpg': // Okay, load image and hide all errors
814 $image = imagecreatefromjpeg($img);
817 case 'png': // Okay, load image and hide all errors
818 $image = imagecreatefrompng($img);
822 // Silently log the error
823 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
827 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
828 $text_color = imagecolorallocate($image, 0, 0, 0);
830 // Insert code into image
831 imagestring($image, 5, 14, 2, $img_code, $text_color);
834 setContentType('image/' . getImgType());
836 // Output image with matching image factory
837 switch (getImgType()) {
838 case 'jpg': imagejpeg($image); break;
839 case 'png': imagepng($image); break;
842 // Remove image from memory
843 imagedestroy($image);
846 // Create selection box or array of splitted timestamp
847 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = false) {
848 // Do not continue if ONE_DAY is absend
849 if (!isConfigEntrySet('ONE_DAY')) {
851 debug_report_bug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
854 // Calculate 2-seconds timestamp
855 $stamp = round($timestamp);
856 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
858 // Do we have a leap year?
860 $TEST = getYear() / 4;
862 $M2 = getMonth(time() + $timestamp);
864 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
865 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
866 $SWITCH = getOneDay();
869 // First of all years...
870 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
871 //* DEBUG: */ debugOutput('Y=' . $Y);
873 $M = abs(floor($timestamp / 2628000 - $Y * 12));
874 //* DEBUG: */ debugOutput('M=' . $M);
876 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
877 //* DEBUG: */ debugOutput('W=' . $W);
879 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
880 //* DEBUG: */ debugOutput('D=' . $D);
882 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
883 //* DEBUG: */ debugOutput('h=' . $h);
885 $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));
886 //* DEBUG: */ debugOutput('m=' . $m);
887 // And at last seconds...
888 $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));
889 //* DEBUG: */ debugOutput('s=' . $s);
891 // Is seconds zero and time is < 60 seconds?
892 if (($s == '0') && ($timestamp < 60)) {
894 $s = round($timestamp);
898 // Now we convert them in seconds...
900 if ($asArray === true) {
901 // Just put all data in an array for later use
913 $OUT = '<div align="' . $align . '">';
914 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
917 if (isInString('Y', $display) || (empty($display))) {
918 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
921 if (isInString('M', $display) || (empty($display))) {
922 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
925 if (isInString('W', $display) || (empty($display))) {
926 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
929 if (isInString('D', $display) || (empty($display))) {
930 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
933 if (isInString('h', $display) || (empty($display))) {
934 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
937 if (isInString('m', $display) || (empty($display))) {
938 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
941 if (isInString('s', $display) || (empty($display))) {
942 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
948 if (isInString('Y', $display) || (empty($display))) {
949 // Generate year selection
950 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
951 for ($idx = 0; $idx <= 10; $idx++) {
952 $OUT .= '<option class="mini_select" value="' . $idx . '"';
953 if ($idx == $Y) $OUT .= ' selected="selected"';
954 $OUT .= '>' . $idx . '</option>';
956 $OUT .= '</select></td>';
958 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
961 if (isInString('M', $display) || (empty($display))) {
962 // Generate month selection
963 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
964 for ($idx = 0; $idx <= 11; $idx++) {
965 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
966 if ($idx == $M) $OUT .= ' selected="selected"';
967 $OUT .= '>' . $idx . '</option>';
969 $OUT .= '</select></td>';
971 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
974 if (isInString('W', $display) || (empty($display))) {
975 // Generate week selection
976 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
977 for ($idx = 0; $idx <= 4; $idx++) {
978 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
979 if ($idx == $W) $OUT .= ' selected="selected"';
980 $OUT .= '>' . $idx . '</option>';
982 $OUT .= '</select></td>';
984 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
987 if (isInString('D', $display) || (empty($display))) {
988 // Generate day selection
989 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
990 for ($idx = 0; $idx <= 31; $idx++) {
991 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
992 if ($idx == $D) $OUT .= ' selected="selected"';
993 $OUT .= '>' . $idx . '</option>';
995 $OUT .= '</select></td>';
997 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1000 if (isInString('h', $display) || (empty($display))) {
1001 // Generate hour selection
1002 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1003 for ($idx = 0; $idx <= 23; $idx++) {
1004 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1005 if ($idx == $h) $OUT .= ' selected="selected"';
1006 $OUT .= '>' . $idx . '</option>';
1008 $OUT .= '</select></td>';
1010 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1013 if (isInString('m', $display) || (empty($display))) {
1014 // Generate minute selection
1015 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1016 for ($idx = 0; $idx <= 59; $idx++) {
1017 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1018 if ($idx == $m) $OUT .= ' selected="selected"';
1019 $OUT .= '>' . $idx . '</option>';
1021 $OUT .= '</select></td>';
1023 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1026 if (isInString('s', $display) || (empty($display))) {
1027 // Generate second selection
1028 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1029 for ($idx = 0; $idx <= 59; $idx++) {
1030 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1031 if ($idx == $s) $OUT .= ' selected="selected"';
1032 $OUT .= '>' . $idx . '</option>';
1034 $OUT .= '</select></td>';
1036 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1043 // Return generated HTML code
1047 // Generate a list of administrative links to a given userid
1048 function generateMemberAdminActionLinks ($userid) {
1049 // Make sure userid is a number
1050 if ($userid != bigintval($userid)) {
1051 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1054 // Define all main targets
1055 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1058 $status = getFetchedUserData('userid', $userid, 'status');
1060 // Begin of navigation links
1063 foreach ($targetArray as $tar) {
1064 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1065 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1066 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1067 // Locked accounts shall be unlocked
1068 $OUT .= 'UNLOCK_USER';
1069 } elseif ($tar == 'del_user') {
1070 // @TODO Deprecate this thing
1071 $OUT .= 'DELETE_USER';
1073 // All other status is fine
1074 $OUT .= strtoupper($tar);
1076 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1077 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1078 // Locked accounts shall be unlocked
1079 $OUT .= 'UNLOCK_USER';
1080 } elseif ($tar == 'del_user') {
1081 // @TODO Deprecate this thing
1082 $OUT .= 'DELETE_USER';
1084 // All other status is fine
1085 $OUT .= strtoupper($tar);
1087 $OUT .= '--}</a></span>|';
1090 // Add special link, in case of the account is unconfirmed
1091 if ($status == 'UNCONFIRMED') {
1093 $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>|';
1096 // Finish navigation link
1097 $OUT = substr($OUT, 0, -1) . ']';
1103 // Generate an email link
1104 function generateEmailLink ($email, $table = 'admins') {
1105 // Default email link (INSECURE! Spammer can read this by harvester programs)
1106 $EMAIL = 'mailto:' . $email;
1108 // Check for several extensions
1109 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1110 // Create email link for contacting admin in guest area
1111 $EMAIL = generateAdminEmailLink($email);
1112 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1113 // Create email link for contacting a member within admin area (or later in other areas, too?)
1114 $EMAIL = generateUserEmailLink($email);
1115 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1116 // Create email link to contact sponsor within admin area (or like the link above?)
1117 $EMAIL = generateSponsorEmailLink($email);
1120 // Return email link
1124 // Output error messages in a fasioned way and die...
1125 function app_die ($F, $L, $message) {
1126 // Check if Script is already dieing and not let it kill itself another 1000 times
1127 if (isset($GLOBALS['app_died'])) {
1128 // Script tried to kill itself twice
1129 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1132 // Make sure, that the script realy realy diese here and now
1133 $GLOBALS['app_died'] = true;
1135 // Set content type as text/html
1136 setContentType('text/html');
1139 loadIncludeOnce('inc/header.php');
1141 // Rewrite message for output
1142 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1144 // Load the message template
1145 loadTemplate('app_die_message', false, $message);
1148 loadIncludeOnce('inc/footer.php');
1151 // Display parsing time and number of SQL queries in footer
1152 function displayParsingTime () {
1153 // Is the timer started?
1154 if (!isset($GLOBALS['startTime'])) {
1160 $endTime = microtime(true);
1162 // "Explode" both times
1163 $start = explode(' ', $GLOBALS['startTime']);
1164 $end = explode(' ', $endTime);
1165 $runTime = $end[0] - $start[0];
1171 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1173 'run_time' => $runTime,
1174 'sql_time' => (getConfig('sql_time') * 1000),
1177 // Load the template
1178 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1181 // Output a debug backtrace to the user
1182 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1183 // Is this already called?
1184 if (isset($GLOBALS[__FUNCTION__])) {
1186 print 'Message:' . $message . '<br />Backtrace:<pre>';
1187 debug_print_backtrace();
1191 // Set this function as called
1192 $GLOBALS[__FUNCTION__] = true;
1197 // Is the optional message set?
1198 if (!empty($message)) {
1200 $debug = sprintf("Note: %s<br />\n",
1204 // @TODO Add a little more infos here
1205 logDebugMessage($F, $L, strip_tags($message));
1209 $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>';
1210 $debug .= debug_get_printable_backtrace();
1212 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1213 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1215 // Send an email? (e.g. not wanted for evaluation errors)
1216 if (($sendEmail === true) && (!isInstallationPhase())) {
1219 'message' => trim($message),
1220 'backtrace' => trim(debug_get_mailable_backtrace())
1223 // Send email to webmaster
1224 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1228 app_die($F, $L, $debug);
1231 // Compile characters which are allowed in URLs
1232 function compileUriCode ($code, $simple = true) {
1233 // Compile constants
1234 if ($simple === false) {
1235 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1238 // Compile QUOT and other non-HTML codes
1239 $code = str_replace('{DOT}', '.',
1240 str_replace('{SLASH}', '/',
1241 str_replace('{QUOT}', "'",
1242 str_replace('{DOLLAR}', '$',
1243 str_replace('{OPEN_ANCHOR}', '(',
1244 str_replace('{CLOSE_ANCHOR}', ')',
1245 str_replace('{OPEN_SQR}', '[',
1246 str_replace('{CLOSE_SQR}', ']',
1247 str_replace('{PER}', '%',
1251 // Return compiled code
1255 // Handle message codes from URL
1256 function handleCodeMessage () {
1258 if (isGetRequestElementSet('code')) {
1259 // Default extension is 'unknown'
1262 // Is extension given?
1263 if (isGetRequestElementSet('ext')) {
1264 $ext = getRequestElement('ext');
1267 // Convert the 'code' parameter from URL to a human-readable message
1268 $message = getMessageFromErrorCode(getRequestElement('code'));
1270 // Load message template
1271 loadTemplate('message', false, $message);
1275 // Generates a 'extension foo out-dated' message
1276 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
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 = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1286 // Is an admin logged in?
1288 // Then output admin message
1289 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1292 // Return prepared message
1296 // Generates a 'extension foo inactive' message
1297 function generateExtensionInactiveMessage ($ext_name) {
1298 // Is the extension empty?
1299 if (empty($ext_name)) {
1300 // This should not happen
1301 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1305 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1307 // Is an admin logged in?
1309 // Then output admin message
1310 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1313 // Return prepared message
1317 // Generates a 'extension foo not installed' message
1318 function generateExtensionNotInstalledMessage ($ext_name) {
1319 // Is the extension empty?
1320 if (empty($ext_name)) {
1321 // This should not happen
1322 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1326 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1328 // Is an admin logged in?
1330 // Then output admin message
1331 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1334 // Return prepared message
1338 // Generates a message depending on if the extension is not installed or not
1340 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1344 // Is the extension not installed or just deactivated?
1345 switch (isExtensionInstalled($ext_name)) {
1346 case true; // Deactivated!
1347 $message = generateExtensionInactiveMessage($ext_name);
1350 case false; // Not installed!
1351 $message = generateExtensionNotInstalledMessage($ext_name);
1354 default: // Should not happen!
1355 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1356 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1360 // Return the message
1364 // Print code with line numbers
1365 function linenumberCode ($code) {
1366 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1367 $count_lines = count($codeE);
1369 $r = 'Line | Code:<br />';
1370 foreach ($codeE as $line => $c) {
1371 $r .= '<div class="line"><span class="linenum">';
1372 if ($count_lines == 1) {
1375 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1380 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1383 return '<div class="code">' . $r . '</div>';
1386 // Determines the right page title
1387 function determinePageTitle () {
1391 // Config and database connection valid?
1392 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1393 // Title decoration enabled?
1394 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) {
1395 $pageTitle .= '{%config,trim=title_left%} ';
1398 // Do we have some extra title?
1399 if (isExtraTitleSet()) {
1401 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1405 $pageTitle .= '{?MAIN_TITLE?}';
1407 // Add title of module? (middle decoration will also be added!)
1408 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1409 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1412 // Add title from what file
1414 if (getModule() == 'login') {
1416 } elseif (getModule() == 'index') {
1418 } elseif (getModule() == 'admin') {
1420 } elseif (getModule() == 'sponsor') {
1424 // Add middle part (always in admin area!)
1425 if ((!empty($mode)) && ((isWhatTitleEnabled()) || ($mode == 'admin'))) {
1426 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($mode, getWhat());
1429 // Add title decorations? (right)
1430 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) {
1431 $pageTitle .= ' {%config,trim=title_right%}';
1433 } elseif ((isInstalled()) && (isAdminRegistered())) {
1434 // Installed, admin registered but no ext-sql_patches
1435 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1436 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1437 // Installed but no admin registered
1438 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1439 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1440 // Installation mode
1441 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1443 // Configuration not found
1444 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1446 // Do not add the fatal message in installation mode
1447 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1448 // Please report this
1449 debug_report_bug(__FUNCTION__, __LINE__, 'No configuration data found!');
1454 return decodeEntities($pageTitle);
1457 // Checks wethere there is a cache file there. This function is cached.
1458 function isTemplateCached ($template) {
1459 // Do we have cached this result?
1460 if (!isset($GLOBALS['template_cache'][$template])) {
1462 $FQFN = generateCacheFqfn($template);
1465 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1469 return $GLOBALS['template_cache'][$template];
1472 // Flushes non-flushed template cache to disk
1473 function flushTemplateCache ($template, $eval) {
1474 // Is this cache flushed?
1475 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1477 $FQFN = generateCacheFqfn($template);
1480 writeToFile($FQFN, $eval, true);
1484 // Reads a template cache
1485 function readTemplateCache ($template) {
1487 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1488 // This should not happen
1489 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1493 if (!isset($GLOBALS['template_eval'][$template])) {
1495 $FQFN = generateCacheFqfn($template);
1498 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1502 return $GLOBALS['template_eval'][$template];
1505 // Escapes quotes (default is only double-quotes)
1506 function escapeQuotes ($str, $single = false) {
1507 // Should we escape all?
1508 if ($single === true) {
1509 // Escape all (including null)
1510 $str = addslashes($str);
1512 // Remove escaping of single quotes
1513 $str = str_replace("\\'", "'", $str);
1515 // Escape only double-quotes but prevent double-quoting
1516 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1519 // Return the escaped string
1523 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1524 function escapeJavaScriptQuotes ($str) {
1525 // Replace all double-quotes and secure back-ticks
1526 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1532 // Send out mails depending on the 'mod/modes' combination
1533 // @TODO Lame description for this function
1534 function sendModeMails ($mod, $modes) {
1536 $content = array ();
1539 if (fetchUserData(getMemberId())) {
1540 // Extract salt from cookie
1541 $salt = substr(getSession('u_hash'), 0, -40);
1543 // Now let's compare passwords
1544 $hash = encodeHashForCookie(getUserData('password'));
1546 // Does the hash match or should we change it?
1547 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
1549 $content = getUserDataArray();
1551 // Clear/init the content variable
1552 $content['message'] = '';
1555 // @TODO Move this in a filter
1558 foreach ($modes as $mode) {
1560 case 'normal': break; // Do not add any special lines
1561 case 'email': // Email was changed!
1562 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . "\n";
1565 case 'password': // Password was changed
1566 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1570 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1571 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1576 if (isExtensionActive('country')) {
1577 // Replace code with description
1578 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1581 // Merge content with data from POST
1582 $content = merge_array($content, postRequestArray());
1585 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1587 if (isAdminNotificationEnabled()) {
1588 // The admin needs to be notified about a profile change
1589 $message_admin = 'admin_mydata_notify';
1590 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1593 $message_admin = '';
1597 // Set subject lines
1598 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1600 // Output success message
1601 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1604 default: // Unsupported module!
1605 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1606 $content['message'] = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1610 // Passwords mismatch
1611 $content['message'] = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1614 // Could not load profile
1615 $content['message'] = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1618 // Send email to user if required
1619 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1621 sendEmail($content['userid'], $sub_mem, $message);
1624 // Send only if no other error has occured
1625 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1627 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1628 } elseif (isAdminNotificationEnabled()) {
1629 // Cannot send mails to admin!
1630 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1633 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1637 displayMessage($content['message']);
1640 // Generates a 'selection box' from given array
1641 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1643 $OUT = '<select name="' . $name . '" size="1" class="form_select">
1644 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1646 // Walk through all options
1647 foreach ($options as $option) {
1648 // Add the <option> entry from ...
1649 if (empty($optionContent)) {
1651 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1653 // ... direct HTML code
1654 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1658 // Finish selection box
1659 $OUT .= '</select>';
1663 'selection_box' => $OUT,
1666 // Load template and return it
1667 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1670 // Prepares the header for HTML output
1671 function loadHtmlHeader () {
1673 // 1.) pre_page_header (mainly loads the page_header template and includes
1674 // meta description)
1675 runFilterChain('pre_page_header');
1677 // Here can be something be added, but normally one of the two filters
1678 // around this line should do the job for you.
1680 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1681 // to close the head-tag)
1682 // Include more header data here
1683 runFilterChain('post_page_header');
1686 // Adds page header and footer to output array element
1687 function addPageHeaderFooter () {
1691 // Add them all together. This is maybe to simple
1692 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1693 // Add page part if set
1694 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1697 // Transfer $OUT to 'output'
1698 $GLOBALS['output'] = $OUT;
1701 // Generates meta description for current module and 'what' value
1702 function generateMetaDescriptionCode () {
1703 // Only include from guest area and if sql_patches has correct version
1704 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1705 // Construct dynamic description
1706 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1708 // Output it directly
1709 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1712 // Initialize referral system
1713 initReferralSystem();
1716 // Generates an FQFN for template cache from the given template name
1717 function generateCacheFqfn ($template, $mode = 'html') {
1719 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1720 // Generate the FQFN
1721 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1722 "%s_compiled/%s/%s.tpl.cache",
1730 return $GLOBALS['template_cache_fqfn'][$template];
1733 // "Fixes" null or empty string to count of dashes
1734 function fixNullEmptyToDashes ($str, $num) {
1735 // Use str as default
1739 if ((is_null($str)) || (trim($str) == '')) {
1741 $return = str_repeat('-', $num);
1744 // Return final string
1748 // Translates the "pool type" into human-readable
1749 function translatePoolType ($type) {
1750 // Return "translation"
1751 return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1754 // Displays given message in admin_settings_saved template
1755 function displayMessage ($message, $return = false) {
1756 // Load the template
1757 return loadTemplate('admin_settings_saved', $return, $message);
1760 // Generates a selection box for (maybe) given gender
1761 function generateGenderSelectionBox ($selectedGender = '') {
1762 // Start the HTML code
1763 $out = '<select name="gender" size="1" class="form_select">';
1766 $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1769 $out .= '</select>';
1775 //-----------------------------------------------------------------------------
1776 // Template helper functions for EL code
1777 //-----------------------------------------------------------------------------
1779 // Color-switch helper function
1780 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1782 if (!isset($GLOBALS['color_switch'][$template])) {
1784 initTemplateColorSwitch($template);
1785 } elseif ($clear === false) {
1786 // Switch color if called from loadTemplate()
1787 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1788 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1791 // Return CSS class name
1792 if ($return === true) {
1793 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1794 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1798 // Helper function for extension registration link
1799 function doTemplateExtensionRegistrationLink ($template, $clear, $ext_name) {
1800 // Default is all non-productive
1801 $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>';
1803 // Is the given extension non-productive?
1804 if (isExtensionProductive($ext_name)) {
1806 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1813 // Helper function to create bonus mail admin links
1814 function doTemplateAdminBonusMailLinks ($template, $clear, $bonusId) {
1815 // Call the inner function
1816 return generateAdminMailLinks('bid', $bonusId);
1819 // Helper function to create member mail admin links
1820 function doTemplateAdminMemberMailLinks ($template, $clear, $mailId) {
1821 // Call the inner function
1822 return generateAdminMailLinks('mid', $mailId);
1825 // Helper function to create a selection box for YES/NO configuration entries
1826 function doTemplateConfigurationYesNoSelectionBox ($template, $clear, $configEntry) {
1827 // Default is a "missing entry" warning
1828 $OUT = '<em style="cursor:help" class="notice" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</em>';
1830 // Generate the HTML code
1831 if (isConfigEntrySet($configEntry)) {
1832 // Configuration entry is found
1833 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
1834 {%config,generateYesNoOptionList=' . $configEntry . '%}
1842 // Helper function to create a selection box for YES/NO form fields
1843 function doTemplateYesNoSelectionBox ($template, $clear, $formField) {
1844 // Generate the HTML code
1845 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
1846 {%pipe,generateYesNoOptionList%}
1853 // Helper function to create a selection box for YES/NO form fields, by NO is default
1854 function doTemplateNoYesSelectionBox ($template, $clear, $formField) {
1855 // Generate the HTML code
1856 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
1857 {%pipe,generateYesNoOptionList=N%}
1864 // Helper function to add extra content for member area (module=login)
1865 function doTemplateMemberFooterExtras ($template, $clear) {
1866 // Is a member logged in?
1868 // This shall not happen
1869 debug_report_bug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
1873 $filterData = array(
1874 'userid' => getMemberId(),
1875 'template' => $template,
1879 // Run the filter chain
1880 $filterData = runFilterChain('member_footer_extras', $filterData);
1883 return $filterData['output'];