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) {
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']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
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']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
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 (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($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 ((strpos($GLOBALS['tpl_content'][$template], '$') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{--') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{?') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{%') !== false)) {
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])) $content[2] = '';
552 // Re-construct the array: 0=visible,1=locked,2=prefix
553 $content['visible'] = $content[0];
554 $content['locked'] = $content[1];
556 // Call our "translator" function
557 $content = translateMenuVisibleLocked($content, $content[2]);
559 // Return CSS classes
560 return ($content['visible_css'] . ' ' . $content['locked_css']);
563 // Generate XHTML code for the CAPTCHA
564 function generateCaptchaCode ($code, $type, $type, $userid) {
565 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $type . '&mode=img&code=' . $code . '%}" />';
568 // Compiles the given HTML/mail code
569 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
570 // Is the code a string or should we not compile?
571 if ((!is_string($code)) || ($compileCode === false)) {
572 // Silently return it
577 $startCompile = microtime(true);
580 $code = compileRawCode($code, $simple, $constants, $full);
583 $compiled = microtime(true);
585 // Add timing if enabled
586 if (isTemplateHtml()) {
587 // Add timing, this should be disabled in
588 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
591 // Return compiled code
596 // @TODO $simple/$constants are deprecated
597 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
598 // Is the code a string or shall we not compile?
599 if ((!is_string($code)) || ($compileCode === false)) {
600 // Silently return it
604 // Init replacement-array with smaller set of security characters
605 $secChars = $GLOBALS['url_chars'];
607 // Select full set of chars to replace when we e.g. want to compile URLs
608 if ($full === true) {
609 $secChars = $GLOBALS['security_chars'];
612 // Compile more through a filter
613 $code = runFilterChain('compile_code', $code);
615 // Compile message strings
616 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
618 // Compile QUOT and other non-HTML codes
619 $code = str_replace($secChars['to'], $secChars['from'], $code);
621 // Find $content[bla][blub] entries
622 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
624 // Are some matches found?
625 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
626 // Replace all matches
627 $matchesFound = array();
628 foreach ($matches[0] as $key => $match) {
629 // Fuzzy look has failed by default
632 // Fuzzy look on match if already found
633 foreach ($matchesFound as $found => $set) {
635 $test = substr($found, 0, strlen($match));
637 // Does this entry exist?
638 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
639 if ($test == $match) {
641 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
648 if ($fuzzyFound === true) {
652 // Take all string elements
653 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
654 // Replace it in the code
655 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
656 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
657 $code = str_replace($match, '".' . $newMatch . '."', $code);
658 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
659 $matchesFound[$match] = true;
660 } elseif (!isset($matchesFound[$match])) {
662 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
663 $code = str_replace($match, '".' . $match . '."', $code);
664 $matchesFound[$match] = 1;
666 // Everthing else should be a least logged
667 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
677 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
681 // This is a yes/no selection only!
682 if ($id > 0) $prefix .= '[' . $id . ']';
683 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
685 // Begin with regular selection box here
686 if (!empty($prefix)) $prefix .= '_';
688 if ($id > 0) $type2 .= '[' . $id . ']';
689 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
694 for ($idx = 1; $idx < 32; $idx++) {
695 $OUT .= '<option value="' . $idx . '"';
696 if ($default == $idx) $OUT .= ' selected="selected"';
697 $OUT .= '>' . $idx . '</option>';
701 case 'month': // Month
702 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
703 $OUT .= '<option value="' . $idx . '"';
704 if ($default == $idx) $OUT .= ' selected="selected"';
705 $OUT .= '>' . $descr . '</option>';
713 // Use configured min age or fixed?
714 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
716 $startYear = $year - getConfig('min_age');
719 $startYear = $year - 16;
722 // Calculate earliest year (100 years old people can still enter Internet???)
723 $minYear = $year - 100;
725 // Check if the default value is larger than minimum and bigger than actual year
726 if (($default > $minYear) && ($default >= $year)) {
727 for ($idx = $year; $idx < ($year + 11); $idx++) {
728 $OUT .= '<option value="' . $idx . '"';
729 if ($default == $idx) $OUT .= ' selected="selected"';
730 $OUT .= '>' . $idx . '</option>';
732 } elseif ($default == -1) {
733 // Current year minus 1
734 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
735 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
738 // Get current year and subtract the configured minimum age
739 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
740 // Calculate earliest year depending on extension version
741 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
742 // Use configured minimum age
743 $year = getYear() - getConfig('min_age');
745 // Use fixed 16 years age
746 $year = getYear() - 16;
749 // Construct year selection list
750 for ($idx = $minYear; $idx <= $year; $idx++) {
751 $OUT .= '<option value="' . $idx . '"';
752 if ($default == $idx) $OUT .= ' selected="selected"';
753 $OUT .= '>' . $idx . '</option>';
760 for ($idx = 0; $idx < 60; $idx+=5) {
761 if (strlen($idx) == 1) $idx = '0' . $idx;
762 $OUT .= '<option value="' . $idx . '"';
763 if ($default == $idx) $OUT .= ' selected="selected"';
764 $OUT .= '>' . $idx . '</option>';
769 for ($idx = 0; $idx < 24; $idx++) {
770 if (strlen($idx) == 1) $idx = '0' . $idx;
771 $OUT .= '<option value="' . $idx . '"';
772 if ($default == $idx) $OUT .= ' selected="selected"';
773 $OUT .= '>' . $idx . '</option>';
778 $OUT .= '<option value="Y"';
779 if ($default == 'Y') $OUT .= ' selected="selected"';
780 $OUT .= '>{--YES--}</option><option value="N"';
781 if ($default != 'Y') $OUT .= ' selected="selected"';
782 $OUT .= '>{--NO--}</option>';
789 // Insert the code in $img_code into jpeg or PNG image
790 function generateImageOrCode ($img_code, $headerSent = true) {
791 // Is the code size oversized or shouldn't we display it?
792 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
793 // Stop execution of function here because of over-sized code length
794 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
795 } elseif ($headerSent === false) {
796 // Return an HTML code here
797 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
801 $img = sprintf("%s/theme/%s/images/code_bg.%s",
808 if (isFileReadable($img)) {
810 switch (getImgType()) {
811 case 'jpg': // Okay, load image and hide all errors
812 $image = imagecreatefromjpeg($img);
815 case 'png': // Okay, load image and hide all errors
816 $image = imagecreatefrompng($img);
820 // Silently log the error
821 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
825 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
826 $text_color = imagecolorallocate($image, 0, 0, 0);
828 // Insert code into image
829 imagestring($image, 5, 14, 2, $img_code, $text_color);
832 setContentType('image/' . getImgType());
834 // Output image with matching image factory
835 switch (getImgType()) {
836 case 'jpg': imagejpeg($image); break;
837 case 'png': imagepng($image); break;
840 // Remove image from memory
841 imagedestroy($image);
844 // Create selection box or array of splitted timestamp
845 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = false) {
846 // Do not continue if ONE_DAY is absend
847 if (!isConfigEntrySet('ONE_DAY')) {
849 debug_report_bug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
852 // Calculate 2-seconds timestamp
853 $stamp = round($timestamp);
854 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
856 // Do we have a leap year?
858 $TEST = getYear() / 4;
860 $M2 = getMonth(time() + $timestamp);
862 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
863 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
864 $SWITCH = getOneDay();
867 // First of all years...
868 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
869 //* DEBUG: */ debugOutput('Y=' . $Y);
871 $M = abs(floor($timestamp / 2628000 - $Y * 12));
872 //* DEBUG: */ debugOutput('M=' . $M);
874 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
875 //* DEBUG: */ debugOutput('W=' . $W);
877 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
878 //* DEBUG: */ debugOutput('D=' . $D);
880 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
881 //* DEBUG: */ debugOutput('h=' . $h);
883 $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));
884 //* DEBUG: */ debugOutput('m=' . $m);
885 // And at last seconds...
886 $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));
887 //* DEBUG: */ debugOutput('s=' . $s);
889 // Is seconds zero and time is < 60 seconds?
890 if (($s == '0') && ($timestamp < 60)) {
892 $s = round($timestamp);
896 // Now we convert them in seconds...
898 if ($asArray === true) {
899 // Just put all data in an array for later use
911 $OUT = '<div align="' . $align . '">';
912 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
915 if (isInString('Y', $display) || (empty($display))) {
916 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
919 if (isInString('M', $display) || (empty($display))) {
920 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
923 if (isInString('W', $display) || (empty($display))) {
924 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
927 if (isInString('D', $display) || (empty($display))) {
928 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
931 if (isInString('h', $display) || (empty($display))) {
932 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
935 if (isInString('m', $display) || (empty($display))) {
936 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
939 if (isInString('s', $display) || (empty($display))) {
940 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
946 if (isInString('Y', $display) || (empty($display))) {
947 // Generate year selection
948 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
949 for ($idx = 0; $idx <= 10; $idx++) {
950 $OUT .= '<option class="mini_select" value="' . $idx . '"';
951 if ($idx == $Y) $OUT .= ' selected="selected"';
952 $OUT .= '>' . $idx . '</option>';
954 $OUT .= '</select></td>';
956 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
959 if (isInString('M', $display) || (empty($display))) {
960 // Generate month selection
961 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
962 for ($idx = 0; $idx <= 11; $idx++) {
963 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
964 if ($idx == $M) $OUT .= ' selected="selected"';
965 $OUT .= '>' . $idx . '</option>';
967 $OUT .= '</select></td>';
969 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
972 if (isInString('W', $display) || (empty($display))) {
973 // Generate week selection
974 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
975 for ($idx = 0; $idx <= 4; $idx++) {
976 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
977 if ($idx == $W) $OUT .= ' selected="selected"';
978 $OUT .= '>' . $idx . '</option>';
980 $OUT .= '</select></td>';
982 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
985 if (isInString('D', $display) || (empty($display))) {
986 // Generate day selection
987 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
988 for ($idx = 0; $idx <= 31; $idx++) {
989 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
990 if ($idx == $D) $OUT .= ' selected="selected"';
991 $OUT .= '>' . $idx . '</option>';
993 $OUT .= '</select></td>';
995 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
998 if (isInString('h', $display) || (empty($display))) {
999 // Generate hour selection
1000 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1001 for ($idx = 0; $idx <= 23; $idx++) {
1002 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1003 if ($idx == $h) $OUT .= ' selected="selected"';
1004 $OUT .= '>' . $idx . '</option>';
1006 $OUT .= '</select></td>';
1008 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1011 if (isInString('m', $display) || (empty($display))) {
1012 // Generate minute selection
1013 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1014 for ($idx = 0; $idx <= 59; $idx++) {
1015 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1016 if ($idx == $m) $OUT .= ' selected="selected"';
1017 $OUT .= '>' . $idx . '</option>';
1019 $OUT .= '</select></td>';
1021 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1024 if (isInString('s', $display) || (empty($display))) {
1025 // Generate second selection
1026 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1027 for ($idx = 0; $idx <= 59; $idx++) {
1028 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1029 if ($idx == $s) $OUT .= ' selected="selected"';
1030 $OUT .= '>' . $idx . '</option>';
1032 $OUT .= '</select></td>';
1034 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1041 // Return generated HTML code
1045 // Generate a list of administrative links to a given userid
1046 function generateMemberAdminActionLinks ($userid) {
1047 // Make sure userid is a number
1048 if ($userid != bigintval($userid)) {
1049 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1052 // Define all main targets
1053 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1056 $status = getFetchedUserData('userid', $userid, 'status');
1058 // Begin of navigation links
1061 foreach ($targetArray as $tar) {
1062 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1063 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1064 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1065 // Locked accounts shall be unlocked
1066 $OUT .= 'UNLOCK_USER';
1067 } elseif ($tar == 'del_user') {
1068 // @TODO Deprecate this thing
1069 $OUT .= 'DELETE_USER';
1071 // All other status is fine
1072 $OUT .= strtoupper($tar);
1074 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1075 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1076 // Locked accounts shall be unlocked
1077 $OUT .= 'UNLOCK_USER';
1078 } elseif ($tar == 'del_user') {
1079 // @TODO Deprecate this thing
1080 $OUT .= 'DELETE_USER';
1082 // All other status is fine
1083 $OUT .= strtoupper($tar);
1085 $OUT .= '--}</a></span>|';
1088 // Add special link, in case of the account is unconfirmed
1089 if ($status == 'UNCONFIRMED') {
1091 $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>|';
1094 // Finish navigation link
1095 $OUT = substr($OUT, 0, -1) . ']';
1101 // Generate an email link
1102 function generateEmailLink ($email, $table = 'admins') {
1103 // Default email link (INSECURE! Spammer can read this by harvester programs)
1104 $EMAIL = 'mailto:' . $email;
1106 // Check for several extensions
1107 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1108 // Create email link for contacting admin in guest area
1109 $EMAIL = generateAdminEmailLink($email);
1110 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1111 // Create email link for contacting a member within admin area (or later in other areas, too?)
1112 $EMAIL = generateUserEmailLink($email);
1113 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1114 // Create email link to contact sponsor within admin area (or like the link above?)
1115 $EMAIL = generateSponsorEmailLink($email);
1118 // Return email link
1122 // Output error messages in a fasioned way and die...
1123 function app_die ($F, $L, $message) {
1124 // Check if Script is already dieing and not let it kill itself another 1000 times
1125 if (isset($GLOBALS['app_died'])) {
1126 // Script tried to kill itself twice
1127 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1130 // Make sure, that the script realy realy diese here and now
1131 $GLOBALS['app_died'] = true;
1133 // Set content type as text/html
1134 setContentType('text/html');
1137 loadIncludeOnce('inc/header.php');
1139 // Rewrite message for output
1140 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1142 // Load the message template
1143 loadTemplate('app_die_message', false, $message);
1146 loadIncludeOnce('inc/footer.php');
1149 // Display parsing time and number of SQL queries in footer
1150 function displayParsingTime () {
1151 // Is the timer started?
1152 if (!isset($GLOBALS['startTime'])) {
1158 $endTime = microtime(true);
1160 // "Explode" both times
1161 $start = explode(' ', $GLOBALS['startTime']);
1162 $end = explode(' ', $endTime);
1163 $runTime = $end[0] - $start[0];
1169 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1171 'run_time' => $runTime,
1172 'sql_time' => (getConfig('sql_time') * 1000),
1175 // Load the template
1176 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1179 // Output a debug backtrace to the user
1180 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1181 // Is this already called?
1182 if (isset($GLOBALS[__FUNCTION__])) {
1184 print 'Message:' . $message . '<br />Backtrace:<pre>';
1185 debug_print_backtrace();
1189 // Set this function as called
1190 $GLOBALS[__FUNCTION__] = true;
1195 // Is the optional message set?
1196 if (!empty($message)) {
1198 $debug = sprintf("Note: %s<br />\n",
1202 // @TODO Add a little more infos here
1203 logDebugMessage($F, $L, strip_tags($message));
1207 $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>';
1208 $debug .= debug_get_printable_backtrace();
1210 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1211 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1213 // Send an email? (e.g. not wanted for evaluation errors)
1214 if (($sendEmail === true) && (!isInstallationPhase())) {
1217 'message' => trim($message),
1218 'backtrace' => trim(debug_get_mailable_backtrace())
1221 // Send email to webmaster
1222 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1226 app_die($F, $L, $debug);
1229 // Compile characters which are allowed in URLs
1230 function compileUriCode ($code, $simple = true) {
1231 // Compile constants
1232 if ($simple === false) {
1233 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1236 // Compile QUOT and other non-HTML codes
1237 $code = str_replace('{DOT}', '.',
1238 str_replace('{SLASH}', '/',
1239 str_replace('{QUOT}', "'",
1240 str_replace('{DOLLAR}', '$',
1241 str_replace('{OPEN_ANCHOR}', '(',
1242 str_replace('{CLOSE_ANCHOR}', ')',
1243 str_replace('{OPEN_SQR}', '[',
1244 str_replace('{CLOSE_SQR}', ']',
1245 str_replace('{PER}', '%',
1249 // Return compiled code
1253 // Handle message codes from URL
1254 function handleCodeMessage () {
1256 if (isGetRequestParameterSet('code')) {
1257 // Default extension is 'unknown'
1260 // Is extension given?
1261 if (isGetRequestParameterSet('ext')) {
1262 $ext = getRequestParameter('ext');
1265 // Convert the 'code' parameter from URL to a human-readable message
1266 $message = getMessageFromErrorCode(getRequestParameter('code'));
1268 // Load message template
1269 loadTemplate('message', false, $message);
1273 // Generates a 'extension foo out-dated' message
1274 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1275 // Is the extension empty?
1276 if (empty($ext_name)) {
1277 // This should not happen
1278 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1282 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1284 // Is an admin logged in?
1286 // Then output admin message
1287 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1290 // Return prepared message
1294 // Generates a 'extension foo inactive' message
1295 function generateExtensionInactiveMessage ($ext_name) {
1296 // Is the extension empty?
1297 if (empty($ext_name)) {
1298 // This should not happen
1299 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1303 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1305 // Is an admin logged in?
1307 // Then output admin message
1308 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1311 // Return prepared message
1315 // Generates a 'extension foo not installed' message
1316 function generateExtensionNotInstalledMessage ($ext_name) {
1317 // Is the extension empty?
1318 if (empty($ext_name)) {
1319 // This should not happen
1320 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1324 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1326 // Is an admin logged in?
1328 // Then output admin message
1329 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1332 // Return prepared message
1336 // Generates a message depending on if the extension is not installed or not
1338 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1342 // Is the extension not installed or just deactivated?
1343 switch (isExtensionInstalled($ext_name)) {
1344 case true; // Deactivated!
1345 $message = generateExtensionInactiveMessage($ext_name);
1348 case false; // Not installed!
1349 $message = generateExtensionNotInstalledMessage($ext_name);
1352 default: // Should not happen!
1353 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1354 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1358 // Return the message
1362 // Print code with line numbers
1363 function linenumberCode ($code) {
1364 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1365 $count_lines = count($codeE);
1367 $r = 'Line | Code:<br />';
1368 foreach ($codeE as $line => $c) {
1369 $r .= '<div class="line"><span class="linenum">';
1370 if ($count_lines == 1) {
1373 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1378 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1381 return '<div class="code">' . $r . '</div>';
1384 // Determines the right page title
1385 function determinePageTitle () {
1389 // Config and database connection valid?
1390 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1391 // Title decoration enabled?
1392 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) {
1393 $pageTitle .= '{%config,trim=title_left%} ';
1396 // Do we have some extra title?
1397 if (isExtraTitleSet()) {
1399 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1403 $pageTitle .= '{?MAIN_TITLE?}';
1405 // Add title of module? (middle decoration will also be added!)
1406 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1407 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1410 // Add title from what file
1412 if (getModule() == 'login') {
1414 } elseif (getModule() == 'index') {
1416 } elseif (getModule() == 'admin') {
1418 } elseif (getModule() == 'sponsor') {
1422 // Add middle part (always in admin area!)
1423 if ((!empty($mode)) && ((isWhatTitleEnabled()) || ($mode == 'admin'))) {
1424 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($mode, getWhat());
1427 // Add title decorations? (right)
1428 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) {
1429 $pageTitle .= ' {%config,trim=title_right%}';
1431 } elseif ((isInstalled()) && (isAdminRegistered())) {
1432 // Installed, admin registered but no ext-sql_patches
1433 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1434 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1435 // Installed but no admin registered
1436 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1437 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1438 // Installation mode
1439 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1441 // Configuration not found
1442 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1444 // Do not add the fatal message in installation mode
1445 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1446 // Please report this
1447 debug_report_bug(__FUNCTION__, __LINE__, 'No configuration data found!');
1452 return decodeEntities($pageTitle);
1455 // Checks wethere there is a cache file there. This function is cached.
1456 function isTemplateCached ($template) {
1457 // Do we have cached this result?
1458 if (!isset($GLOBALS['template_cache'][$template])) {
1460 $FQFN = generateCacheFqfn($template);
1463 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1467 return $GLOBALS['template_cache'][$template];
1470 // Flushes non-flushed template cache to disk
1471 function flushTemplateCache ($template, $eval) {
1472 // Is this cache flushed?
1473 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1475 $FQFN = generateCacheFqfn($template);
1478 writeToFile($FQFN, $eval, true);
1482 // Reads a template cache
1483 function readTemplateCache ($template) {
1485 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1486 // This should not happen
1487 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1491 if (!isset($GLOBALS['template_eval'][$template])) {
1493 $FQFN = generateCacheFqfn($template);
1496 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1500 return $GLOBALS['template_eval'][$template];
1503 // Escapes quotes (default is only double-quotes)
1504 function escapeQuotes ($str, $single = false) {
1505 // Should we escape all?
1506 if ($single === true) {
1507 // Escape all (including null)
1508 $str = addslashes($str);
1510 // Remove escaping of single quotes
1511 $str = str_replace("\\'", "'", $str);
1513 // Escape only double-quotes but prevent double-quoting
1514 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1517 // Return the escaped string
1521 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1522 function escapeJavaScriptQuotes ($str) {
1523 // Replace all double-quotes and secure back-ticks
1524 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1530 // Send out mails depending on the 'mod/modes' combination
1531 // @TODO Lame description for this function
1532 function sendModeMails ($mod, $modes) {
1534 $content = array ();
1537 if (fetchUserData(getMemberId())) {
1538 // Extract salt from cookie
1539 $salt = substr(getSession('u_hash'), 0, -40);
1541 // Now let's compare passwords
1542 $hash = encodeHashForCookie(getUserData('password'));
1544 // Does the hash match or should we change it?
1545 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1547 $content = getUserDataArray();
1549 // Clear/init the content variable
1550 $content['message'] = '';
1553 // @TODO Move this in a filter
1556 foreach ($modes as $mode) {
1558 case 'normal': break; // Do not add any special lines
1559 case 'email': // Email was changed!
1560 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1563 case 'password': // Password was changed
1564 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1568 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1569 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1574 if (isExtensionActive('country')) {
1575 // Replace code with description
1576 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1579 // Merge content with data from POST
1580 $content = merge_array($content, postRequestArray());
1583 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1585 if (isAdminNotificationEnabled()) {
1586 // The admin needs to be notified about a profile change
1587 $message_admin = 'admin_mydata_notify';
1588 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1591 $message_admin = '';
1595 // Set subject lines
1596 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1598 // Output success message
1599 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1602 default: // Unsupported module!
1603 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1604 $content['message'] = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1608 // Passwords mismatch
1609 $content['message'] = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1612 // Could not load profile
1613 $content['message'] = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1616 // Send email to user if required
1617 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1619 sendEmail($content['userid'], $sub_mem, $message);
1622 // Send only if no other error has occured
1623 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1625 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1626 } elseif (isAdminNotificationEnabled()) {
1627 // Cannot send mails to admin!
1628 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1631 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1635 displayMessage($content['message']);
1638 // Generates a 'selection box' from given array
1639 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1641 $OUT = '<select name="' . $name . '" size="1" class="form_select">
1642 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1644 // Walk through all options
1645 foreach ($options as $option) {
1646 // Add the <option> entry from ...
1647 if (empty($optionContent)) {
1649 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1651 // ... direct HTML code
1652 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1656 // Finish selection box
1657 $OUT .= '</select>';
1661 'selection_box' => $OUT,
1664 // Load template and return it
1665 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1668 // Prepares the header for HTML output
1669 function loadHtmlHeader () {
1671 // 1.) pre_page_header (mainly loads the page_header template and includes
1672 // meta description)
1673 runFilterChain('pre_page_header');
1675 // Here can be something be added, but normally one of the two filters
1676 // around this line should do the job for you.
1678 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1679 // to close the head-tag)
1680 // Include more header data here
1681 runFilterChain('post_page_header');
1684 // Adds page header and footer to output array element
1685 function addPageHeaderFooter () {
1689 // Add them all together. This is maybe to simple
1690 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1691 // Add page part if set
1692 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1695 // Transfer $OUT to 'output'
1696 $GLOBALS['output'] = $OUT;
1699 // Generates meta description for current module and 'what' value
1700 function generateMetaDescriptionCode () {
1701 // Only include from guest area and if sql_patches has correct version
1702 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1703 // Construct dynamic description
1704 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1706 // Output it directly
1707 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1710 // Initialize referal system
1711 initReferalSystem();
1714 // Generates an FQFN for template cache from the given template name
1715 function generateCacheFqfn ($template, $mode = 'html') {
1717 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1718 // Generate the FQFN
1719 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1720 "%s_compiled/%s/%s.tpl.cache",
1728 return $GLOBALS['template_cache_fqfn'][$template];
1731 // "Fixes" null or empty string to count of dashes
1732 function fixNullEmptyToDashes ($str, $num) {
1733 // Use str as default
1737 if ((is_null($str)) || (trim($str) == '')) {
1739 $return = str_repeat('-', $num);
1742 // Return final string
1746 // Translates the "pool type" into human-readable
1747 function translatePoolType ($type) {
1748 // Return "translation"
1749 return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1752 // Displays given message in admin_settings_saved template
1753 function displayMessage ($message, $return = false) {
1754 // Load the template
1755 return loadTemplate('admin_settings_saved', $return, $message);
1758 // Generates a selection box for (maybe) given gender
1759 function generateGenderSelectionBox ($selectedGender = '') {
1760 // Start the HTML code
1761 $out = '<select name="gender" size="1" class="form_select">';
1764 $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1767 $out .= '</select>';
1773 //-----------------------------------------------------------------------------
1774 // Template helper functions for EL code
1775 //-----------------------------------------------------------------------------
1777 // Color-switch helper function
1778 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1780 if (!isset($GLOBALS['color_switch'][$template])) {
1782 initTemplateColorSwitch($template);
1783 } elseif ($clear === false) {
1784 // Switch color if called from loadTemplate()
1785 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1786 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1789 // Return CSS class name
1790 if ($return === true) {
1791 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1792 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1796 // Helper function for extension registration link
1797 function doTemplateExtensionRegistrationLink ($template, $clear, $ext_name) {
1798 // Default is all non-productive
1799 $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>';
1801 // Is the given extension non-productive?
1802 if (isExtensionProductive($ext_name)) {
1804 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1811 // Helper function to create bonus mail admin links
1812 function doTemplateAdminBonusMailLinks ($template, $clear, $bonusId) {
1813 // Call the inner function
1814 return generateAdminMailLinks('bid', $bonusId);
1817 // Helper function to create member mail admin links
1818 function doTemplateAdminMemberMailLinks ($template, $clear, $mailId) {
1819 // Call the inner function
1820 return generateAdminMailLinks('mid', $mailId);
1823 // Helper function to create a selection box for YES/NO configuration entries
1824 function doTemplateConfigurationYesNoSelectionBox ($template, $clear, $configEntry) {
1825 // Default is a "missing entry" warning
1826 $OUT = '<em style="cursor:help" class="notice" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</em>';
1828 // Generate the HTML code
1829 if (isConfigEntrySet($configEntry)) {
1830 // Configuration entry is found
1831 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
1832 {%config,generateYesNoOptionList=' . $configEntry . '%}
1840 // Helper function to create a selection box for YES/NO form fields
1841 function doTemplateYesNoSelectionBox ($template, $clear, $formField) {
1842 // Generate the HTML code
1843 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
1844 {%pipe,generateYesNoOptionList%}
1851 // Helper function to create a selection box for YES/NO form fields, by NO is default
1852 function doTemplateNoYesSelectionBox ($template, $clear, $formField) {
1853 // Generate the HTML code
1854 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
1855 {%pipe,generateYesNoOptionList=N%}