2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 04/04/2009 *
4 * =================== Last change: 04/04/2009 *
6 * -------------------------------------------------------------------- *
7 * File : template-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Template functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Template-Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Wrapper until we merged to the EL branch
46 function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
47 return compileCode($code, false, true, $full);
50 // Setter for 'is_template_html'
51 function enableTemplateHtml ($enable = true) {
52 $GLOBALS['is_template_html'] = (bool) $enable;
55 // Checks wether the template is HTML or not by previously set flag
57 function isTemplateHtml () {
58 // Is the output_mode other than 0 (HTML), then no comments are enabled
59 if (getScriptOutputMode() != 0) {
64 return $GLOBALS['is_template_html'];
68 // Wrapper for writing debug informations to the browser
69 function debugOutput ($message) {
70 outputHtml('<div class="debug_message">' . $message . '</div>');
73 // "Fixes" an empty string into three dashes (use for templates)
74 function fixEmptyContentToDashes ($str) {
78 // Is the string empty?
79 if (empty($str)) $str = '---';
85 // Color-switch helper function
86 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
88 if (!isset($GLOBALS['color_switch'][$template])) {
90 initTemplateColorSwitch($template);
91 } elseif ($clear === false) {
92 // Switch color if called from loadTemplate()
93 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
94 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
97 // Return CSS class name
98 if ($return === true) {
99 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
100 return 'switch_sw' . $GLOBALS['color_switch'][$template];
105 function initTemplateColorSwitch ($template) {
106 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
107 $GLOBALS['color_switch'][$template] = 2;
110 // "Getter" for color switch code
111 function getColorSwitchCode ($template) {
113 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
119 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
120 function outputHtml ($htmlCode, $newLine = true) {
122 if (!isset($GLOBALS['output'])) {
123 $GLOBALS['output'] = '';
126 // Do we have HTML-Code here?
127 if (!empty($htmlCode)) {
128 // Yes, so we handle it as you have configured
129 switch (getOutputMode()) {
131 // That's why you don't need any \n at the end of your HTML code... :-)
132 if (getPhpCaching() == 'on') {
133 // Output into PHP's internal buffer
134 outputRawCode($htmlCode);
136 // That's why you don't need any \n at the end of your HTML code... :-)
137 if ($newLine === true) print("\n");
139 // Render mode for old or lame servers...
140 $GLOBALS['output'] .= $htmlCode;
142 // That's why you don't need any \n at the end of your HTML code... :-)
143 if ($newLine === true) $GLOBALS['output'] .= "\n";
148 // If we are switching from render to direct output rendered code
149 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
151 // The same as above... ^
152 outputRawCode($htmlCode);
153 if ($newLine === true) print("\n");
157 // Huh, something goes wrong or maybe you have edited config.php ???
158 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
161 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
162 // Output cached HTML code
163 $GLOBALS['output'] = ob_get_contents();
165 // Clear output buffer for later output if output is found
166 if (!empty($GLOBALS['output'])) {
170 // Send all HTTP headers
173 // Compile and run finished rendered HTML code
174 compileFinalOutput();
176 // Output code here, DO NOT REMOVE! ;-)
177 outputRawCode($GLOBALS['output']);
178 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
179 // Send all HTTP headers
182 // Compile and run finished rendered HTML code
183 compileFinalOutput();
185 // Output code here, DO NOT REMOVE! ;-)
186 outputRawCode($GLOBALS['output']);
188 // And flush all headers
193 // Compiles the final output
194 function compileFinalOutput () {
195 // Add page header and footer
196 addPageHeaderFooter();
198 // Do the final compilation
199 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
201 // Extension 'rewrite' installed?
202 if ((isExtensionActive('rewrite')) && (getScriptOutputMode() != 1)) {
203 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
207 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
208 // Compress it for HTTP gzip
209 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
212 sendHeader('Content-Encoding: gzip');
213 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
214 // Compress it for HTTP deflate
215 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
218 sendHeader('Content-Encoding: deflate');
222 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
228 // Main compilation loop
229 function doFinalCompilation ($code, $insertComments = true) {
230 // Insert comments? (Only valid with HTML templates, of course)
231 enableTemplateHtml($insertComments);
237 while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
238 // Init common variables
243 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
244 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code))) . '";';
245 //* DEBUG: */ if (!$insertComments) print('<pre>'.linenumberCode($eval).'</pre>');
247 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
249 // Was that eval okay?
250 if (empty($newContent)) {
251 // Something went wrong!
252 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
262 // Return the compiled code
266 // Output the raw HTML code
267 function outputRawCode ($htmlCode) {
268 // Output stripped HTML code to avoid broken JavaScript code, etc.
269 print(str_replace('{BACK}', "\\", $htmlCode));
271 // Flush the output if only getPhpCaching() is not 'on'
272 if (getPhpCaching() != 'on') {
278 // Load a template file and return it's content (only it's name; do not use ' or ")
279 function loadTemplate ($template, $return = false, $content = array()) {
280 // @TODO Remove this sanity-check if all is fine
281 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
283 // Set current template
284 $GLOBALS['current_template'] = $template;
287 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
288 // Evaluate the cache
289 eval(readTemplateCache($template));
290 } elseif (!isset($GLOBALS['template_eval'][$template])) {
291 // Make all template names lowercase
292 $template = strtolower($template);
296 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
299 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
300 $extraPath = detectExtraTemplatePath($template);;
302 ////////////////////////
303 // Generate file name //
304 ////////////////////////
305 $FQFN = $basePath . $extraPath . $template . '.tpl';
307 // Does the special template exists?
308 if (!isFileReadable($FQFN)) {
309 // Reset to default template
310 $FQFN = $basePath . $template . '.tpl';
313 // Now does the final template exists?
314 if (isFileReadable($FQFN)) {
315 // Count the template load
316 incrementConfigEntry('num_templates');
318 // The local file does exists so we load it. :)
319 $GLOBALS['tpl_content'] = readFromFile($FQFN);
321 // Do we have to compile the code?
323 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
324 // Normal HTML output?
325 if (getScriptOutputMode() == '0') {
326 // Add surrounding HTML comments to help finding bugs faster
327 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
329 // Prepare eval() command
330 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
331 } elseif (substr($template, 0, 3) == 'js_') {
332 // JavaScripts don't like entities and timings
333 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
335 // Prepare eval() command, other output doesn't like entities, maybe
336 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
339 // Add surrounding HTML comments to help finding bugs faster
340 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
341 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
343 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
344 // Only admins shall see this warning or when installation mode is active
345 $ret = '<div class="para">
346 <span class="guest_failed">{--TEMPLATE_404--}</span>
352 {--TEMPLATE_CONTENT--}
353 <pre>' . print_r($content, true) . '</pre>
357 $GLOBALS['template_eval'][$template] = '404';
362 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
364 eval($GLOBALS['template_eval'][$template]);
367 // Do we have some content to output or return?
369 // Not empty so let's put it out! ;)
370 if ($return === true) {
371 // Return the HTML code
377 } elseif (isDebugModeEnabled()) {
378 // Warning, empty output!
379 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
383 // Detects the extra template path from given template name
384 function detectExtraTemplatePath ($template) {
389 if (!isset($GLOBALS['extra_path'][$template])) {
390 // Check for admin/guest/member/etc. templates
391 if (substr($template, 0, 6) == 'admin_') {
392 // Admin template found
393 $extraPath = 'admin/';
394 } elseif (substr($template, 0, 6) == 'guest_') {
395 // Guest template found
396 $extraPath = 'guest/';
397 } elseif (substr($template, 0, 7) == 'member_') {
398 // Member template found
399 $extraPath = 'member/';
400 } elseif (substr($template, 0, 7) == 'select_') {
401 // Selection template found
402 $extraPath = 'select/';
403 } elseif (substr($template, 0, 8) == 'install_') {
404 // Installation template found
405 $extraPath = 'install/';
406 } elseif (substr($template, 0, 4) == 'ext_') {
407 // Extension template found
409 } elseif (substr($template, 0, 3) == 'la_') {
410 // 'Logical-area' template found
412 } elseif (substr($template, 0, 3) == 'js_') {
413 // JavaScript template found
415 } elseif (substr($template, 0, 5) == 'menu_') {
416 // Menu template found
417 $extraPath = 'menu/';
419 // Test for extension
420 $test = substr($template, 0, strpos($template, '_'));
422 // Probe for valid extension name
423 if (isExtensionNameValid($test)) {
424 // Set extra path to extension's name
425 $extraPath = $test . '/';
430 $GLOBALS['extra_path'][$template] = $extraPath;
434 return $GLOBALS['extra_path'][$template];
437 // Loads an email template and compiles it
438 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
441 // Make sure all template names are lowercase!
442 $template = strtolower($template);
444 // Is content an array?
445 if (is_array($content)) {
446 // Add expiration to array
447 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
448 // Will never expire!
449 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
450 } elseif (isConfigEntrySet('auto_purge')) {
451 // Create nice date string
452 $content['expiration'] = createFancyTime(getAutoPurge());
455 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
461 if ((isValidUserId($userid)) && (is_array($content))) {
462 // If nickname extension is installed, fetch nickname as well
463 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
466 fetchUserData($userid, 'nickname');
468 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
470 fetchUserData($userid);
473 // Merge data if valid
474 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
475 if (isUserDataValid()) {
476 $content = merge_array($content, getUserDataArray());
478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
482 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
485 $extraPath = detectExtraTemplatePath($template);
487 // Generate full FQFN
488 $FQFN = $basePath . $extraPath . $template . '.tpl';
490 // Does the special template exists?
491 if (!isFileReadable($FQFN)) {
492 // Reset to default template
493 $FQFN = $basePath . $template . '.tpl';
496 // Now does the final template exists?
498 if (isFileReadable($FQFN)) {
499 // The local file does exists so we load it. :)
500 $GLOBALS['tpl_content'] = readFromFile($FQFN);
503 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
504 eval($GLOBALS['tpl_content']);
505 } elseif (!empty($template)) {
506 // Template file not found!
507 $newContent = '<div class="para">
508 {--TEMPLATE_404--}: ' . $template . '
511 {--TEMPLATE_CONTENT--}
512 <pre>' . print_r($content, true) . '</pre>
514 <pre>' . print_r($DATA, true) . '</pre>
517 // Debug mode not active? Then remove the HTML tags
518 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
520 // No template name supplied!
521 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
524 // Is there some content?
525 if (empty($newContent)) {
527 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
529 // Add last error if the required function exists
530 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
533 // Remove content and data
541 // "Getter" for menu CSS classes, mainly used in templates
542 function getMenuCssClasses ($data) {
543 // $data needs to be converted into an array
544 $content = explode('|', $data);
546 // Non-existent index 2 will happen in menu blocks
547 if (!isset($content[2])) $content[2] = '';
549 // Re-construct the array: 0=visible,1=locked,2=prefix
550 $content['visible'] = $content[0];
551 $content['locked'] = $content[1];
553 // Call our "translator" function
554 $content = translateMenuVisibleLocked($content, $content[2]);
556 // Return CSS classes
557 return ($content['visible_css'] . ' ' . $content['locked_css']);
560 // Generate XHTML code for the CAPTCHA
561 function generateCaptchaCode ($code, $type, $DATA, $userid) {
562 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
565 // Compiles the given HTML/mail code
566 function compileCode ($code, $simple = false, $constants = true, $full = true) {
567 // Is the code a string?
568 if (!is_string($code)) {
569 // Silently return it
574 $startCompile = microtime(true);
577 $code = compileRawCode($code, $simple, $constants, $full);
580 $compiled = microtime(true);
582 // Add timing if enabled
583 if (isTemplateHtml()) {
584 // Add timing, this should be disabled in
585 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
588 // Return compiled code
592 // Compiles the code (use compileCode() only for HTML because of the comments)
593 // @TODO $simple/$constants are deprecated
594 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
595 // Is the code a string?
596 if (!is_string($code)) {
597 // Silently return it
601 // Init replacement-array with smaller set of security characters
602 $secChars = $GLOBALS['url_chars'];
604 // Select full set of chars to replace when we e.g. want to compile URLs
605 if ($full === true) $secChars = $GLOBALS['security_chars'];
607 // Compile more through a filter
608 $code = runFilterChain('compile_code', $code);
610 // Compile message strings
611 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
613 // Compile QUOT and other non-HTML codes
614 foreach ($secChars['to'] as $k => $to) {
615 // Do the reversed thing as in inc/libs/security_functions.php
616 $code = str_replace($to, $secChars['from'][$k], $code);
619 // Find $content[bla][blub] entries
620 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
621 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
623 // Are some matches found?
624 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
625 // Replace all matches
626 $matchesFound = array();
627 foreach ($matches[0] as $key => $match) {
628 // Fuzzy look has failed by default
631 // Fuzzy look on match if already found
632 foreach ($matchesFound as $found => $set) {
634 $test = substr($found, 0, strlen($match));
636 // Does this entry exist?
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
638 if ($test == $match) {
640 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
647 if ($fuzzyFound === true) continue;
649 // Take all string elements
650 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
651 // Replace it in the code
652 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
653 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
654 $code = str_replace($match, '".' . $newMatch . '."', $code);
655 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
656 $matchesFound[$match] = 1;
657 } elseif (!isset($matchesFound[$match])) {
659 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
660 $code = str_replace($match, '".' . $match . '."', $code);
661 $matchesFound[$match] = 1;
671 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
675 // This is a yes/no selection only!
676 if ($id > 0) $prefix .= '[' . $id . ']';
677 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
679 // Begin with regular selection box here
680 if (!empty($prefix)) $prefix .= '_';
682 if ($id > 0) $type2 .= '[' . $id . ']';
683 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
688 for ($idx = 1; $idx < 32; $idx++) {
689 $OUT .= '<option value="' . $idx . '"';
690 if ($default == $idx) $OUT .= ' selected="selected"';
691 $OUT .= '>' . $idx . '</option>';
695 case 'month': // Month
696 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
697 $OUT .= '<option value="' . $idx . '"';
698 if ($default == $idx) $OUT .= ' selected="selected"';
699 $OUT .= '>' . $descr . '</option>';
707 // Use configured min age or fixed?
708 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
710 $startYear = $year - getConfig('min_age');
713 $startYear = $year - 16;
716 // Calculate earliest year (100 years old people can still enter Internet???)
717 $minYear = $year - 100;
719 // Check if the default value is larger than minimum and bigger than actual year
720 if (($default > $minYear) && ($default >= $year)) {
721 for ($idx = $year; $idx < ($year + 11); $idx++) {
722 $OUT .= '<option value="' . $idx . '"';
723 if ($default == $idx) $OUT .= ' selected="selected"';
724 $OUT .= '>' . $idx . '</option>';
726 } elseif ($default == -1) {
727 // Current year minus 1
728 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
729 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
732 // Get current year and subtract the configured minimum age
733 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
734 // Calculate earliest year depending on extension version
735 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
736 // Use configured minimum age
737 $year = getYear() - getConfig('min_age');
739 // Use fixed 16 years age
740 $year = getYear() - 16;
743 // Construct year selection list
744 for ($idx = $minYear; $idx <= $year; $idx++) {
745 $OUT .= '<option value="' . $idx . '"';
746 if ($default == $idx) $OUT .= ' selected="selected"';
747 $OUT .= '>' . $idx . '</option>';
754 for ($idx = 0; $idx < 60; $idx+=5) {
755 if (strlen($idx) == 1) $idx = '0' . $idx;
756 $OUT .= '<option value="' . $idx . '"';
757 if ($default == $idx) $OUT .= ' selected="selected"';
758 $OUT .= '>' . $idx . '</option>';
763 for ($idx = 0; $idx < 24; $idx++) {
764 if (strlen($idx) == 1) $idx = '0' . $idx;
765 $OUT .= '<option value="' . $idx . '"';
766 if ($default == $idx) $OUT .= ' selected="selected"';
767 $OUT .= '>' . $idx . '</option>';
772 $OUT .= '<option value="Y"';
773 if ($default == 'Y') $OUT .= ' selected="selected"';
774 $OUT .= '>{--YES--}</option><option value="N"';
775 if ($default != 'Y') $OUT .= ' selected="selected"';
776 $OUT .= '>{--NO--}</option>';
783 // Insert the code in $img_code into jpeg or PNG image
784 function generateImageOrCode ($img_code, $headerSent = true) {
785 // Is the code size oversized or shouldn't we display it?
786 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
787 // Stop execution of function here because of over-sized code length
788 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
789 } elseif ($headerSent === false) {
790 // Return an HTML code here
791 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
795 $img = sprintf("%s/theme/%s/images/code_bg.%s",
798 getConfig('img_type')
802 if (isFileReadable($img)) {
804 switch (getConfig('img_type')) {
806 // Okay, load image and hide all errors
807 $image = imagecreatefromjpeg($img);
811 // Okay, load image and hide all errors
812 $image = imagecreatefrompng($img);
816 // Exit function here
817 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
821 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
822 $text_color = imagecolorallocate($image, 0, 0, 0);
824 // Insert code into image
825 imagestring($image, 5, 14, 2, $img_code, $text_color);
828 sendHeader('Content-Type: image/' . getConfig('img_type'));
830 // Output image with matching image factory
831 switch (getConfig('img_type')) {
832 case 'jpg': imagejpeg($image); break;
833 case 'png': imagepng($image); break;
836 // Remove image from memory
837 imagedestroy($image);
839 // Create selection box or array of splitted timestamp
840 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
841 // Do not continue if ONE_DAY is absend
842 if (!isConfigEntrySet('ONE_DAY')) {
843 // And return the timestamp itself or empty array
844 if ($return_array === true) {
851 // Calculate 2-seconds timestamp
852 $stamp = round($timestamp);
853 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
855 // Do we have a leap year?
857 $TEST = getYear() / 4;
859 $M2 = getMonth(time() + $timestamp);
861 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
862 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
864 // First of all years...
865 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
866 //* DEBUG: */ debugOutput('Y=' . $Y);
868 $M = abs(floor($timestamp / 2628000 - $Y * 12));
869 //* DEBUG: */ debugOutput('M=' . $M);
871 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
872 //* DEBUG: */ debugOutput('W=' . $W);
874 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
875 //* DEBUG: */ debugOutput('D=' . $D);
877 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
878 //* DEBUG: */ debugOutput('h=' . $h);
880 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
881 //* DEBUG: */ debugOutput('m=' . $m);
882 // And at last seconds...
883 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
884 //* DEBUG: */ debugOutput('s=' . $s);
886 // Is seconds zero and time is < 60 seconds?
887 if (($s == '0') && ($timestamp < 60)) {
889 $s = round($timestamp);
893 // Now we convert them in seconds...
896 // Just put all data in an array for later use
908 $OUT = '<div align="' . $align . '">';
909 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
912 if (isInString('Y', $display) || (empty($display))) {
913 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
916 if (isInString('M', $display) || (empty($display))) {
917 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
920 if (isInString('W', $display) || (empty($display))) {
921 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
924 if (isInString('D', $display) || (empty($display))) {
925 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
928 if (isInString('h', $display) || (empty($display))) {
929 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
932 if (isInString('m', $display) || (empty($display))) {
933 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
936 if (isInString('s', $display) || (empty($display))) {
937 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
943 if (isInString('Y', $display) || (empty($display))) {
944 // Generate year selection
945 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
946 for ($idx = 0; $idx <= 10; $idx++) {
947 $OUT .= '<option class="mini_select" value="' . $idx . '"';
948 if ($idx == $Y) $OUT .= ' selected="selected"';
949 $OUT .= '>' . $idx . '</option>';
951 $OUT .= '</select></td>';
953 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
956 if (isInString('M', $display) || (empty($display))) {
957 // Generate month selection
958 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
959 for ($idx = 0; $idx <= 11; $idx++) {
960 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
961 if ($idx == $M) $OUT .= ' selected="selected"';
962 $OUT .= '>' . $idx . '</option>';
964 $OUT .= '</select></td>';
966 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
969 if (isInString('W', $display) || (empty($display))) {
970 // Generate week selection
971 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
972 for ($idx = 0; $idx <= 4; $idx++) {
973 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
974 if ($idx == $W) $OUT .= ' selected="selected"';
975 $OUT .= '>' . $idx . '</option>';
977 $OUT .= '</select></td>';
979 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
982 if (isInString('D', $display) || (empty($display))) {
983 // Generate day selection
984 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
985 for ($idx = 0; $idx <= 31; $idx++) {
986 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
987 if ($idx == $D) $OUT .= ' selected="selected"';
988 $OUT .= '>' . $idx . '</option>';
990 $OUT .= '</select></td>';
992 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
995 if (isInString('h', $display) || (empty($display))) {
996 // Generate hour selection
997 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
998 for ($idx = 0; $idx <= 23; $idx++) {
999 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1000 if ($idx == $h) $OUT .= ' selected="selected"';
1001 $OUT .= '>' . $idx . '</option>';
1003 $OUT .= '</select></td>';
1005 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1008 if (isInString('m', $display) || (empty($display))) {
1009 // Generate minute selection
1010 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1011 for ($idx = 0; $idx <= 59; $idx++) {
1012 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1013 if ($idx == $m) $OUT .= ' selected="selected"';
1014 $OUT .= '>' . $idx . '</option>';
1016 $OUT .= '</select></td>';
1018 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1021 if (isInString('s', $display) || (empty($display))) {
1022 // Generate second selection
1023 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1024 for ($idx = 0; $idx <= 59; $idx++) {
1025 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1026 if ($idx == $s) $OUT .= ' selected="selected"';
1027 $OUT .= '>' . $idx . '</option>';
1029 $OUT .= '</select></td>';
1031 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1038 // Return generated HTML code
1042 // Generate a list of administrative links to a given userid
1043 function generateMemberAdminActionLinks ($userid) {
1044 // Make sure userid is a number
1045 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1047 // Define all main targets
1048 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1051 $status = getFetchedUserData('userid', $userid, 'status');
1053 // Begin of navigation links
1056 foreach ($targetArray as $tar) {
1057 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1058 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1059 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1060 // Locked accounts shall be unlocked
1061 $OUT .= 'UNLOCK_USER';
1063 // All other status is fine
1064 $OUT .= strtoupper($tar);
1066 $OUT .= '_TITLE--}">{--ADMIN_';
1067 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1068 // Locked accounts shall be unlocked
1069 $OUT .= 'UNLOCK_USER';
1071 // All other status is fine
1072 $OUT .= strtoupper($tar);
1074 $OUT .= '--}</a></span>|';
1077 // Finish navigation link
1078 $OUT = substr($OUT, 0, -1) . ']';
1084 // Generate an email link
1085 function generateEmailLink ($email, $table = 'admins') {
1086 // Default email link (INSECURE! Spammer can read this by harvester programs)
1087 $EMAIL = 'mailto:' . $email;
1089 // Check for several extensions
1090 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1091 // Create email link for contacting admin in guest area
1092 $EMAIL = generateAdminEmailLink($email);
1093 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1094 // Create email link for contacting a member within admin area (or later in other areas, too?)
1095 $EMAIL = generateUserEmailLink($email, 'admin');
1096 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1097 // Create email link to contact sponsor within admin area (or like the link above?)
1098 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1101 // Shall I close the link when there is no admin?
1102 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1104 // Return email link
1108 // Output error messages in a fasioned way and die...
1109 function app_die ($F, $L, $message) {
1110 // Check if Script is already dieing and not let it kill itself another 1000 times
1111 if (!isset($GLOBALS['app_died'])) {
1112 // Make sure, that the script realy realy diese here and now
1113 $GLOBALS['app_died'] = true;
1115 // Set content type as text/html
1116 setContentType('text/html');
1119 loadIncludeOnce('inc/header.php');
1121 // Rewrite message for output
1122 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1124 // Load the message template
1125 loadTemplate('app_die_message', false, $message);
1128 loadIncludeOnce('inc/footer.php');
1130 // Script tried to kill itself twice
1131 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1135 // Display parsing time and number of SQL queries in footer
1136 function displayParsingTime () {
1137 // Is the timer started?
1138 if (!isset($GLOBALS['startTime'])) {
1144 $endTime = microtime(true);
1146 // "Explode" both times
1147 $start = explode(' ', $GLOBALS['startTime']);
1148 $end = explode(' ', $endTime);
1149 $runTime = $end[0] - $start[0];
1150 if ($runTime < 0) $runTime = '0';
1153 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1155 'run_time' => $runTime,
1156 'sql_time' => (getConfig('sql_time') * 1000),
1159 // Load the template
1160 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1163 // Output a debug backtrace to the user
1164 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1165 // Is this already called?
1166 if (isset($GLOBALS[__FUNCTION__])) {
1168 print 'Message:' . $message . '<br />Backtrace:<pre>';
1169 debug_print_backtrace();
1173 // Set this function as called
1174 $GLOBALS[__FUNCTION__] = true;
1179 // Is the optional message set?
1180 if (!empty($message)) {
1182 $debug = sprintf("Note: %s<br />\n",
1186 // @TODO Add a little more infos here
1187 logDebugMessage($F, $L, strip_tags($message));
1191 $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>';
1192 $debug .= debug_get_printable_backtrace();
1194 $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
1195 $debug .= '<div>Thank you for finding bugs.</div>';
1197 // Send an email? (e.g. not wanted for evaluation errors)
1198 if (($sendEmail === true) && (!isInstallationPhase())) {
1201 'message' => trim($message),
1202 'backtrace' => trim(debug_get_mailable_backtrace())
1205 // Send email to webmaster
1206 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1210 app_die($F, $L, $debug);
1213 // Compile characters which are allowed in URLs
1214 function compileUriCode ($code, $simple = true) {
1215 // Compile constants
1216 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1218 // Compile QUOT and other non-HTML codes
1219 $code = str_replace('{DOT}', '.',
1220 str_replace('{SLASH}', '/',
1221 str_replace('{QUOT}', "'",
1222 str_replace('{DOLLAR}', '$',
1223 str_replace('{OPEN_ANCHOR}', '(',
1224 str_replace('{CLOSE_ANCHOR}', ')',
1225 str_replace('{OPEN_SQR}', '[',
1226 str_replace('{CLOSE_SQR}', ']',
1227 str_replace('{PER}', '%',
1231 // Return compiled code
1235 // Handle message codes from URL
1236 function handleCodeMessage () {
1237 if (isGetRequestParameterSet('code')) {
1238 // Default extension is 'unknown'
1241 // Is extension given?
1242 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1244 // Convert the 'code' parameter from URL to a human-readable message
1245 $message = getMessageFromErrorCode(getRequestParameter('code'));
1247 // Load message template
1248 loadTemplate('message', false, $message);
1252 // Generates a 'extension foo inactive' message
1253 function generateExtensionInactiveMessage ($ext_name) {
1254 // Is the extension empty?
1255 if (empty($ext_name)) {
1256 // This should not happen
1257 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1261 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1263 // Is an admin logged in?
1265 // Then output admin message
1266 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1269 // Return prepared message
1273 // Generates a 'extension foo not installed' message
1274 function generateExtensionNotInstalledMessage ($ext_name) {
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 = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1284 // Is an admin logged in?
1286 // Then output admin message
1287 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1290 // Return prepared message
1294 // Generates a message depending on if the extension is not installed or not
1296 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1300 // Is the extension not installed or just deactivated?
1301 switch (isExtensionInstalled($ext_name)) {
1302 case true; // Deactivated!
1303 $message = generateExtensionInactiveMessage($ext_name);
1306 case false; // Not installed!
1307 $message = generateExtensionNotInstalledMessage($ext_name);
1310 default: // Should not happen!
1311 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1312 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1316 // Return the message
1320 // Print code with line numbers
1321 function linenumberCode ($code) {
1322 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1323 $count_lines = count($codeE);
1325 $r = 'Line | Code:<br />';
1326 foreach($codeE as $line => $c) {
1327 $r .= '<div class="line"><span class="linenum">';
1328 if ($count_lines == 1) {
1331 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1336 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1339 return '<div class="code">' . $r . '</div>';
1342 // Determines the right page title
1343 function determinePageTitle () {
1344 // Config and database connection valid?
1345 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1349 // Title decoration enabled?
1350 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1352 // Do we have some extra title?
1353 if (isExtraTitleSet()) {
1355 $TITLE .= getExtraTitle() . ' by ';
1359 $TITLE .= getMainTitle();
1361 // Add title of module? (middle decoration will also be added!)
1362 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1363 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1366 // Add title from what file
1368 if (getModule() == 'login') $mode = 'member';
1369 elseif (getModule() == 'index') $mode = 'guest';
1370 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1372 // Add title decorations? (right)
1373 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1375 // Remember title in constant for the template
1376 $pageTitle = $TITLE;
1377 } elseif ((isInstalled()) && (isAdminRegistered())) {
1378 // Installed, admin registered but no ext-sql_patches
1379 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1380 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1381 // Installed but no admin registered
1382 $pageTitle = '{--SETUP_OF_MAILER--}';
1383 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1384 // Installation mode
1385 $pageTitle = '{--INSTALLATION_OF_MAILER--}';
1387 // Configuration not found!
1388 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1390 // Do not add the fatal message in installation mode
1391 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1395 return decodeEntities($pageTitle);
1398 // Checks wethere there is a cache file there. This function is cached.
1399 function isTemplateCached ($template) {
1400 // Do we have cached this result?
1401 if (!isset($GLOBALS['template_cache'][$template])) {
1403 $FQFN = generateCacheFqfn($template);
1406 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1410 return $GLOBALS['template_cache'][$template];
1413 // Flushes non-flushed template cache to disk
1414 function flushTemplateCache ($template, $eval) {
1415 // Is this cache flushed?
1416 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1418 $FQFN = generateCacheFqfn($template);
1421 writeToFile($FQFN, $eval, true);
1425 // Reads a template cache
1426 function readTemplateCache ($template) {
1428 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1429 // This should not happen
1430 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1434 if (!isset($GLOBALS['template_eval'][$template])) {
1436 $FQFN = generateCacheFqfn($template);
1439 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1443 return $GLOBALS['template_eval'][$template];
1446 // Escapes quotes (default is only double-quotes)
1447 function escapeQuotes ($str, $single = false) {
1448 // Should we escape all?
1449 if ($single === true) {
1450 // Escape all (including null)
1451 $str = addslashes($str);
1453 // Remove escaping of single quotes
1454 $str = str_replace("\'", "'", $str);
1456 // Escape only double-quotes but prevent double-quoting
1457 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1460 // Return the escaped string
1464 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1465 function escapeJavaScriptQuotes ($str) {
1466 // Replace all double-quotes and secure back-ticks
1467 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1473 // Send out mails depending on the 'mod/modes' combination
1474 // @TODO Lame description for this function
1475 function sendModeMails ($mod, $modes) {
1477 if (fetchUserData(getMemberId())) {
1478 // Extract salt from cookie
1479 $salt = substr(getSession('u_hash'), 0, -40);
1481 // Now let's compare passwords
1482 $hash = encodeHashForCookie(getUserData('password'));
1484 // Does the hash match or should we change it?
1485 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1487 $content = getUserDataArray();
1489 // Clear/init the content variable
1490 $content['message'] = '';
1493 // @TODO Move this in a filter
1496 foreach ($modes as $mode) {
1498 case 'normal': break; // Do not add any special lines
1499 case 'email': // Email was changed!
1500 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1503 case 'pass': // Password was changed
1504 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1508 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1509 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1514 if (isExtensionActive('country')) {
1515 // Replace code with description
1516 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1519 // Merge content with data from POST
1520 $content = merge_array($content, postRequestArray());
1523 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1525 if (isAdminNotificationEnabled()) {
1526 // The admin needs to be notified about a profile change
1527 $message_admin = 'admin_mydata_notify';
1528 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1531 $message_admin = '';
1535 // Set subject lines
1536 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1538 // Output success message
1539 $content = '<span class="member_done">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1542 default: // Unsupported module!
1543 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1544 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
1548 // Passwords mismatch
1549 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
1552 // Could not load profile
1553 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1556 // Send email to user if required
1557 if ((!empty($sub_mem)) && (!empty($message))) {
1559 sendEmail($content['email'], $sub_mem, $message);
1562 // Send only if no other error has occured
1563 if (empty($content)) {
1564 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1566 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1567 } elseif (isAdminNotificationEnabled()) {
1568 // Cannot send mails to admin!
1569 $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1572 $content = '<span class="member_done">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1577 loadTemplate('admin_settings_saved', false, $content);
1580 // Generates a 'selection box' from given array
1581 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1583 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
1584 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1586 // Walk through all options
1587 foreach ($options as $option) {
1588 // Add the <option> entry
1589 if (empty($optionContent)) {
1590 // ... from template
1591 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1594 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1598 // Finish selection box
1599 $OUT .= '</select>';
1603 'selection_box' => $OUT,
1606 // Load template and return it
1607 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1610 // Prepares the header for HTML output
1611 function loadHtmlHeader () {
1613 // 1.) pre_page_header (mainly loads the page_header template and includes
1614 // meta description)
1615 runFilterChain('pre_page_header');
1617 // Here can be something be added, but normally one of the two filters
1618 // around this line should do the job for you.
1620 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1621 // to close the head-tag)
1622 // Include more header data here
1623 runFilterChain('post_page_header');
1626 // Adds page header and footer to output array element
1627 function addPageHeaderFooter () {
1631 // Add them all together. This is maybe to simple
1632 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1633 // Add page part if set
1634 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1637 // Transfer $OUT to 'output'
1638 $GLOBALS['output'] = $OUT;
1641 // Generates meta description for current module and 'what' value
1642 function generateMetaDescriptionCode () {
1643 // Only include from guest area and if sql_patches has correct version
1644 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1645 // Construct dynamic description
1646 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1648 // Output it directly
1649 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1653 unset($GLOBALS['ref_level']);
1656 // Generates an FQFN for template cache from the given template name
1657 function generateCacheFqfn ($template, $mode = 'html') {
1659 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1660 // Generate the FQFN
1661 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1662 "%s_compiled/%s/%s.tpl.cache",
1670 return $GLOBALS['template_cache_fqfn'][$template];
1673 // "Fixes" null or empty string to count of dashes
1674 function fixNullEmptyToDashes ($str, $num) {
1675 // Use str as default
1679 if ((is_null($str)) || (trim($str) == '')) {
1681 $return = str_repeat('-', $num);
1684 // Return final string