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 (!isHtmlOutputMode()) {
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 = '---';
86 function initTemplateColorSwitch ($template) {
87 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
88 $GLOBALS['color_switch'][$template] = 2;
91 // "Getter" for color switch code
92 function getColorSwitchCode ($template) {
94 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
100 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
101 function outputHtml ($htmlCode, $newLine = true) {
103 if (!isset($GLOBALS['output'])) {
104 $GLOBALS['output'] = '';
107 // Do we have HTML-Code here?
108 if (!empty($htmlCode)) {
109 // Yes, so we handle it as you have configured
110 switch (getOutputMode()) {
112 // That's why you don't need any \n at the end of your HTML code... :-)
113 if (getPhpCaching() == 'on') {
114 // Output into PHP's internal buffer
115 outputRawCode($htmlCode);
117 // That's why you don't need any \n at the end of your HTML code... :-)
118 if ($newLine === true) print("\n");
120 // Render mode for old or lame servers...
121 $GLOBALS['output'] .= $htmlCode;
123 // That's why you don't need any \n at the end of your HTML code... :-)
124 if ($newLine === true) $GLOBALS['output'] .= "\n";
129 // If we are switching from render to direct output rendered code
130 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
132 // The same as above... ^
133 outputRawCode($htmlCode);
134 if ($newLine === true) print("\n");
138 // Huh, something goes wrong or maybe you have edited config.php ???
139 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
142 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
143 // Output cached HTML code
144 $GLOBALS['output'] = ob_get_contents();
146 // Clear output buffer for later output if output is found
147 if (!empty($GLOBALS['output'])) {
151 // Send all HTTP headers
154 // Compile and run finished rendered HTML code
155 compileFinalOutput();
157 // Output code here, DO NOT REMOVE! ;-)
158 outputRawCode($GLOBALS['output']);
159 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
160 // Send all HTTP headers
163 // Compile and run finished rendered HTML code
164 compileFinalOutput();
166 // Output code here, DO NOT REMOVE! ;-)
167 outputRawCode($GLOBALS['output']);
169 // And flush all headers
174 // Compiles the final output
175 function compileFinalOutput () {
176 // Add page header and footer
177 addPageHeaderFooter();
179 // Do the final compilation
180 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
182 // Extension 'rewrite' installed?
183 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
184 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
188 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
189 // Compress it for HTTP gzip
190 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
193 sendHeader('Content-Encoding: gzip');
194 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
195 // Compress it for HTTP deflate
196 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
199 sendHeader('Content-Encoding: deflate');
203 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
209 // Main compilation loop
210 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
211 // Insert comments? (Only valid with HTML templates, of course)
212 enableTemplateHtml($insertComments);
218 while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
219 // Init common variables
224 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
225 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
226 //* DEBUG: */ if (!$insertComments) print('<pre>'.linenumberCode($eval).'</pre>');
228 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
230 // Was that eval okay?
231 if (empty($newContent)) {
232 // Something went wrong!
233 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
243 // Return the compiled code
247 // Output the raw HTML code
248 function outputRawCode ($htmlCode) {
249 // Output stripped HTML code to avoid broken JavaScript code, etc.
250 print(str_replace('{BACK}', "\\", $htmlCode));
252 // Flush the output if only getPhpCaching() is not 'on'
253 if (getPhpCaching() != 'on') {
259 // Load a template file and return it's content (only it's name; do not use ' or ")
260 function loadTemplate ($template, $return = false, $content = array()) {
261 // @TODO Remove this sanity-check if all is fine
262 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
264 // Set current template
265 $GLOBALS['current_template'] = $template;
268 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
269 // Evaluate the cache
270 eval(readTemplateCache($template));
271 } elseif (!isset($GLOBALS['template_eval'][$template])) {
272 // Make all template names lowercase
273 $template = strtolower($template);
277 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
280 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
281 $extraPath = detectExtraTemplatePath($template);;
284 $FQFN = $basePath . $extraPath . $template . '.tpl';
286 // Does the special template exists?
287 if (!isFileReadable($FQFN)) {
288 // Reset to default template
289 $FQFN = $basePath . $template . '.tpl';
292 // Now does the final template exists?
293 if (isFileReadable($FQFN)) {
294 // Count the template load
295 incrementConfigEntry('num_templates');
297 // The local file does exists so we load it. :)
298 $GLOBALS['tpl_content'] = readFromFile($FQFN);
300 // Do we have to compile the code?
302 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
303 // Normal HTML output?
304 if (isHtmlOutputMode()) {
305 // Add surrounding HTML comments to help finding bugs faster
306 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
308 // Prepare eval() command
309 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
310 } elseif (substr($template, 0, 3) == 'js_') {
311 // JavaScripts don't like entities and timings
312 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
314 // Prepare eval() command, other output doesn't like entities, maybe
315 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
318 // Add surrounding HTML comments to help finding bugs faster
319 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . ' - End //-->';
320 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
322 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
323 // Only admins shall see this warning or when installation mode is active
324 $ret = '<div class="para">
325 <span class="guest_failed">{--TEMPLATE_404--}</span>
331 {--TEMPLATE_CONTENT--}
332 <pre>' . print_r($content, true) . '</pre>
336 $GLOBALS['template_eval'][$template] = '404';
341 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
343 eval($GLOBALS['template_eval'][$template]);
346 // Do we have some content to output or return?
348 // Not empty so let's put it out! ;)
349 if ($return === true) {
350 // Return the HTML code
356 } elseif (isDebugModeEnabled()) {
357 // Warning, empty output!
358 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
362 // Detects the extra template path from given template name
363 function detectExtraTemplatePath ($template) {
368 if (!isset($GLOBALS['extra_path'][$template])) {
369 // Check for admin/guest/member/etc. templates
370 if (substr($template, 0, 6) == 'admin_') {
371 // Admin template found
372 $extraPath = 'admin/';
373 } elseif (substr($template, 0, 6) == 'guest_') {
374 // Guest template found
375 $extraPath = 'guest/';
376 } elseif (substr($template, 0, 7) == 'member_') {
377 // Member template found
378 $extraPath = 'member/';
379 } elseif (substr($template, 0, 7) == 'select_') {
380 // Selection template found
381 $extraPath = 'select/';
382 } elseif (substr($template, 0, 8) == 'install_') {
383 // Installation template found
384 $extraPath = 'install/';
385 } elseif (substr($template, 0, 4) == 'ext_') {
386 // Extension template found
388 } elseif (substr($template, 0, 3) == 'la_') {
389 // 'Logical-area' template found
391 } elseif (substr($template, 0, 3) == 'js_') {
392 // JavaScript template found
394 } elseif (substr($template, 0, 5) == 'menu_') {
395 // Menu template found
396 $extraPath = 'menu/';
398 // Test for extension
399 $test = substr($template, 0, strpos($template, '_'));
401 // Probe for valid extension name
402 if (isExtensionNameValid($test)) {
403 // Set extra path to extension's name
404 $extraPath = $test . '/';
409 $GLOBALS['extra_path'][$template] = $extraPath;
413 return $GLOBALS['extra_path'][$template];
416 // Loads an email template and compiles it
417 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
420 // Make sure all template names are lowercase!
421 $template = strtolower($template);
423 // Is content an array?
424 if (is_array($content)) {
425 // Add expiration to array
426 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
427 // Will never expire!
428 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
429 } elseif (isConfigEntrySet('auto_purge')) {
430 // Create nice date string
431 $content['expiration'] = createFancyTime(getAutoPurge());
434 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
439 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
440 if ((isValidUserId($userid)) && (is_array($content))) {
441 // If nickname extension is installed, fetch nickname as well
442 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
443 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
445 fetchUserData($userid, 'nickname');
447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
449 fetchUserData($userid);
452 // Merge data if valid
453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
454 if (isUserDataValid()) {
455 $content = merge_array($content, getUserDataArray());
457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
461 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
464 $extraPath = detectExtraTemplatePath($template);
466 // Generate full FQFN
467 $FQFN = $basePath . $extraPath . $template . '.tpl';
469 // Does the special template exists?
470 if (!isFileReadable($FQFN)) {
471 // Reset to default template
472 $FQFN = $basePath . $template . '.tpl';
475 // Now does the final template exists?
477 if (isFileReadable($FQFN)) {
478 // The local file does exists so we load it. :)
479 $GLOBALS['tpl_content'] = readFromFile($FQFN);
482 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
483 eval($GLOBALS['tpl_content']);
484 } elseif (!empty($template)) {
485 // Template file not found!
486 $newContent = '<div class="para">
487 {--TEMPLATE_404--}: ' . $template . '
490 {--TEMPLATE_CONTENT--}
491 <pre>' . print_r($content, true) . '</pre>
493 <pre>' . print_r($DATA, true) . '</pre>
496 // Debug mode not active? Then remove the HTML tags
497 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
499 // No template name supplied!
500 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
503 // Is there some content?
504 if (empty($newContent)) {
506 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
508 // Add last error if the required function exists
509 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
512 // Remove content and data
520 // "Getter" for menu CSS classes, mainly used in templates
521 function getMenuCssClasses ($data) {
522 // $data needs to be converted into an array
523 $content = explode('|', $data);
525 // Non-existent index 2 will happen in menu blocks
526 if (!isset($content[2])) $content[2] = '';
528 // Re-construct the array: 0=visible,1=locked,2=prefix
529 $content['visible'] = $content[0];
530 $content['locked'] = $content[1];
532 // Call our "translator" function
533 $content = translateMenuVisibleLocked($content, $content[2]);
535 // Return CSS classes
536 return ($content['visible_css'] . ' ' . $content['locked_css']);
539 // Generate XHTML code for the CAPTCHA
540 function generateCaptchaCode ($code, $type, $DATA, $userid) {
541 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
544 // Compiles the given HTML/mail code
545 function compileCode ($code, $simple = false, $constants = true, $full = true) {
546 // Is the code a string?
547 if (!is_string($code)) {
548 // Silently return it
553 $startCompile = microtime(true);
556 $code = compileRawCode($code, $simple, $constants, $full);
559 $compiled = microtime(true);
561 // Add timing if enabled
562 if (isTemplateHtml()) {
563 // Add timing, this should be disabled in
564 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
567 // Return compiled code
571 // Compiles the code (use compileCode() only for HTML because of the comments)
572 // @TODO $simple/$constants are deprecated
573 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
574 // Is the code a string?
575 if (!is_string($code)) {
576 // Silently return it
580 // Init replacement-array with smaller set of security characters
581 $secChars = $GLOBALS['url_chars'];
583 // Select full set of chars to replace when we e.g. want to compile URLs
584 if ($full === true) $secChars = $GLOBALS['security_chars'];
586 // Compile more through a filter
587 $code = runFilterChain('compile_code', $code);
589 // Compile message strings
590 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
592 // Compile QUOT and other non-HTML codes
593 foreach ($secChars['to'] as $k => $to) {
594 // Do the reversed thing as in inc/libs/security_functions.php
595 $code = str_replace($to, $secChars['from'][$k], $code);
598 // Find $content[bla][blub] entries
599 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
600 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
602 // Are some matches found?
603 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
604 // Replace all matches
605 $matchesFound = array();
606 foreach ($matches[0] as $key => $match) {
607 // Fuzzy look has failed by default
610 // Fuzzy look on match if already found
611 foreach ($matchesFound as $found => $set) {
613 $test = substr($found, 0, strlen($match));
615 // Does this entry exist?
616 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
617 if ($test == $match) {
619 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
626 if ($fuzzyFound === true) continue;
628 // Take all string elements
629 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
630 // Replace it in the code
631 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
632 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
633 $code = str_replace($match, '".' . $newMatch . '."', $code);
634 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
635 $matchesFound[$match] = 1;
636 } elseif (!isset($matchesFound[$match])) {
638 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
639 $code = str_replace($match, '".' . $match . '."', $code);
640 $matchesFound[$match] = 1;
650 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
654 // This is a yes/no selection only!
655 if ($id > 0) $prefix .= '[' . $id . ']';
656 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
658 // Begin with regular selection box here
659 if (!empty($prefix)) $prefix .= '_';
661 if ($id > 0) $type2 .= '[' . $id . ']';
662 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
667 for ($idx = 1; $idx < 32; $idx++) {
668 $OUT .= '<option value="' . $idx . '"';
669 if ($default == $idx) $OUT .= ' selected="selected"';
670 $OUT .= '>' . $idx . '</option>';
674 case 'month': // Month
675 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
676 $OUT .= '<option value="' . $idx . '"';
677 if ($default == $idx) $OUT .= ' selected="selected"';
678 $OUT .= '>' . $descr . '</option>';
686 // Use configured min age or fixed?
687 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
689 $startYear = $year - getConfig('min_age');
692 $startYear = $year - 16;
695 // Calculate earliest year (100 years old people can still enter Internet???)
696 $minYear = $year - 100;
698 // Check if the default value is larger than minimum and bigger than actual year
699 if (($default > $minYear) && ($default >= $year)) {
700 for ($idx = $year; $idx < ($year + 11); $idx++) {
701 $OUT .= '<option value="' . $idx . '"';
702 if ($default == $idx) $OUT .= ' selected="selected"';
703 $OUT .= '>' . $idx . '</option>';
705 } elseif ($default == -1) {
706 // Current year minus 1
707 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
708 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
711 // Get current year and subtract the configured minimum age
712 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
713 // Calculate earliest year depending on extension version
714 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
715 // Use configured minimum age
716 $year = getYear() - getConfig('min_age');
718 // Use fixed 16 years age
719 $year = getYear() - 16;
722 // Construct year selection list
723 for ($idx = $minYear; $idx <= $year; $idx++) {
724 $OUT .= '<option value="' . $idx . '"';
725 if ($default == $idx) $OUT .= ' selected="selected"';
726 $OUT .= '>' . $idx . '</option>';
733 for ($idx = 0; $idx < 60; $idx+=5) {
734 if (strlen($idx) == 1) $idx = '0' . $idx;
735 $OUT .= '<option value="' . $idx . '"';
736 if ($default == $idx) $OUT .= ' selected="selected"';
737 $OUT .= '>' . $idx . '</option>';
742 for ($idx = 0; $idx < 24; $idx++) {
743 if (strlen($idx) == 1) $idx = '0' . $idx;
744 $OUT .= '<option value="' . $idx . '"';
745 if ($default == $idx) $OUT .= ' selected="selected"';
746 $OUT .= '>' . $idx . '</option>';
751 $OUT .= '<option value="Y"';
752 if ($default == 'Y') $OUT .= ' selected="selected"';
753 $OUT .= '>{--YES--}</option><option value="N"';
754 if ($default != 'Y') $OUT .= ' selected="selected"';
755 $OUT .= '>{--NO--}</option>';
762 // Insert the code in $img_code into jpeg or PNG image
763 function generateImageOrCode ($img_code, $headerSent = true) {
764 // Is the code size oversized or shouldn't we display it?
765 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
766 // Stop execution of function here because of over-sized code length
767 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
768 } elseif ($headerSent === false) {
769 // Return an HTML code here
770 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
774 $img = sprintf("%s/theme/%s/images/code_bg.%s",
777 getConfig('img_type')
781 if (isFileReadable($img)) {
783 switch (getConfig('img_type')) {
785 // Okay, load image and hide all errors
786 $image = imagecreatefromjpeg($img);
790 // Okay, load image and hide all errors
791 $image = imagecreatefrompng($img);
795 // Exit function here
796 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
800 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
801 $text_color = imagecolorallocate($image, 0, 0, 0);
803 // Insert code into image
804 imagestring($image, 5, 14, 2, $img_code, $text_color);
807 sendHeader('Content-Type: image/' . getConfig('img_type'));
809 // Output image with matching image factory
810 switch (getConfig('img_type')) {
811 case 'jpg': imagejpeg($image); break;
812 case 'png': imagepng($image); break;
815 // Remove image from memory
816 imagedestroy($image);
818 // Create selection box or array of splitted timestamp
819 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
820 // Do not continue if ONE_DAY is absend
821 if (!isConfigEntrySet('ONE_DAY')) {
822 // And return the timestamp itself or empty array
823 if ($return_array === true) {
830 // Calculate 2-seconds timestamp
831 $stamp = round($timestamp);
832 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
834 // Do we have a leap year?
836 $TEST = getYear() / 4;
838 $M2 = getMonth(time() + $timestamp);
840 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
841 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
843 // First of all years...
844 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
845 //* DEBUG: */ debugOutput('Y=' . $Y);
847 $M = abs(floor($timestamp / 2628000 - $Y * 12));
848 //* DEBUG: */ debugOutput('M=' . $M);
850 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
851 //* DEBUG: */ debugOutput('W=' . $W);
853 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
854 //* DEBUG: */ debugOutput('D=' . $D);
856 $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));
857 //* DEBUG: */ debugOutput('h=' . $h);
859 $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));
860 //* DEBUG: */ debugOutput('m=' . $m);
861 // And at last seconds...
862 $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));
863 //* DEBUG: */ debugOutput('s=' . $s);
865 // Is seconds zero and time is < 60 seconds?
866 if (($s == '0') && ($timestamp < 60)) {
868 $s = round($timestamp);
872 // Now we convert them in seconds...
875 // Just put all data in an array for later use
887 $OUT = '<div align="' . $align . '">';
888 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
891 if (isInString('Y', $display) || (empty($display))) {
892 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
895 if (isInString('M', $display) || (empty($display))) {
896 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
899 if (isInString('W', $display) || (empty($display))) {
900 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
903 if (isInString('D', $display) || (empty($display))) {
904 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
907 if (isInString('h', $display) || (empty($display))) {
908 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
911 if (isInString('m', $display) || (empty($display))) {
912 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
915 if (isInString('s', $display) || (empty($display))) {
916 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
922 if (isInString('Y', $display) || (empty($display))) {
923 // Generate year selection
924 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
925 for ($idx = 0; $idx <= 10; $idx++) {
926 $OUT .= '<option class="mini_select" value="' . $idx . '"';
927 if ($idx == $Y) $OUT .= ' selected="selected"';
928 $OUT .= '>' . $idx . '</option>';
930 $OUT .= '</select></td>';
932 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
935 if (isInString('M', $display) || (empty($display))) {
936 // Generate month selection
937 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
938 for ($idx = 0; $idx <= 11; $idx++) {
939 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
940 if ($idx == $M) $OUT .= ' selected="selected"';
941 $OUT .= '>' . $idx . '</option>';
943 $OUT .= '</select></td>';
945 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
948 if (isInString('W', $display) || (empty($display))) {
949 // Generate week selection
950 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
951 for ($idx = 0; $idx <= 4; $idx++) {
952 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
953 if ($idx == $W) $OUT .= ' selected="selected"';
954 $OUT .= '>' . $idx . '</option>';
956 $OUT .= '</select></td>';
958 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
961 if (isInString('D', $display) || (empty($display))) {
962 // Generate day selection
963 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
964 for ($idx = 0; $idx <= 31; $idx++) {
965 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
966 if ($idx == $D) $OUT .= ' selected="selected"';
967 $OUT .= '>' . $idx . '</option>';
969 $OUT .= '</select></td>';
971 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
974 if (isInString('h', $display) || (empty($display))) {
975 // Generate hour selection
976 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
977 for ($idx = 0; $idx <= 23; $idx++) {
978 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
979 if ($idx == $h) $OUT .= ' selected="selected"';
980 $OUT .= '>' . $idx . '</option>';
982 $OUT .= '</select></td>';
984 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
987 if (isInString('m', $display) || (empty($display))) {
988 // Generate minute selection
989 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
990 for ($idx = 0; $idx <= 59; $idx++) {
991 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
992 if ($idx == $m) $OUT .= ' selected="selected"';
993 $OUT .= '>' . $idx . '</option>';
995 $OUT .= '</select></td>';
997 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1000 if (isInString('s', $display) || (empty($display))) {
1001 // Generate second selection
1002 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1003 for ($idx = 0; $idx <= 59; $idx++) {
1004 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1005 if ($idx == $s) $OUT .= ' selected="selected"';
1006 $OUT .= '>' . $idx . '</option>';
1008 $OUT .= '</select></td>';
1010 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1017 // Return generated HTML code
1021 // Generate a list of administrative links to a given userid
1022 function generateMemberAdminActionLinks ($userid) {
1023 // Make sure userid is a number
1024 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1026 // Define all main targets
1027 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1030 $status = getFetchedUserData('userid', $userid, 'status');
1032 // Begin of navigation links
1035 foreach ($targetArray as $tar) {
1036 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1037 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1038 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1039 // Locked accounts shall be unlocked
1040 $OUT .= 'UNLOCK_USER';
1042 // All other status is fine
1043 $OUT .= strtoupper($tar);
1045 $OUT .= '_TITLE--}">{--ADMIN_';
1046 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1047 // Locked accounts shall be unlocked
1048 $OUT .= 'UNLOCK_USER';
1050 // All other status is fine
1051 $OUT .= strtoupper($tar);
1053 $OUT .= '--}</a></span>|';
1056 // Finish navigation link
1057 $OUT = substr($OUT, 0, -1) . ']';
1063 // Generate an email link
1064 function generateEmailLink ($email, $table = 'admins') {
1065 // Default email link (INSECURE! Spammer can read this by harvester programs)
1066 $EMAIL = 'mailto:' . $email;
1068 // Check for several extensions
1069 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1070 // Create email link for contacting admin in guest area
1071 $EMAIL = generateAdminEmailLink($email);
1072 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1073 // Create email link for contacting a member within admin area (or later in other areas, too?)
1074 $EMAIL = generateUserEmailLink($email);
1075 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1076 // Create email link to contact sponsor within admin area (or like the link above?)
1077 $EMAIL = generateSponsorEmailLink($email);
1080 // Shall I close the link when there is no admin?
1081 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1083 // Return email link
1087 // Output error messages in a fasioned way and die...
1088 function app_die ($F, $L, $message) {
1089 // Check if Script is already dieing and not let it kill itself another 1000 times
1090 if (!isset($GLOBALS['app_died'])) {
1091 // Make sure, that the script realy realy diese here and now
1092 $GLOBALS['app_died'] = true;
1094 // Set content type as text/html
1095 setContentType('text/html');
1098 loadIncludeOnce('inc/header.php');
1100 // Rewrite message for output
1101 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1103 // Load the message template
1104 loadTemplate('app_die_message', false, $message);
1107 loadIncludeOnce('inc/footer.php');
1109 // Script tried to kill itself twice
1110 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1114 // Display parsing time and number of SQL queries in footer
1115 function displayParsingTime () {
1116 // Is the timer started?
1117 if (!isset($GLOBALS['startTime'])) {
1123 $endTime = microtime(true);
1125 // "Explode" both times
1126 $start = explode(' ', $GLOBALS['startTime']);
1127 $end = explode(' ', $endTime);
1128 $runTime = $end[0] - $start[0];
1129 if ($runTime < 0) $runTime = '0';
1132 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1134 'run_time' => $runTime,
1135 'sql_time' => (getConfig('sql_time') * 1000),
1138 // Load the template
1139 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1142 // Output a debug backtrace to the user
1143 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1144 // Is this already called?
1145 if (isset($GLOBALS[__FUNCTION__])) {
1147 print 'Message:' . $message . '<br />Backtrace:<pre>';
1148 debug_print_backtrace();
1152 // Set this function as called
1153 $GLOBALS[__FUNCTION__] = true;
1158 // Is the optional message set?
1159 if (!empty($message)) {
1161 $debug = sprintf("Note: %s<br />\n",
1165 // @TODO Add a little more infos here
1166 logDebugMessage($F, $L, strip_tags($message));
1170 $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>';
1171 $debug .= debug_get_printable_backtrace();
1173 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1174 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1176 // Send an email? (e.g. not wanted for evaluation errors)
1177 if (($sendEmail === true) && (!isInstallationPhase())) {
1180 'message' => trim($message),
1181 'backtrace' => trim(debug_get_mailable_backtrace())
1184 // Send email to webmaster
1185 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1189 app_die($F, $L, $debug);
1192 // Compile characters which are allowed in URLs
1193 function compileUriCode ($code, $simple = true) {
1194 // Compile constants
1195 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1197 // Compile QUOT and other non-HTML codes
1198 $code = str_replace('{DOT}', '.',
1199 str_replace('{SLASH}', '/',
1200 str_replace('{QUOT}', "'",
1201 str_replace('{DOLLAR}', '$',
1202 str_replace('{OPEN_ANCHOR}', '(',
1203 str_replace('{CLOSE_ANCHOR}', ')',
1204 str_replace('{OPEN_SQR}', '[',
1205 str_replace('{CLOSE_SQR}', ']',
1206 str_replace('{PER}', '%',
1210 // Return compiled code
1214 // Handle message codes from URL
1215 function handleCodeMessage () {
1216 if (isGetRequestParameterSet('code')) {
1217 // Default extension is 'unknown'
1220 // Is extension given?
1221 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1223 // Convert the 'code' parameter from URL to a human-readable message
1224 $message = getMessageFromErrorCode(getRequestParameter('code'));
1226 // Load message template
1227 loadTemplate('message', false, $message);
1231 // Generates a 'extension foo inactive' message
1232 function generateExtensionInactiveMessage ($ext_name) {
1233 // Is the extension empty?
1234 if (empty($ext_name)) {
1235 // This should not happen
1236 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1240 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1242 // Is an admin logged in?
1244 // Then output admin message
1245 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1248 // Return prepared message
1252 // Generates a 'extension foo not installed' message
1253 function generateExtensionNotInstalledMessage ($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_EXTENSION_NOT_INSTALLED', $ext_name);
1263 // Is an admin logged in?
1265 // Then output admin message
1266 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1269 // Return prepared message
1273 // Generates a message depending on if the extension is not installed or not
1275 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1279 // Is the extension not installed or just deactivated?
1280 switch (isExtensionInstalled($ext_name)) {
1281 case true; // Deactivated!
1282 $message = generateExtensionInactiveMessage($ext_name);
1285 case false; // Not installed!
1286 $message = generateExtensionNotInstalledMessage($ext_name);
1289 default: // Should not happen!
1290 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1291 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1295 // Return the message
1299 // Print code with line numbers
1300 function linenumberCode ($code) {
1301 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1302 $count_lines = count($codeE);
1304 $r = 'Line | Code:<br />';
1305 foreach($codeE as $line => $c) {
1306 $r .= '<div class="line"><span class="linenum">';
1307 if ($count_lines == 1) {
1310 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1315 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1318 return '<div class="code">' . $r . '</div>';
1321 // Determines the right page title
1322 function determinePageTitle () {
1323 // Config and database connection valid?
1324 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1328 // Title decoration enabled?
1329 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1331 // Do we have some extra title?
1332 if (isExtraTitleSet()) {
1334 $TITLE .= getExtraTitle() . ' by ';
1338 $TITLE .= getMainTitle();
1340 // Add title of module? (middle decoration will also be added!)
1341 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1342 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1345 // Add title from what file
1347 if (getModule() == 'login') $mode = 'member';
1348 elseif (getModule() == 'index') $mode = 'guest';
1349 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1351 // Add title decorations? (right)
1352 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1354 // Remember title in constant for the template
1355 $pageTitle = $TITLE;
1356 } elseif ((isInstalled()) && (isAdminRegistered())) {
1357 // Installed, admin registered but no ext-sql_patches
1358 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1359 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1360 // Installed but no admin registered
1361 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1362 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1363 // Installation mode
1364 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1366 // Configuration not found!
1367 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1369 // Do not add the fatal message in installation mode
1370 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1374 return decodeEntities($pageTitle);
1377 // Checks wethere there is a cache file there. This function is cached.
1378 function isTemplateCached ($template) {
1379 // Do we have cached this result?
1380 if (!isset($GLOBALS['template_cache'][$template])) {
1382 $FQFN = generateCacheFqfn($template);
1385 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1389 return $GLOBALS['template_cache'][$template];
1392 // Flushes non-flushed template cache to disk
1393 function flushTemplateCache ($template, $eval) {
1394 // Is this cache flushed?
1395 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1397 $FQFN = generateCacheFqfn($template);
1400 writeToFile($FQFN, $eval, true);
1404 // Reads a template cache
1405 function readTemplateCache ($template) {
1407 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1408 // This should not happen
1409 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1413 if (!isset($GLOBALS['template_eval'][$template])) {
1415 $FQFN = generateCacheFqfn($template);
1418 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1422 return $GLOBALS['template_eval'][$template];
1425 // Escapes quotes (default is only double-quotes)
1426 function escapeQuotes ($str, $single = false) {
1427 // Should we escape all?
1428 if ($single === true) {
1429 // Escape all (including null)
1430 $str = addslashes($str);
1432 // Remove escaping of single quotes
1433 $str = str_replace("\'", "'", $str);
1435 // Escape only double-quotes but prevent double-quoting
1436 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1439 // Return the escaped string
1443 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1444 function escapeJavaScriptQuotes ($str) {
1445 // Replace all double-quotes and secure back-ticks
1446 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1452 // Send out mails depending on the 'mod/modes' combination
1453 // @TODO Lame description for this function
1454 function sendModeMails ($mod, $modes) {
1456 if (fetchUserData(getMemberId())) {
1457 // Extract salt from cookie
1458 $salt = substr(getSession('u_hash'), 0, -40);
1460 // Now let's compare passwords
1461 $hash = encodeHashForCookie(getUserData('password'));
1463 // Does the hash match or should we change it?
1464 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1466 $content = getUserDataArray();
1468 // Clear/init the content variable
1469 $content['message'] = '';
1472 // @TODO Move this in a filter
1475 foreach ($modes as $mode) {
1477 case 'normal': break; // Do not add any special lines
1478 case 'email': // Email was changed!
1479 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1482 case 'password': // Password was changed
1483 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1487 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1488 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1493 if (isExtensionActive('country')) {
1494 // Replace code with description
1495 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1498 // Merge content with data from POST
1499 $content = merge_array($content, postRequestArray());
1502 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1504 if (isAdminNotificationEnabled()) {
1505 // The admin needs to be notified about a profile change
1506 $message_admin = 'admin_mydata_notify';
1507 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1510 $message_admin = '';
1514 // Set subject lines
1515 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1517 // Output success message
1518 $content = '<span class="member_done">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1521 default: // Unsupported module!
1522 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1523 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
1527 // Passwords mismatch
1528 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
1531 // Could not load profile
1532 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1535 // Send email to user if required
1536 if ((!empty($sub_mem)) && (!empty($message))) {
1538 sendEmail($content['email'], $sub_mem, $message);
1541 // Send only if no other error has occured
1542 if (empty($content)) {
1543 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1545 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1546 } elseif (isAdminNotificationEnabled()) {
1547 // Cannot send mails to admin!
1548 $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1551 $content = '<span class="member_done">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1556 loadTemplate('admin_settings_saved', false, $content);
1559 // Generates a 'selection box' from given array
1560 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1562 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
1563 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1565 // Walk through all options
1566 foreach ($options as $option) {
1567 // Add the <option> entry
1568 if (empty($optionContent)) {
1569 // ... from template
1570 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1573 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1577 // Finish selection box
1578 $OUT .= '</select>';
1582 'selection_box' => $OUT,
1585 // Load template and return it
1586 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1589 // Prepares the header for HTML output
1590 function loadHtmlHeader () {
1592 // 1.) pre_page_header (mainly loads the page_header template and includes
1593 // meta description)
1594 runFilterChain('pre_page_header');
1596 // Here can be something be added, but normally one of the two filters
1597 // around this line should do the job for you.
1599 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1600 // to close the head-tag)
1601 // Include more header data here
1602 runFilterChain('post_page_header');
1605 // Adds page header and footer to output array element
1606 function addPageHeaderFooter () {
1610 // Add them all together. This is maybe to simple
1611 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1612 // Add page part if set
1613 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1616 // Transfer $OUT to 'output'
1617 $GLOBALS['output'] = $OUT;
1620 // Generates meta description for current module and 'what' value
1621 function generateMetaDescriptionCode () {
1622 // Only include from guest area and if sql_patches has correct version
1623 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1624 // Construct dynamic description
1625 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1627 // Output it directly
1628 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1632 unset($GLOBALS['ref_level']);
1635 // Generates an FQFN for template cache from the given template name
1636 function generateCacheFqfn ($template, $mode = 'html') {
1638 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1639 // Generate the FQFN
1640 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1641 "%s_compiled/%s/%s.tpl.cache",
1649 return $GLOBALS['template_cache_fqfn'][$template];
1652 // "Fixes" null or empty string to count of dashes
1653 function fixNullEmptyToDashes ($str, $num) {
1654 // Use str as default
1658 if ((is_null($str)) || (trim($str) == '')) {
1660 $return = str_repeat('-', $num);
1663 // Return final string
1667 //-----------------------------------------------------------------------------
1668 // Template Helper Functions
1669 //-----------------------------------------------------------------------------
1671 // Color-switch helper function
1672 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1674 if (!isset($GLOBALS['color_switch'][$template])) {
1676 initTemplateColorSwitch($template);
1677 } elseif ($clear === false) {
1678 // Switch color if called from loadTemplate()
1679 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1680 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1683 // Return CSS class name
1684 if ($return === true) {
1685 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1686 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1690 // Helper function for extension registration link
1691 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1692 // Default is all productive
1693 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1695 // Is the given extension non-productive?
1696 if (!isExtensionProductive($ext_name)) {
1697 // Non-productive code
1698 $OUT = '<em style="cursor:help" class="admin_note" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</em>';