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) {
117 // Render mode for old or lame servers...
118 $GLOBALS['output'] .= $htmlCode;
120 // That's why you don't need any \n at the end of your HTML code... :-)
121 if ($newLine === true) {
122 $GLOBALS['output'] .= "\n";
128 // If we are switching from render to direct output rendered code
129 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) {
130 outputRawCode($GLOBALS['output']);
131 $GLOBALS['output'] = '';
134 // The same as above... ^
135 outputRawCode($htmlCode);
136 if ($newLine === true) {
142 // Huh, something goes wrong or maybe you have edited config.php ???
143 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
146 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
147 // Output cached HTML code
148 $GLOBALS['output'] = ob_get_contents();
150 // Clear output buffer for later output if output is found
151 if (!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']);
163 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
164 // Send all HTTP headers
167 // Compile and run finished rendered HTML code
168 compileFinalOutput();
170 // Output code here, DO NOT REMOVE! ;-)
171 outputRawCode($GLOBALS['output']);
173 // And flush all headers
178 // Compiles the final output
179 function compileFinalOutput () {
180 // Add page header and footer
181 addPageHeaderFooter();
183 // Do the final compilation
184 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
186 // Extension 'rewrite' installed?
187 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
188 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
193 * @TODO On some pages this is buggy
194 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
195 // Compress it for HTTP gzip
196 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9);
199 addHttpHeader('Content-Encoding: gzip');
200 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
201 // Compress it for HTTP deflate
202 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
205 addHttpHeader('Content-Encoding: deflate');
210 addHttpHeader('Content-Length: ' . strlen($GLOBALS['output']));
216 // Main compilation loop
217 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
218 // Insert comments? (Only valid with HTML templates, of course)
219 enableTemplateHtml($insertComments);
225 while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== false)) && ($count < 7)) {
226 // Init common variables
231 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
232 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
233 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
235 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
236 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
238 // Was that eval okay?
239 if (empty($newContent)) {
240 // Something went wrong!
241 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
247 // Compile the final code if insertComments is true
248 if ($insertComments == true) {
249 // ... because SQL queries shall keep OPEN_CONFIG and such in
250 $code = compileRawCode($code);
257 // Add debugging data in HTML code, if mode is enabled
258 if ((isDebugModeEnabled()) && ($insertComments === true)) {
260 $code .= '<!-- Total compilation loop=' . $count . ' //-->';
263 // Return the compiled code
267 // Output the raw HTML code
268 function outputRawCode ($htmlCode) {
269 // Output stripped HTML code to avoid broken JavaScript code, etc.
270 print(str_replace('{BACK}', "\\", $htmlCode));
272 // Flush the output if only getPhpCaching() is not 'on'
273 if (getPhpCaching() != 'on') {
279 // Load a template file and return it's content (only it's name; do not use ' or ")
280 function loadTemplate ($template, $return = false, $content = array(), $compileCode = true) {
281 // @TODO Remove these sanity checks if all is fine
282 if (!is_bool($return)) {
283 // $return has to be boolean
284 debug_report_bug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
285 } elseif (!is_string($template)) {
286 // $template has to be string
287 debug_report_bug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
290 // Init returned content
293 // Set current template
294 $GLOBALS['current_template'] = $template;
297 if ((!isDebuggingTemplateCache()) && (isTemplateCached($template))) {
298 // Evaluate the cache
299 eval(readTemplateCache($template));
300 } elseif (!isset($GLOBALS['template_eval'][$template])) {
301 // Make all template names lowercase
302 $template = strtolower($template);
305 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
306 $extraPath = detectExtraTemplatePath($template);
309 $FQFN = $basePath . $extraPath . $template . '.tpl';
311 // Does the special template exists?
312 if (!isFileReadable($FQFN)) {
313 // Reset to default template
314 $FQFN = $basePath . $template . '.tpl';
317 // Now does the final template exists?
318 if (isFileReadable($FQFN)) {
319 // Count the template load
320 incrementConfigEntry('num_templates');
322 // The local file does exists so we load it. :)
323 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
325 // Do we have to compile the code?
326 if ((isInString('$', $GLOBALS['tpl_content'][$template])) || (isInString('{--', $GLOBALS['tpl_content'][$template])) || (isInString('{?', $GLOBALS['tpl_content'][$template])) || (isInString('{%', $GLOBALS['tpl_content'][$template]))) {
327 // Normal HTML output?
328 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
329 // Add surrounding HTML comments to help finding bugs faster
330 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
332 // Prepare eval() command
333 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
334 } elseif (substr($template, 0, 3) == 'js_') {
335 // JavaScripts don't like entities, dollar signs and timings
336 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
338 // Prepare eval() command, other output doesn't like entities, maybe
339 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
341 } elseif (isHtmlOutputMode()) {
342 // Add surrounding HTML comments to help finding bugs faster
343 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
344 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
347 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
349 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
350 // Only admins shall see this warning or when installation mode is active
351 $ret = '<div class="para">
352 <span class="bad">{--TEMPLATE_404--}</span>
358 {--TEMPLATE_CONTENT--}:
359 <pre>' . print_r($content, true) . '</pre>
363 $GLOBALS['template_eval'][$template] = '404';
368 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
370 eval($GLOBALS['template_eval'][$template]);
373 // Do we have some content to output or return?
375 // Not empty so let's put it out! ;)
376 if ($return === true) {
377 // Return the HTML code
383 } elseif (isDebugModeEnabled()) {
384 // Warning, empty output!
385 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
389 // Detects the extra template path from given template name
390 function detectExtraTemplatePath ($template) {
395 if (!isset($GLOBALS['extra_path'][$template])) {
396 // Check for admin/guest/member/etc. templates
397 if (substr($template, 0, 6) == 'admin_') {
398 // Admin template found
399 $extraPath = 'admin/';
400 } elseif (substr($template, 0, 6) == 'guest_') {
401 // Guest template found
402 $extraPath = 'guest/';
403 } elseif (substr($template, 0, 7) == 'member_') {
404 // Member template found
405 $extraPath = 'member/';
406 } elseif (substr($template, 0, 7) == 'select_') {
407 // Selection template found
408 $extraPath = 'select/';
409 } elseif (substr($template, 0, 8) == 'install_') {
410 // Installation template found
411 $extraPath = 'install/';
412 } elseif (substr($template, 0, 4) == 'ext_') {
413 // Extension template found
415 } elseif (substr($template, 0, 3) == 'la_') {
416 // 'Logical-area' template found
418 } elseif (substr($template, 0, 3) == 'js_') {
419 // JavaScript template found
421 } elseif (substr($template, 0, 5) == 'menu_') {
422 // Menu template found
423 $extraPath = 'menu/';
425 // Test for extension
426 $test = substr($template, 0, strpos($template, '_'));
428 // Probe for valid extension name
429 if (isExtensionNameValid($test)) {
430 // Set extra path to extension's name
431 $extraPath = $test . '/';
436 $GLOBALS['extra_path'][$template] = $extraPath;
440 return $GLOBALS['extra_path'][$template];
443 // Loads an email template and compiles it
444 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = true) {
445 // Make sure all template names are lowercase!
446 $template = strtolower($template);
448 // Is content an array?
449 if (is_array($content)) {
450 // Add expiration to array
451 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
452 // Will never expire!
453 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
454 } elseif (isConfigEntrySet('auto_purge')) {
455 // Create nice date string
456 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
459 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
464 // @DEPRECATED Loading the user data by given userid is deprecated because it is not related to template loading
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UID=' . $userid . ',template=' . $template . ',content[]=' . gettype($content));
466 if ((isValidUserId($userid)) && (is_array($content))) {
467 // If nickname extension is installed, fetch nickname as well
468 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - NICKNAME!');
471 fetchUserData($userid, 'nickname');
472 } elseif (isNicknameUsed($userid)) {
473 // Non-number characters entered but no ext-nickname found
474 debug_report_bug(__FUNCTION__, __LINE__, 'userid=' . $userid . ': is no id number and ext-nickname is gone.');
477 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - USERID!');
478 fetchUserData($userid);
481 // Merge data if valid
482 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - BEFORE!');
483 if ((isUserDataValid()) && ($loadUserData === true)) {
485 $content = merge_array($content, getUserDataArray());
487 // But we don't like hashed passwords be mailed
488 unset($content['password']);
491 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - AFTER!');
495 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
498 $extraPath = detectExtraTemplatePath($template);
500 // Generate full FQFN
501 $FQFN = $basePath . $extraPath . $template . '.tpl';
503 // Does the special template exists?
504 if (!isFileReadable($FQFN)) {
505 // Reset to default template
506 $FQFN = $basePath . $template . '.tpl';
509 // Now does the final template exists?
511 if (isFileReadable($FQFN)) {
512 // The local file does exists so we load it. :)
513 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
516 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
517 eval($GLOBALS['tpl_content'][$template]);
518 } elseif (!empty($template)) {
519 // Template file not found
520 $newContent = '<div class="para">
521 {--TEMPLATE_404--}: ' . $template . '
524 {--TEMPLATE_CONTENT--}:
525 <pre>' . print_r($content, true) . '</pre>
528 // Debug mode not active? Then remove the HTML tags
529 if (!isDebugModeEnabled()) {
531 $newContent = secureString($newContent);
534 // No template name supplied!
535 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
538 // Is there some content?
539 if (empty($newContent)) {
541 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
543 // Add last error if the required function exists
544 if (function_exists('error_get_last')) {
545 // Add last error and some lines for better overview
546 $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
550 // Remove content and data
557 // "Getter" for menu CSS classes, mainly used in templates
558 function getMenuCssClasses ($data) {
559 // $data needs to be converted into an array
560 $content = explode('|', $data);
562 // Non-existent index 2 will happen in menu blocks
563 if (!isset($content[2])) {
567 // Re-construct the array: 0=visible,1=locked,2=prefix
568 $content['visible'] = $content[0];
569 $content['locked'] = $content[1];
571 // Call our "translator" function
572 $content = translateMenuVisibleLocked($content, $content[2]);
574 // Return CSS classes
575 return ($content['visible_css'] . ' ' . $content['locked_css']);
578 // Generate XHTML code for the CAPTCHA
579 function generateCaptchaCode ($code, $type, $type, $userid) {
580 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $type . '&do=img&code=' . $code . '%}" />';
583 // Compiles the given HTML/mail code
584 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
585 // Is the code a string or should we not compile?
586 if ((!is_string($code)) || ($compileCode === false)) {
587 // Silently return it
592 $startCompile = microtime(true);
595 $code = compileRawCode($code, $simple, $constants, $full);
598 $compiled = microtime(true);
600 // Add timing if enabled
601 if (isTemplateHtml()) {
602 // Add timing, this should be disabled in
603 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
606 // Return compiled code
611 // @TODO $simple/$constants are deprecated
612 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
613 // Is the code a string or shall we not compile?
614 if ((!is_string($code)) || ($compileCode === false)) {
615 // Silently return it
619 // Init replacement-array with smaller set of security characters
620 $secChars = $GLOBALS['url_chars'];
622 // Select full set of chars to replace when we e.g. want to compile URLs
623 if ($full === true) {
624 $secChars = $GLOBALS['security_chars'];
627 // Compile more through a filter
628 $code = runFilterChain('compile_code', $code);
630 // Compile message strings
631 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
633 // Compile QUOT and other non-HTML codes
634 $code = str_replace($secChars['to'], $secChars['from'], $code);
636 // Find $fooBar entries
637 preg_match_all('/\$(.){0,}/', $code, $matches);
639 // Are some matches found?
640 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
641 // Scan all matches for not $content
642 foreach ($matches[0] as $match) {
644 $match = trim($match);
646 // Is the first part not $content and not empty?
647 if ((!empty($match)) && (substr($match, 0, 8) != '$content')) {
648 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
649 // Then replace $ with $
650 $matchSecured = str_replace('$', '$', $match);
652 // And in $code as well
653 $code = str_replace($match, $matchSecured, $code);
658 // Find $content[bla][blub] entries
659 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
661 // Are some matches found?
662 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
663 // Replace all matches
664 $matchesFound = array();
665 foreach ($matches[0] as $key => $match) {
666 // Fuzzy look has failed by default
669 // Fuzzy look on match if already found
670 foreach ($matchesFound as $found => $set) {
672 $test = substr($found, 0, strlen($match));
674 // Does this entry exist?
675 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
676 if ($test == $match) {
678 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
685 if ($fuzzyFound === true) {
689 // Take all string elements
690 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
691 // Replace it in the code
692 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
693 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
694 $code = str_replace($match, '".' . $newMatch . '."', $code);
695 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
696 $matchesFound[$match] = true;
697 } elseif (!isset($matchesFound[$match])) {
699 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
700 $code = str_replace($match, '".' . $match . '."', $code);
701 $matchesFound[$match] = 1;
703 // Everthing else should be a least logged
704 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
714 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
718 // This is a yes/no selection only!
719 if ($id > 0) $prefix .= '[' . $id . ']';
720 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
722 // Begin with regular selection box here
723 if (!empty($prefix)) $prefix .= '_';
725 if ($id > 0) $type2 .= '[' . $id . ']';
726 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
731 for ($idx = 1; $idx < 32; $idx++) {
732 $OUT .= '<option value="' . $idx . '"';
733 if ($default == $idx) $OUT .= ' selected="selected"';
734 $OUT .= '>' . $idx . '</option>';
738 case 'month': // Month
739 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
740 $OUT .= '<option value="' . $idx . '"';
741 if ($default == $idx) $OUT .= ' selected="selected"';
742 $OUT .= '>' . $descr . '</option>';
750 // Use configured min age or fixed?
751 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
753 $startYear = $year - getConfig('min_age');
756 $startYear = $year - 16;
759 // Calculate earliest year (100 years old people can still enter Internet???)
760 $minYear = $year - 100;
762 // Check if the default value is larger than minimum and bigger than actual year
763 if (($default > $minYear) && ($default >= $year)) {
764 for ($idx = $year; $idx < ($year + 11); $idx++) {
765 $OUT .= '<option value="' . $idx . '"';
766 if ($default == $idx) $OUT .= ' selected="selected"';
767 $OUT .= '>' . $idx . '</option>';
769 } elseif ($default == -1) {
770 // Current year minus 1
771 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
772 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
775 // Get current year and subtract the configured minimum age
776 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
777 // Calculate earliest year depending on extension version
778 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
779 // Use configured minimum age
780 $year = getYear() - getConfig('min_age');
782 // Use fixed 16 years age
783 $year = getYear() - 16;
786 // Construct year selection list
787 for ($idx = $minYear; $idx <= $year; $idx++) {
788 $OUT .= '<option value="' . $idx . '"';
789 if ($default == $idx) $OUT .= ' selected="selected"';
790 $OUT .= '>' . $idx . '</option>';
797 for ($idx = 0; $idx < 60; $idx+=5) {
798 if (strlen($idx) == 1) $idx = '0' . $idx;
799 $OUT .= '<option value="' . $idx . '"';
800 if ($default == $idx) $OUT .= ' selected="selected"';
801 $OUT .= '>' . $idx . '</option>';
806 for ($idx = 0; $idx < 24; $idx++) {
807 if (strlen($idx) == 1) $idx = '0' . $idx;
808 $OUT .= '<option value="' . $idx . '"';
809 if ($default == $idx) $OUT .= ' selected="selected"';
810 $OUT .= '>' . $idx . '</option>';
815 $OUT .= '<option value="Y"';
816 if ($default == 'Y') $OUT .= ' selected="selected"';
817 $OUT .= '>{--YES--}</option><option value="N"';
818 if ($default != 'Y') $OUT .= ' selected="selected"';
819 $OUT .= '>{--NO--}</option>';
826 // Insert the code in $img_code into jpeg or PNG image
827 function generateImageOrCode ($img_code, $headerSent = true) {
828 // Is the code size oversized or shouldn't we display it?
829 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
830 // Stop execution of function here because of over-sized code length
831 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
832 } elseif ($headerSent === false) {
833 // Return an HTML code here
834 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
838 $img = sprintf("%s/theme/%s/images/code_bg.%s",
845 if (isFileReadable($img)) {
847 switch (getImgType()) {
848 case 'jpg': // Okay, load image and hide all errors
849 $image = imagecreatefromjpeg($img);
852 case 'png': // Okay, load image and hide all errors
853 $image = imagecreatefrompng($img);
857 // Silently log the error
858 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
862 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
863 $text_color = imagecolorallocate($image, 0, 0, 0);
865 // Insert code into image
866 imagestring($image, 5, 14, 2, $img_code, $text_color);
869 setContentType('image/' . getImgType());
871 // Output image with matching image factory
872 switch (getImgType()) {
873 case 'jpg': imagejpeg($image); break;
874 case 'png': imagepng($image); break;
877 // Remove image from memory
878 imagedestroy($image);
881 // Create selection box or array of splitted timestamp
882 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = false) {
883 // Do not continue if ONE_DAY is absend
884 if (!isConfigEntrySet('ONE_DAY')) {
886 debug_report_bug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
889 // Calculate 2-seconds timestamp
890 $stamp = round($timestamp);
891 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
893 // Do we have a leap year?
895 $TEST = getYear() / 4;
897 $M2 = getMonth(time() + $timestamp);
899 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
900 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
901 $SWITCH = getOneDay();
904 // First of all years...
905 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
906 //* DEBUG: */ debugOutput('Y=' . $Y);
908 $M = abs(floor($timestamp / 2628000 - $Y * 12));
909 //* DEBUG: */ debugOutput('M=' . $M);
911 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
912 //* DEBUG: */ debugOutput('W=' . $W);
914 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
915 //* DEBUG: */ debugOutput('D=' . $D);
917 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
918 //* DEBUG: */ debugOutput('h=' . $h);
920 $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));
921 //* DEBUG: */ debugOutput('m=' . $m);
922 // And at last seconds...
923 $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));
924 //* DEBUG: */ debugOutput('s=' . $s);
926 // Is seconds zero and time is < 60 seconds?
927 if (($s == '0') && ($timestamp < 60)) {
929 $s = round($timestamp);
933 // Now we convert them in seconds...
935 if ($asArray === true) {
936 // Just put all data in an array for later use
948 $OUT = '<div align="' . $align . '">';
949 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
952 if (isInString('Y', $display) || (empty($display))) {
953 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_YEAR--}</strong></td>';
956 if (isInString('M', $display) || (empty($display))) {
957 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MONTH--}</strong></td>';
960 if (isInString('W', $display) || (empty($display))) {
961 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_WEEK--}</strong></td>';
964 if (isInString('D', $display) || (empty($display))) {
965 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_DAY--}</strong></td>';
968 if (isInString('h', $display) || (empty($display))) {
969 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_HOUR--}</strong></td>';
972 if (isInString('m', $display) || (empty($display))) {
973 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MINUTE--}</strong></td>';
976 if (isInString('s', $display) || (empty($display))) {
977 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_SECOND--}</strong></td>';
983 if (isInString('Y', $display) || (empty($display))) {
984 // Generate year selection
985 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
986 for ($idx = 0; $idx <= 10; $idx++) {
987 $OUT .= '<option class="mini_select" value="' . $idx . '"';
988 if ($idx == $Y) $OUT .= ' selected="selected"';
989 $OUT .= '>' . $idx . '</option>';
991 $OUT .= '</select></td>';
993 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
996 if (isInString('M', $display) || (empty($display))) {
997 // Generate month selection
998 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
999 for ($idx = 0; $idx <= 11; $idx++) {
1000 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1001 if ($idx == $M) $OUT .= ' selected="selected"';
1002 $OUT .= '>' . $idx . '</option>';
1004 $OUT .= '</select></td>';
1006 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1009 if (isInString('W', $display) || (empty($display))) {
1010 // Generate week selection
1011 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1012 for ($idx = 0; $idx <= 4; $idx++) {
1013 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1014 if ($idx == $W) $OUT .= ' selected="selected"';
1015 $OUT .= '>' . $idx . '</option>';
1017 $OUT .= '</select></td>';
1019 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1022 if (isInString('D', $display) || (empty($display))) {
1023 // Generate day selection
1024 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1025 for ($idx = 0; $idx <= 31; $idx++) {
1026 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1027 if ($idx == $D) $OUT .= ' selected="selected"';
1028 $OUT .= '>' . $idx . '</option>';
1030 $OUT .= '</select></td>';
1032 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1035 if (isInString('h', $display) || (empty($display))) {
1036 // Generate hour selection
1037 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1038 for ($idx = 0; $idx <= 23; $idx++) {
1039 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1040 if ($idx == $h) $OUT .= ' selected="selected"';
1041 $OUT .= '>' . $idx . '</option>';
1043 $OUT .= '</select></td>';
1045 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1048 if (isInString('m', $display) || (empty($display))) {
1049 // Generate minute selection
1050 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1051 for ($idx = 0; $idx <= 59; $idx++) {
1052 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1053 if ($idx == $m) $OUT .= ' selected="selected"';
1054 $OUT .= '>' . $idx . '</option>';
1056 $OUT .= '</select></td>';
1058 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1061 if (isInString('s', $display) || (empty($display))) {
1062 // Generate second selection
1063 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1064 for ($idx = 0; $idx <= 59; $idx++) {
1065 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1066 if ($idx == $s) $OUT .= ' selected="selected"';
1067 $OUT .= '>' . $idx . '</option>';
1069 $OUT .= '</select></td>';
1071 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1078 // Return generated HTML code
1082 // Generate a list of administrative links to a given userid
1083 function generateMemberAdminActionLinks ($userid) {
1084 // Make sure userid is a number
1085 if ($userid != bigintval($userid)) {
1086 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1089 // Define all main targets
1090 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1093 $status = getFetchedUserData('userid', $userid, 'status');
1095 // Begin of navigation links
1098 foreach ($targetArray as $tar) {
1099 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1100 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1101 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1102 // Locked accounts shall be unlocked
1103 $OUT .= 'UNLOCK_USER';
1104 } elseif ($tar == 'del_user') {
1105 // @TODO Deprecate this thing
1106 $OUT .= 'DELETE_USER';
1108 // All other status is fine
1109 $OUT .= strtoupper($tar);
1111 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1112 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1113 // Locked accounts shall be unlocked
1114 $OUT .= 'UNLOCK_USER';
1115 } elseif ($tar == 'del_user') {
1116 // @TODO Deprecate this thing
1117 $OUT .= 'DELETE_USER';
1119 // All other status is fine
1120 $OUT .= strtoupper($tar);
1122 $OUT .= '--}</a></span>|';
1125 // Add special link, in case of the account is unconfirmed
1126 if ($status == 'UNCONFIRMED') {
1128 $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>|';
1131 // Finish navigation link
1132 $OUT = substr($OUT, 0, -1) . ']';
1138 // Generate an email link
1139 function generateEmailLink ($email, $table = 'admins') {
1140 // Default email link (INSECURE! Spammer can read this by harvester programs)
1141 $EMAIL = 'mailto:' . $email;
1143 // Check for several extensions
1144 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1145 // Create email link for contacting admin in guest area
1146 $EMAIL = generateAdminEmailLink($email);
1147 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1148 // Create email link for contacting a member within admin area (or later in other areas, too?)
1149 $EMAIL = generateUserEmailLink($email);
1150 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1151 // Create email link to contact sponsor within admin area (or like the link above?)
1152 $EMAIL = generateSponsorEmailLink($email);
1155 // Return email link
1159 // Output error messages in a fasioned way and die...
1160 function app_die ($F, $L, $message) {
1161 // Check if Script is already dieing and not let it kill itself another 1000 times
1162 if (isset($GLOBALS['app_died'])) {
1163 // Script tried to kill itself twice
1164 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1167 // Make sure, that the script realy realy diese here and now
1168 $GLOBALS['app_died'] = true;
1170 // Set content type as text/html
1171 setContentType('text/html');
1174 loadIncludeOnce('inc/header.php');
1176 // Rewrite message for output
1177 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1179 // Load the message template
1180 loadTemplate('app_die_message', false, $message);
1183 loadIncludeOnce('inc/footer.php');
1186 // Display parsing time and number of SQL queries in footer
1187 function displayParsingTime () {
1188 // Is the timer started?
1189 if (!isset($GLOBALS['startTime'])) {
1195 $endTime = microtime(true);
1197 // "Explode" both times
1198 $start = explode(' ', $GLOBALS['startTime']);
1199 $end = explode(' ', $endTime);
1200 $runTime = $end[0] - $start[0];
1206 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1208 'run_time' => $runTime,
1209 'sql_time' => (getConfig('sql_time') * 1000),
1212 // Load the template
1213 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1216 // Output a debug backtrace to the user
1217 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1218 // Is this already called?
1219 if (isset($GLOBALS[__FUNCTION__])) {
1221 print 'Message:' . $message . '<br />Backtrace:<pre>';
1222 debug_print_backtrace();
1226 // Set HTTP status to 500 (e.g. for AJAX requests)
1227 setHttpStatus('500 Internal Server Error');
1229 // Set this function as called
1230 $GLOBALS[__FUNCTION__] = true;
1235 // Is the optional message set?
1236 if (!empty($message)) {
1238 $debug = sprintf("Note: %s<br />\n",
1242 // @TODO Add a little more infos here
1243 logDebugMessage($F, $L, strip_tags($message));
1247 $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>';
1248 $debug .= debug_get_printable_backtrace();
1250 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1251 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1253 // Send an email? (e.g. not wanted for evaluation errors)
1254 if (($sendEmail === true) && (!isInstallationPhase())) {
1257 'message' => trim($message),
1258 'backtrace' => trim(debug_get_mailable_backtrace())
1261 // Send email to webmaster
1262 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1266 app_die($F, $L, $debug);
1269 // Compile characters which are allowed in URLs
1270 function compileUriCode ($code, $simple = true) {
1271 // Compile constants
1272 if ($simple === false) {
1273 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1276 // Compile QUOT and other non-HTML codes
1277 $code = str_replace('{DOT}', '.',
1278 str_replace('{SLASH}', '/',
1279 str_replace('{QUOT}', "'",
1280 str_replace('{DOLLAR}', '$',
1281 str_replace('{OPEN_ANCHOR}', '(',
1282 str_replace('{CLOSE_ANCHOR}', ')',
1283 str_replace('{OPEN_SQR}', '[',
1284 str_replace('{CLOSE_SQR}', ']',
1285 str_replace('{PER}', '%',
1289 // Return compiled code
1293 // Handle message codes from URL
1294 function handleCodeMessage () {
1296 if (isGetRequestElementSet('code')) {
1297 // Default extension is 'unknown'
1300 // Is extension given?
1301 if (isGetRequestElementSet('ext')) {
1302 $ext = getRequestElement('ext');
1305 // Convert the 'code' parameter from URL to a human-readable message
1306 $message = getMessageFromErrorCode(getRequestElement('code'));
1308 // Load message template
1309 loadTemplate('message', false, $message);
1313 // Generates a 'extension foo out-dated' message
1314 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1315 // Is the extension empty?
1316 if (empty($ext_name)) {
1317 // This should not happen
1318 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1322 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1324 // Is an admin logged in?
1326 // Then output admin message
1327 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1330 // Return prepared message
1334 // Generates a 'extension foo inactive' message
1335 function generateExtensionInactiveMessage ($ext_name) {
1336 // Is the extension empty?
1337 if (empty($ext_name)) {
1338 // This should not happen
1339 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1343 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1345 // Is an admin logged in?
1347 // Then output admin message
1348 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1351 // Return prepared message
1355 // Generates a 'extension foo not installed' message
1356 function generateExtensionNotInstalledMessage ($ext_name) {
1357 // Is the extension empty?
1358 if (empty($ext_name)) {
1359 // This should not happen
1360 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1364 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1366 // Is an admin logged in?
1368 // Then output admin message
1369 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1372 // Return prepared message
1376 // Generates a message depending on if the extension is not installed or not
1378 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1382 // Is the extension not installed or just deactivated?
1383 switch (isExtensionInstalled($ext_name)) {
1384 case true; // Deactivated!
1385 $message = generateExtensionInactiveMessage($ext_name);
1388 case false; // Not installed!
1389 $message = generateExtensionNotInstalledMessage($ext_name);
1392 default: // Should not happen!
1393 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1394 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1398 // Return the message
1402 // Print code with line numbers
1403 function linenumberCode ($code) {
1404 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1405 $count_lines = count($codeE);
1407 $r = 'Line | Code:<br />';
1408 foreach ($codeE as $line => $c) {
1409 $r .= '<div class="line"><span class="linenum">';
1410 if ($count_lines == 1) {
1413 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1418 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1421 return '<div class="code">' . $r . '</div>';
1424 // Determines the right page title
1425 function determinePageTitle () {
1429 // Config and database connection valid?
1430 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1431 // Title decoration enabled?
1432 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) {
1433 $pageTitle .= '{%config,trim=title_left%} ';
1436 // Do we have some extra title?
1437 if (isExtraTitleSet()) {
1439 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1443 $pageTitle .= '{?MAIN_TITLE?}';
1445 // Add title of module? (middle decoration will also be added!)
1446 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1447 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1450 // Add title from what file
1452 if (getModule() == 'login') {
1453 $menuMode = 'member';
1454 } elseif (getModule() == 'index') {
1455 $menuMode = 'guest';
1456 } elseif (getModule() == 'admin') {
1457 $menuMode = 'admin';
1458 } elseif (getModule() == 'sponsor') {
1459 $menuMode = 'sponsor';
1462 // Add middle part (always in admin area!)
1463 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1464 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1467 // Add title decorations? (right)
1468 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) {
1469 $pageTitle .= ' {%config,trim=title_right%}';
1471 } elseif ((isInstalled()) && (isAdminRegistered())) {
1472 // Installed, admin registered but no ext-sql_patches
1473 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1474 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1475 // Installed but no admin registered
1476 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1477 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1478 // Installation mode
1479 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1481 // Configuration not found
1482 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1484 // Do not add the fatal message in installation mode
1485 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1486 // Please report this
1487 debug_report_bug(__FUNCTION__, __LINE__, 'No configuration data found!');
1492 return decodeEntities($pageTitle);
1495 // Checks wethere there is a cache file there. This function is cached.
1496 function isTemplateCached ($template) {
1497 // Do we have cached this result?
1498 if (!isset($GLOBALS['template_cache'][$template])) {
1500 $FQFN = generateCacheFqfn($template);
1503 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1507 return $GLOBALS['template_cache'][$template];
1510 // Flushes non-flushed template cache to disk
1511 function flushTemplateCache ($template, $eval) {
1512 // Is this cache flushed?
1513 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1515 $FQFN = generateCacheFqfn($template);
1518 writeToFile($FQFN, $eval, true);
1522 // Reads a template cache
1523 function readTemplateCache ($template) {
1525 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1526 // This should not happen
1527 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1531 if (!isset($GLOBALS['template_eval'][$template])) {
1533 $FQFN = generateCacheFqfn($template);
1536 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1540 return $GLOBALS['template_eval'][$template];
1543 // Escapes quotes (default is only double-quotes)
1544 function escapeQuotes ($str, $single = false) {
1545 // Should we escape all?
1546 if ($single === true) {
1547 // Escape all (including null)
1548 $str = addslashes($str);
1550 // Remove escaping of single quotes
1551 $str = str_replace("\\'", "'", $str);
1553 // Escape only double-quotes but prevent double-quoting
1554 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1557 // Return the escaped string
1561 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1562 function escapeJavaScriptQuotes ($str) {
1563 // Replace all double-quotes and secure back-ticks
1564 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1570 // Send out mails depending on the 'mod/modes' combination
1571 // @TODO Lame description for this function
1572 function sendModeMails ($mod, $modes) {
1574 $content = array ();
1577 if (fetchUserData(getMemberId())) {
1578 // Extract salt from cookie
1579 $salt = substr(getSession('u_hash'), 0, -40);
1581 // Now let's compare passwords
1582 $hash = encodeHashForCookie(getUserData('password'));
1584 // Does the hash match or should we change it?
1585 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
1587 $content = getUserDataArray();
1589 // Clear/init the content variable
1590 $content['message'] = '';
1593 // @TODO Move this in a filter
1596 foreach ($modes as $mode) {
1598 case 'normal': break; // Do not add any special lines
1599 case 'email': // Email was changed!
1600 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . "\n";
1603 case 'password': // Password was changed
1604 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1608 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1609 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1614 if (isExtensionActive('country')) {
1615 // Replace code with description
1616 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1619 // Merge content with data from POST
1620 $content = merge_array($content, postRequestArray());
1623 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1625 if (isAdminNotificationEnabled()) {
1626 // The admin needs to be notified about a profile change
1627 $message_admin = 'admin_mydata_notify';
1628 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1631 $message_admin = '';
1635 // Set subject lines
1636 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1638 // Output success message
1639 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1642 default: // Unsupported module!
1643 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1644 $content['message'] = '<span class="bad">{--UNKNOWN_MODULE--}</span>';
1648 // Passwords mismatch
1649 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1652 // Could not load profile
1653 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1656 // Send email to user if required
1657 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1659 sendEmail($content['userid'], $sub_mem, $message);
1662 // Send only if no other error has occured
1663 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1665 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1666 } elseif (isAdminNotificationEnabled()) {
1667 // Cannot send mails to admin!
1668 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1671 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1675 displayMessage($content['message']);
1678 // Generates a 'selection box' from given array
1679 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '', $templateName = '') {
1681 $OUT = '<select name="' . $name . '" size="1" class="form_select">
1682 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1684 // Walk through all options
1685 foreach ($options as $option) {
1686 // Add the <option> entry from ...
1687 if (empty($optionContent)) {
1688 // Is a template name given?
1689 if (empty($templateName)) {
1690 // ... $name template
1691 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1693 // ... $templateName template
1694 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', true, $option);
1697 // ... direct HTML code
1698 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1702 // Finish selection box
1703 $OUT .= '</select>';
1707 'selection_box' => $OUT,
1710 // Load template and return it
1711 if (empty($templateName)) {
1712 // Use name from $name + $extraName
1713 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1715 // Use name from $templateName + $extraName
1716 return loadTemplate('select_' . $templateName . $extraName . '_box', true, $content);
1720 // Prepares the header for HTML output
1721 function loadHtmlHeader () {
1723 // 1.) pre_page_header (mainly loads the page_header template and includes
1724 // meta description)
1725 runFilterChain('pre_page_header');
1727 // Here can be something be added, but normally one of the two filters
1728 // around this line should do the job for you.
1730 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1731 // to close the head-tag)
1732 // Include more header data here
1733 runFilterChain('post_page_header');
1736 // Adds page header and footer to output array element
1737 function addPageHeaderFooter () {
1741 // Add them all together. This is maybe to simple
1742 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1743 // Add page part if set
1744 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1747 // Transfer $OUT to 'output'
1748 $GLOBALS['output'] = $OUT;
1751 // Generates meta description for current module and 'what' value
1752 function generateMetaDescriptionCode () {
1753 // Only include from guest area and if sql_patches has correct version
1754 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1755 // Construct dynamic description
1756 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1758 // Output it directly
1759 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1762 // Initialize referral system
1763 initReferralSystem();
1766 // Generates an FQFN for template cache from the given template name
1767 function generateCacheFqfn ($template, $mode = 'html') {
1769 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1770 // Generate the FQFN
1771 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1772 "%s_compiled/%s/%s.tpl.cache",
1780 return $GLOBALS['template_cache_fqfn'][$template];
1783 // "Fixes" null or empty string to count of dashes
1784 function fixNullEmptyToDashes ($str, $num) {
1785 // Use str as default
1789 if ((is_null($str)) || (trim($str) == '')) {
1791 $return = str_repeat('-', $num);
1794 // Return final string
1798 // Translates the "pool type" into human-readable
1799 function translatePoolType ($type) {
1800 // Return "translation"
1801 return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1804 // "Translates" given time unit
1805 function translateTimeUnit ($unit) {
1806 // Default is unknown
1807 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1812 $message = '{--TIME_UNIT_YEAR--}';
1816 $message = '{--TIME_UNIT_MONTH--}';
1820 $message = '{--TIME_UNIT_WEEK--}';
1824 $message = '{--TIME_UNIT_DAY--}';
1828 $message = '{--TIME_UNIT_HOUR--}';
1832 $message = '{--TIME_UNIT_MINUTE--}';
1835 case 's': // Seconds
1836 $message = '{--TIME_UNIT_SECOND--}';
1839 default: // Unknown value detected
1840 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1848 // Displays given message in admin_settings_saved template
1849 function displayMessage ($message, $return = false) {
1850 // Load the template
1851 return loadTemplate('admin_settings_saved', $return, $message);
1854 // Generates a selection box for (maybe) given gender
1855 function generateGenderSelectionBox ($selectedGender = '') {
1856 // Start the HTML code
1857 $out = '<select name="gender" size="1" class="form_select">';
1860 $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1863 $out .= '</select>';
1869 // Generates a selection box for given default value
1870 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
1872 $messageIds = array();
1874 // Generate message id array
1875 foreach ($unitArray as $unit) {
1877 $messageIds[] = translateTimeUnit($unit);
1880 // Start the HTML code
1881 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
1884 $out .= generateOptionList('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
1887 $out .= '</select>';
1893 // Function to add style tag (wether display:none/block)
1894 function addStyleMenuContent ($menuMode, $mainAction, $action) {
1895 // Do we have foo_menu_javascript enabled?
1896 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
1897 // Silently abort here, not enabled
1901 // Is action=mainAction?
1902 if ($action == $mainAction) {
1903 // Add "menu open" style
1904 return ' style="display:block"';
1906 return ' style="display:none"';
1910 // Function to add onclick attribute
1911 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
1912 // Do we have foo_menu_javascript enabled?
1913 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
1914 // Silently abort here, not enabled
1919 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
1925 //-----------------------------------------------------------------------------
1926 // Template helper functions for EL code
1927 //-----------------------------------------------------------------------------
1929 // Color-switch helper function
1930 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1932 if (!isset($GLOBALS['color_switch'][$template])) {
1934 initTemplateColorSwitch($template);
1935 } elseif ($clear === false) {
1936 // Switch color if called from loadTemplate()
1937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1938 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1941 // Return CSS class name
1942 if ($return === true) {
1943 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1944 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1948 // Helper function for extension registration link
1949 function doTemplateExtensionRegistrationLink ($template, $clear, $ext_name) {
1950 // Default is all non-productive
1951 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
1953 // Is the given extension non-productive?
1954 if (isExtensionProductive($ext_name)) {
1956 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1963 // Helper function to create bonus mail admin links
1964 function doTemplateAdminBonusMailLinks ($template, $clear, $bonusId) {
1965 // Call the inner function
1966 return generateAdminMailLinks('bid', $bonusId);
1969 // Helper function to create member mail admin links
1970 function doTemplateAdminMemberMailLinks ($template, $clear, $mailId) {
1971 // Call the inner function
1972 return generateAdminMailLinks('mid', $mailId);
1975 // Helper function to create a selection box for YES/NO configuration entries
1976 function doTemplateConfigurationYesNoSelectionBox ($template, $clear, $configEntry) {
1977 // Default is a "missing entry" warning
1978 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
1980 // Generate the HTML code
1981 if (isConfigEntrySet($configEntry)) {
1982 // Configuration entry is found
1983 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
1984 {%config,generateYesNoOptionList=' . $configEntry . '%}
1992 // Helper function to create a selection box for YES/NO form fields
1993 function doTemplateYesNoSelectionBox ($template, $clear, $formField) {
1994 // Generate the HTML code
1995 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
1996 {%pipe,generateYesNoOptionList%}
2003 // Helper function to create a selection box for YES/NO form fields, by NO is default
2004 function doTemplateNoYesSelectionBox ($template, $clear, $formField) {
2005 // Generate the HTML code
2006 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2007 {%pipe,generateYesNoOptionList=N%}
2014 // Helper function to add extra content for member area (module=login)
2015 function doTemplateMemberFooterExtras ($template, $clear) {
2016 // Is a member logged in?
2018 // This shall not happen
2019 debug_report_bug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2023 $filterData = array(
2024 'userid' => getMemberId(),
2025 'template' => $template,
2029 // Run the filter chain
2030 $filterData = runFilterChain('member_footer_extras', $filterData);
2033 return $filterData['output'];