ba3588063aef2e71c416d33e56150c515db62a76
[mailer.git] / inc / template-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 04/04/2009 *
4  * ===================                          Last change: 04/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : template-functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : Template functions                               *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Template-Funktionen                              *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                  *
23  *                                                                      *
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.                                  *
28  *                                                                      *
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.                         *
33  *                                                                      *
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,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
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);
48 }
49
50 // Setter for 'is_template_html'
51 function enableTemplateHtml ($enable = true) {
52         $GLOBALS['is_template_html'] = (bool) $enable;
53 }
54
55 // Checks wether the template is HTML or not by previously set flag
56 // Default: true
57 function isTemplateHtml () {
58         // Is the output_mode other than 0 (HTML), then no comments are enabled
59         if (getScriptOutputMode() != 0) {
60                 // No HTML
61                 return false;
62         } else {
63                 // Maybe HTML?
64                 return $GLOBALS['is_template_html'];
65         }
66 }
67
68 // Wrapper for writing debug informations to the browser
69 function debugOutput ($message) {
70         outputHtml('<div class="debug_message">' . $message . '</div>');
71 }
72
73 // "Fixes" an empty string into three dashes (use for templates)
74 function fixEmptyContentToDashes ($str) {
75         // Trim the string
76         $str = trim($str);
77
78         // Is the string empty?
79         if (empty($str)) $str = '---';
80
81         // Return string
82         return $str;
83 }
84
85 // Color-switch helper function
86 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
87         // Is it there?
88         if (!isset($GLOBALS['color_switch'][$template])) {
89                 // Initialize it
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];
95         } // END - if
96
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];
101         } // END - if
102 }
103
104 // Init color switch
105 function initTemplateColorSwitch ($template) {
106         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
107         $GLOBALS['color_switch'][$template] = 2;
108 }
109
110 // "Getter" for color switch code
111 function getColorSwitchCode ($template) {
112         // Prepare the code
113         $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
114
115         // And return it
116         return $code;
117 }
118
119 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
120 function outputHtml ($htmlCode, $newLine = true) {
121         // Init output
122         if (!isset($GLOBALS['output'])) {
123                 $GLOBALS['output'] = '';
124         } // END - if
125
126         // Do we have HTML-Code here?
127         if (!empty($htmlCode)) {
128                 // Yes, so we handle it as you have configured
129                 switch (getOutputMode()) {
130                         case 'render':
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);
135
136                                         // That's why you don't need any \n at the end of your HTML code... :-)
137                                         if ($newLine === true) print("\n");
138                                 } else {
139                                         // Render mode for old or lame servers...
140                                         $GLOBALS['output'] .= $htmlCode;
141
142                                         // That's why you don't need any \n at the end of your HTML code... :-)
143                                         if ($newLine === true) $GLOBALS['output'] .= "\n";
144                                 }
145                                 break;
146
147                         case 'direct':
148                                 // If we are switching from render to direct output rendered code
149                                 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
150
151                                 // The same as above... ^
152                                 outputRawCode($htmlCode);
153                                 if ($newLine === true) print("\n");
154                                 break;
155
156                         default:
157                                 // Huh, something goes wrong or maybe you have edited config.php ???
158                                 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
159                                 break;
160                 } // END - switch
161         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
162                 // Output cached HTML code
163                 $GLOBALS['output'] = ob_get_contents();
164
165                 // Clear output buffer for later output if output is found
166                 if (!empty($GLOBALS['output'])) {
167                         clearOutputBuffer();
168                 } // END - if
169
170                 // Send all HTTP headers
171                 sendHttpHeaders();
172
173                 // Compile and run finished rendered HTML code
174                 compileFinalOutput();
175
176                 // Output code here, DO NOT REMOVE! ;-)
177                 outputRawCode($GLOBALS['output']);
178         } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
179                 // Send all HTTP headers
180                 sendHttpHeaders();
181
182                 // Compile and run finished rendered HTML code
183                 compileFinalOutput();
184
185                 // Output code here, DO NOT REMOVE! ;-)
186                 outputRawCode($GLOBALS['output']);
187         } else {
188                 // And flush all headers
189                 flushHeaders();
190         }
191 }
192
193 // Compiles the final output
194 function compileFinalOutput () {
195         // Add page header and footer
196         addPageHeaderFooter();
197
198         // Do the final compilation
199         $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
200
201         // Extension 'rewrite' installed?
202         if ((isExtensionActive('rewrite')) && (getScriptOutputMode() != 1)) {
203                 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
204         } // END - if
205
206         // Compress it?
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);
210
211                 // Add header
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);
216
217                 // Add header
218                 sendHeader('Content-Encoding: deflate');
219         }
220
221         // Add final length
222         sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
223
224         // Flush all headers
225         flushHeaders();
226 }
227
228 // Main compilation loop
229 function doFinalCompilation ($code, $insertComments = true) {
230         // Insert comments? (Only valid with HTML templates, of course)
231         enableTemplateHtml($insertComments);
232
233         // Init counter
234         $cnt = 0;
235
236         // Compile all out
237         while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
238                 // Init common variables
239                 $content = array();
240                 $newContent = '';
241
242                 // Compile it
243                 //* DEBUG: */ debugOutput('<pre>'.encodeEntities($code).'</pre>');
244                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code))) . '";';
245                 //* DEBUG: */ if (!$insertComments) print('<pre>'.linenumberCode($eval).'</pre>');
246                 eval($eval);
247                 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
248
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);
253                 } // END - if
254
255                 // Use it again
256                 $code = $newContent;
257
258                 // Count round
259                 $cnt++;
260         } // END - while
261
262         // Return the compiled code
263         return $code;
264 }
265
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));
270
271         // Flush the output if only getPhpCaching() is not 'on'
272         if (getPhpCaching() != 'on') {
273                 // Flush it
274                 flush();
275         } // END - if
276 }
277
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) . ')');
282
283         // Set current template
284         $GLOBALS['current_template'] = $template;
285
286         // Do we have cache?
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);
293
294                 // Init some data
295                 $ret = '';
296                 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
297
298                 // Base directory
299                 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
300                 $extraPath = detectExtraTemplatePath($template);;
301
302                 ////////////////////////
303                 // Generate file name //
304                 ////////////////////////
305                 $FQFN = $basePath . $extraPath . $template . '.tpl';
306
307                 // Does the special template exists?
308                 if (!isFileReadable($FQFN)) {
309                         // Reset to default template
310                         $FQFN = $basePath . $template . '.tpl';
311                 } // END - if
312
313                 // Now does the final template exists?
314                 if (isFileReadable($FQFN)) {
315                         // Count the template load
316                         incrementConfigEntry('num_templates');
317
318                         // The local file does exists so we load it. :)
319                         $GLOBALS['tpl_content'] = readFromFile($FQFN);
320
321                         // Do we have to compile the code?
322                         $ret = '';
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 //-->';
328
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'])) . '");';
334                                 } else {
335                                         // Prepare eval() command, other output doesn't like entities, maybe
336                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
337                                 }
338                         } else {
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)) . '";';
342                         } // END - if
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>
347 </div>
348 <div class="para">
349         (' . $template . ')
350 </div>
351 <div class="para">
352         {--TEMPLATE_CONTENT--}
353         <pre>' . print_r($content, true) . '</pre>
354 </div>';
355                 } else {
356                         // No file!
357                         $GLOBALS['template_eval'][$template] = '404';
358                 }
359         }
360
361         // Code set?
362         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
363                 // Eval the code
364                 eval($GLOBALS['template_eval'][$template]);
365         } // END - if
366
367         // Do we have some content to output or return?
368         if (!empty($ret)) {
369                 // Not empty so let's put it out! ;)
370                 if ($return === true) {
371                         // Return the HTML code
372                         return $ret;
373                 } else {
374                         // Output directly
375                         outputHtml($ret);
376                 }
377         } elseif (isDebugModeEnabled()) {
378                 // Warning, empty output!
379                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
380         }
381 }
382
383 // Detects the extra template path from given template name
384 function detectExtraTemplatePath ($template) {
385         // Default is empty
386         $extraPath = '';
387
388         // Do we have cache?
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
408                         $extraPath = 'ext/';
409                 } elseif (substr($template, 0, 3) == 'la_') {
410                         // 'Logical-area' template found
411                         $extraPath = 'la/';
412                 } elseif (substr($template, 0, 3) == 'js_') {
413                         // JavaScript template found
414                         $extraPath = 'js/';
415                 } elseif (substr($template, 0, 5) == 'menu_') {
416                         // Menu template found
417                         $extraPath = 'menu/';
418                 } else {
419                         // Test for extension
420                         $test = substr($template, 0, strpos($template, '_'));
421
422                         // Probe for valid extension name
423                         if (isExtensionNameValid($test)) {
424                                 // Set extra path to extension's name
425                                 $extraPath = $test . '/';
426                         } // END - if
427                 }
428
429                 // Store it in cache
430                 $GLOBALS['extra_path'][$template] = $extraPath;
431         } // END - if
432
433         // Return result
434         return $GLOBALS['extra_path'][$template];
435 }
436
437 // Loads an email template and compiles it
438 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
439         global $DATA;
440
441         // Make sure all template names are lowercase!
442         $template = strtolower($template);
443
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());
453                 } else {
454                         // Missing entry
455                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
456                 }
457         } // END - if
458
459         // Load user's data
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 />");
465                         // Load by nickname
466                         fetchUserData($userid, 'nickname');
467                 } else {
468                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
469                         /// Load by userid
470                         fetchUserData($userid);
471                 }
472
473                 // Merge data if valid
474                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
475                 if (isUserDataValid()) {
476                         $content = merge_array($content, getUserDataArray());
477                 } // END - if
478                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
479         } // END - if
480
481         // Base directory
482         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
483
484         // Detect extra path
485         $extraPath = detectExtraTemplatePath($template);
486
487         // Generate full FQFN
488         $FQFN = $basePath . $extraPath . $template . '.tpl';
489
490         // Does the special template exists?
491         if (!isFileReadable($FQFN)) {
492                 // Reset to default template
493                 $FQFN = $basePath . $template . '.tpl';
494         } // END - if
495
496         // Now does the final template exists?
497         $newContent = '';
498         if (isFileReadable($FQFN)) {
499                 // The local file does exists so we load it. :)
500                 $GLOBALS['tpl_content'] = readFromFile($FQFN);
501
502                 // Run code
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 . '
509 </div>
510 <div class="para">
511         {--TEMPLATE_CONTENT--}
512         <pre>' . print_r($content, true) . '</pre>
513         {--TEMPLATE_DATA--}
514         <pre>' . print_r($DATA, true) . '</pre>
515 </div>';
516
517                 // Debug mode not active? Then remove the HTML tags
518                 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
519         } else {
520                 // No template name supplied!
521                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
522         }
523
524         // Is there some content?
525         if (empty($newContent)) {
526                 // Compiling failed
527                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
528
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.";
531         } // END - if
532
533         // Remove content and data
534         unset($content);
535         unset($DATA);
536
537         // Return content
538         return $newContent;
539 }
540
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);
545
546         // Non-existent index 2 will happen in menu blocks
547         if (!isset($content[2])) $content[2] = '';
548
549         // Re-construct the array: 0=visible,1=locked,2=prefix
550         $content['visible'] = $content[0];
551         $content['locked']  = $content[1];
552
553         // Call our "translator" function
554         $content = translateMenuVisibleLocked($content, $content[2]);
555
556         // Return CSS classes
557         return ($content['visible_css'] . ' ' . $content['locked_css']);
558 }
559
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 . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '%}" />';
563 }
564
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
570                 return $code;
571         } // END - if
572
573         // Start couting
574         $startCompile = microtime(true);
575
576         // Comile the code
577         $code = compileRawCode($code, $simple, $constants, $full);
578
579         // Get timing
580         $compiled = microtime(true);
581
582         // Add timing if enabled
583         if (isTemplateHtml()) {
584                 // Add timing, this should be disabled in
585                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
586         } // END - if
587
588         // Return compiled code
589         return $code;
590 }
591
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
598                 return $code;
599         } // END - if
600
601         // Init replacement-array with smaller set of security characters
602         $secChars = $GLOBALS['url_chars'];
603
604         // Select full set of chars to replace when we e.g. want to compile URLs
605         if ($full === true) $secChars = $GLOBALS['security_chars'];
606
607         // Compile more through a filter
608         $code = runFilterChain('compile_code', $code);
609
610         // Compile message strings
611         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
612
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);
617         } // END - foreach
618
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);
622
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
629                         $fuzzyFound = false;
630
631                         // Fuzzy look on match if already found
632                         foreach ($matchesFound as $found => $set) {
633                                 // Get test part
634                                 $test = substr($found, 0, strlen($match));
635
636                                 // Does this entry exist?
637                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
638                                 if ($test == $match) {
639                                         // Match found!
640                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
641                                         $fuzzyFound = true;
642                                         break;
643                                 } // END - if
644                         } // END - foreach
645
646                         // Skip this entry?
647                         if ($fuzzyFound === true) continue;
648
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])) {
658                                 // Not yet replaced!
659                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
660                                 $code = str_replace($match, '".' . $match . '."', $code);
661                                 $matchesFound[$match] = 1;
662                         }
663                 } // END - foreach
664         } // END - if
665
666         // Return it
667         return $code;
668 }
669
670 //
671 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
672         $OUT = '';
673
674         if ($type == 'yn') {
675                 // This is a yes/no selection only!
676                 if ($id > 0) $prefix .= '[' . $id . ']';
677                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
678         } else {
679                 // Begin with regular selection box here
680                 if (!empty($prefix)) $prefix .= '_';
681                 $type2 = $type;
682                 if ($id > 0) $type2 .= '[' . $id . ']';
683                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
684         }
685
686         switch ($type) {
687                 case 'day': // Day
688                         for ($idx = 1; $idx < 32; $idx++) {
689                                 $OUT .= '<option value="' . $idx . '"';
690                                 if ($default == $idx) $OUT .= ' selected="selected"';
691                                 $OUT .= '>' . $idx . '</option>';
692                         } // END - for
693                         break;
694
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>';
700                         } // END - for
701                         break;
702
703                 case 'year': // Year
704                         // Get current year
705                         $year = getYear();
706
707                         // Use configured min age or fixed?
708                         if (isExtensionInstalledAndNewer('order', '0.2.1')) {
709                                 // Configured
710                                 $startYear = $year - getConfig('min_age');
711                         } else {
712                                 // Fixed 16 years
713                                 $startYear = $year - 16;
714                         }
715
716                         // Calculate earliest year (100 years old people can still enter Internet???)
717                         $minYear = $year - 100;
718
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>';
725                                 } // END - for
726                         } elseif ($default == -1) {
727                                 // Current year minus 1
728                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
729                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
730                                 } // END - for
731                         } else {
732                                 // Get current year and subtract the configured minimum age
733                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $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');
738                                 } else {
739                                         // Use fixed 16 years age
740                                         $year = getYear() - 16;
741                                 }
742
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>';
748                                 } // END - for
749                         }
750                         break;
751
752                 case 'sec':
753                 case 'min':
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>';
759                         } // END - for
760                         break;
761
762                 case 'hour':
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>';
768                         } // END - for
769                         break;
770
771                 case 'yn':
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>';
777                         break;
778         }
779         $OUT .= '</select>';
780         return $OUT;
781 }
782
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" />';
792         }
793
794         // Load image
795         $img = sprintf("%s/theme/%s/images/code_bg.%s",
796                 getPath(),
797                 getCurrentTheme(),
798                 getConfig('img_type')
799         );
800
801         // Is it readable?
802         if (isFileReadable($img)) {
803                 // Switch image type
804                 switch (getConfig('img_type')) {
805                         case 'jpg':
806                                 // Okay, load image and hide all errors
807                                 $image = imagecreatefromjpeg($img);
808                                 break;
809
810                         case 'png':
811                                 // Okay, load image and hide all errors
812                                 $image = imagecreatefrompng($img);
813                                 break;
814                 } // END - switch
815         } else {
816                 // Exit function here
817                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
818                 return;
819         }
820
821         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
822         $text_color = imagecolorallocate($image, 0, 0, 0);
823
824         // Insert code into image
825         imagestring($image, 5, 14, 2, $img_code, $text_color);
826
827         // Return to browser
828         sendHeader('Content-Type: image/' . getConfig('img_type'));
829
830         // Output image with matching image factory
831         switch (getConfig('img_type')) {
832                 case 'jpg': imagejpeg($image); break;
833                 case 'png': imagepng($image);  break;
834         } // END - switch
835
836         // Remove image from memory
837         imagedestroy($image);
838 }
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) {
845                         return array();
846                 } else {
847                         return $timestamp;
848                 }
849         } // END - if
850
851         // Calculate 2-seconds timestamp
852         $stamp = round($timestamp);
853         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
854
855         // Do we have a leap year?
856         $SWITCH = '0';
857         $TEST = getYear() / 4;
858         $M1 = getMonth();
859         $M2 = getMonth(time() + $timestamp);
860
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');
863
864         // First of all years...
865         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
866         //* DEBUG: */ debugOutput('Y=' . $Y);
867         // Next months...
868         $M = abs(floor($timestamp / 2628000 - $Y * 12));
869         //* DEBUG: */ debugOutput('M=' . $M);
870         // Next weeks
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);
873         // Next days...
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);
876         // Next hours...
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);
879         // Next minutes..
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);
885
886         // Is seconds zero and time is < 60 seconds?
887         if (($s == '0') && ($timestamp < 60)) {
888                 // Fix seconds
889                 $s = round($timestamp);
890         } // END - if
891
892         //
893         // Now we convert them in seconds...
894         //
895         if ($return_array) {
896                 // Just put all data in an array for later use
897                 $OUT = array(
898                         'YEARS'   => $Y,
899                         'MONTHS'  => $M,
900                         'WEEKS'   => $W,
901                         'DAYS'    => $D,
902                         'HOURS'   => $h,
903                         'MINUTES' => $m,
904                         'SECONDS' => $s
905                 );
906         } else {
907                 // Generate table
908                 $OUT  = '<div align="' . $align . '">';
909                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
910                 $OUT .= '<tr>';
911
912                 if (isInString('Y', $display) || (empty($display))) {
913                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
914                 } // END - if
915
916                 if (isInString('M', $display) || (empty($display))) {
917                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
918                 } // END - if
919
920                 if (isInString('W', $display) || (empty($display))) {
921                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
922                 } // END - if
923
924                 if (isInString('D', $display) || (empty($display))) {
925                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
926                 } // END - if
927
928                 if (isInString('h', $display) || (empty($display))) {
929                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
930                 } // END - if
931
932                 if (isInString('m', $display) || (empty($display))) {
933                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
934                 } // END - if
935
936                 if (isInString('s', $display) || (empty($display))) {
937                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
938                 } // END - if
939
940                 $OUT .= '</tr>';
941                 $OUT .= '<tr>';
942
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>';
950                         } // END - for
951                         $OUT .= '</select></td>';
952                 } else {
953                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
954                 }
955
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>';
963                         } // END - for
964                         $OUT .= '</select></td>';
965                 } else {
966                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
967                 }
968
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>';
976                         } // END - for
977                         $OUT .= '</select></td>';
978                 } else {
979                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
980                 }
981
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>';
989                         } // END - for
990                         $OUT .= '</select></td>';
991                 } else {
992                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
993                 }
994
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>';
1002                         } // END - for
1003                         $OUT .= '</select></td>';
1004                 } else {
1005                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1006                 }
1007
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>';
1015                         } // END - for
1016                         $OUT .= '</select></td>';
1017                 } else {
1018                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1019                 }
1020
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>';
1028                         } // END - for
1029                         $OUT .= '</select></td>';
1030                 } else {
1031                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1032                 }
1033                 $OUT .= '</tr>';
1034                 $OUT .= '</table>';
1035                 $OUT .= '</div>';
1036         }
1037
1038         // Return generated HTML code
1039         return $OUT;
1040 }
1041
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!');
1046
1047         // Define all main targets
1048         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1049
1050         // Get user status
1051         $status = getFetchedUserData('userid', $userid, 'status');
1052
1053         // Begin of navigation links
1054         $OUT = '[';
1055
1056         foreach ($targetArray as $tar) {
1057                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;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';
1062                 } else {
1063                         // All other status is fine
1064                         $OUT .= strtoupper($tar);
1065                 }
1066                 $OUT .= '_TITLE--}">{--ADMIN_';
1067                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1068                         // Locked accounts shall be unlocked
1069                         $OUT .= 'UNLOCK_USER';
1070                 } else {
1071                         // All other status is fine
1072                         $OUT .= strtoupper($tar);
1073                 }
1074                 $OUT .= '--}</a></span>|';
1075         } // END - foreach
1076
1077         // Finish navigation link
1078         $OUT = substr($OUT, 0, -1) . ']';
1079
1080         // Return string
1081         return $OUT;
1082 }
1083
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;
1088
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');
1099         }
1100
1101         // Shall I close the link when there is no admin?
1102         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1103
1104         // Return email link
1105         return $EMAIL;
1106 }
1107
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;
1114
1115                 // Set content type as text/html
1116                 setContentType('text/html');
1117
1118                 // Load header
1119                 loadIncludeOnce('inc/header.php');
1120
1121                 // Rewrite message for output
1122                 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1123
1124                 // Load the message template
1125                 loadTemplate('app_die_message', false, $message);
1126
1127                 // Load footer
1128                 loadIncludeOnce('inc/footer.php');
1129         } else {
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);
1132         }
1133 }
1134
1135 // Display parsing time and number of SQL queries in footer
1136 function displayParsingTime () {
1137         // Is the timer started?
1138         if (!isset($GLOBALS['startTime'])) {
1139                 // Abort here
1140                 return false;
1141         } // END - if
1142
1143         // Get end time
1144         $endTime = microtime(true);
1145
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';
1151
1152         // Prepare output
1153         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1154         $content = array(
1155                 'run_time' => $runTime,
1156                 'sql_time' => (getConfig('sql_time') * 1000),
1157         );
1158
1159         // Load the template
1160         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1161 }
1162
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__])) {
1167                 // Other backtrace
1168                 print 'Message:' . $message . '<br />Backtrace:<pre>';
1169                 debug_print_backtrace();
1170                 die('</pre>');
1171         } // END - if
1172
1173         // Set this function as called
1174         $GLOBALS[__FUNCTION__] = true;
1175
1176         // Init message
1177         $debug = '';
1178
1179         // Is the optional message set?
1180         if (!empty($message)) {
1181                 // Use and log it
1182                 $debug = sprintf("Note: %s<br />\n",
1183                         $message
1184                 );
1185
1186                 // @TODO Add a little more infos here
1187                 logDebugMessage($F, $L, strip_tags($message));
1188         } // END - if
1189
1190         // Add output
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();
1193         $debug .= '</pre>';
1194         $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
1195         $debug .= '<div>Thank you for finding bugs.</div>';
1196
1197         // Send an email? (e.g. not wanted for evaluation errors)
1198         if (($sendEmail === true) && (!isInstallationPhase())) {
1199                 // Prepare content
1200                 $content = array(
1201                         'message'   => trim($message),
1202                         'backtrace' => trim(debug_get_mailable_backtrace())
1203                 );
1204
1205                 // Send email to webmaster
1206                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1207         } // END - if
1208
1209         // And abort here
1210         app_die($F, $L, $debug);
1211 }
1212
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));
1217
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}', '%',
1228                 $code
1229         )))))))));
1230
1231         // Return compiled code
1232         return $code;
1233 }
1234
1235 // Handle message codes from URL
1236 function handleCodeMessage () {
1237         if (isGetRequestParameterSet('code')) {
1238                 // Default extension is 'unknown'
1239                 $ext = 'unknown';
1240
1241                 // Is extension given?
1242                 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1243
1244                 // Convert the 'code' parameter from URL to a human-readable message
1245                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1246
1247                 // Load message template
1248                 loadTemplate('message', false, $message);
1249         } // END - if
1250 }
1251
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.');
1258         } // END - if
1259
1260         // Default message
1261         $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1262
1263         // Is an admin logged in?
1264         if (isAdmin()) {
1265                 // Then output admin message
1266                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1267         } // END - if
1268
1269         // Return prepared message
1270         return $message;
1271 }
1272
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.');
1279         } // END - if
1280
1281         // Default message
1282         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1283
1284         // Is an admin logged in?
1285         if (isAdmin()) {
1286                 // Then output admin message
1287                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1288         } // END - if
1289
1290         // Return prepared message
1291         return $message;
1292 }
1293
1294 // Generates a message depending on if the extension is not installed or not
1295 // just activated
1296 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1297         // Init message
1298         $message = '';
1299
1300         // Is the extension not installed or just deactivated?
1301         switch (isExtensionInstalled($ext_name)) {
1302                 case true; // Deactivated!
1303                         $message = generateExtensionInactiveMessage($ext_name);
1304                         break;
1305
1306                 case false; // Not installed!
1307                         $message = generateExtensionNotInstalledMessage($ext_name);
1308                         break;
1309
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);
1313                         break;
1314         } // END - switch
1315
1316         // Return the message
1317         return $message;
1318 }
1319
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);
1324
1325         $r = 'Line | Code:<br />';
1326         foreach($codeE as $line => $c) {
1327                 $r .= '<div class="line"><span class="linenum">';
1328                 if ($count_lines == 1) {
1329                         $r .= 1;
1330                 } else {
1331                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
1332                 }
1333                 $r .= '</span>|';
1334
1335                 // Add code
1336                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1337         }
1338
1339         return '<div class="code">' . $r . '</div>';
1340 }
1341
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'))) {
1346                 // Init title
1347                 $TITLE = '';
1348
1349                 // Title decoration enabled?
1350                 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1351
1352                 // Do we have some extra title?
1353                 if (isExtraTitleSet()) {
1354                         // Then prepent it
1355                         $TITLE .= getExtraTitle() . ' by ';
1356                 } // END - if
1357
1358                 // Add main title
1359                 $TITLE .= getMainTitle();
1360
1361                 // Add title of module? (middle decoration will also be added!)
1362                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1363                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
1364                 } // END - if
1365
1366                 // Add title from what file
1367                 $mode = '';
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());
1371
1372                 // Add title decorations? (right)
1373                 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1374
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--}';
1386         } else {
1387                 // Configuration not found!
1388                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1389
1390                 // Do not add the fatal message in installation mode
1391                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1392         }
1393
1394         // Return title
1395         return decodeEntities($pageTitle);
1396 }
1397
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])) {
1402                 // Generate FQFN
1403                 $FQFN = generateCacheFqfn($template);
1404
1405                 // Is it there?
1406                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1407         } // END - if
1408
1409         // Return it
1410         return $GLOBALS['template_cache'][$template];
1411 }
1412
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')) {
1417                 // Generate FQFN
1418                 $FQFN = generateCacheFqfn($template);
1419
1420                 // And flush it
1421                 writeToFile($FQFN, $eval, true);
1422         } // END - if
1423 }
1424
1425 // Reads a template cache
1426 function readTemplateCache ($template) {
1427         // Check it again
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.');
1431         } // END - if
1432
1433         // Is it cached?
1434         if (!isset($GLOBALS['template_eval'][$template])) {
1435                 // Generate FQFN
1436                 $FQFN = generateCacheFqfn($template);
1437
1438                 // And read from it
1439                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1440         } // END - if
1441
1442         // And return it
1443         return $GLOBALS['template_eval'][$template];
1444 }
1445
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);
1452         } else {
1453                 // Remove escaping of single quotes
1454                 $str = str_replace("\'", "'", $str);
1455
1456                 // Escape only double-quotes but prevent double-quoting
1457                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1458         }
1459
1460         // Return the escaped string
1461         return $str;
1462 }
1463
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));
1468
1469         // Return it
1470         return $str;
1471 }
1472
1473 // Send out mails depending on the 'mod/modes' combination
1474 // @TODO Lame description for this function
1475 function sendModeMails ($mod, $modes) {
1476         // Load hash
1477         if (fetchUserData(getMemberId())) {
1478                 // Extract salt from cookie
1479                 $salt = substr(getSession('u_hash'), 0, -40);
1480
1481                 // Now let's compare passwords
1482                 $hash = encodeHashForCookie(getUserData('password'));
1483
1484                 // Does the hash match or should we change it?
1485                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1486                         // Load the data
1487                         $content = getUserDataArray();
1488
1489                         // Clear/init the content variable
1490                         $content['message'] = '';
1491
1492                         // Which mail?
1493                         // @TODO Move this in a filter
1494                         switch ($mod) {
1495                                 case 'mydata':
1496                                         foreach ($modes as $mode) {
1497                                                 switch ($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";
1501                                                                 break;
1502
1503                                                         case 'pass': // Password was changed
1504                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1505                                                                 break;
1506
1507                                                         default:
1508                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1509                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1510                                                                 break;
1511                                                 } // END - switch
1512                                         } // END - foreach
1513
1514                                         if (isExtensionActive('country')) {
1515                                                 // Replace code with description
1516                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1517                                         } // END - if
1518
1519                                         // Merge content with data from POST
1520                                         $content = merge_array($content, postRequestArray());
1521
1522                                         // Load template
1523                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1524
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--}';
1529                                         } else {
1530                                                 // No mail to admin
1531                                                 $message_admin = '';
1532                                                 $sub_adm   = '';
1533                                         }
1534
1535                                         // Set subject lines
1536                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1537
1538                                         // Output success message
1539                                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1540                                         break;
1541
1542                                 default: // Unsupported module!
1543                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1544                                         $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
1545                                         break;
1546                         } // END - switch
1547                 } else {
1548                         // Passwords mismatch
1549                         $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
1550                 }
1551         } else {
1552                 // Could not load profile
1553                 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1554         }
1555
1556         // Send email to user if required
1557         if ((!empty($sub_mem)) && (!empty($message))) {
1558                 // Send member mail
1559                 sendEmail($content['email'], $sub_mem, $message);
1560         } // END - if
1561
1562         // Send only if no other error has occured
1563         if (empty($content)) {
1564                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1565                         // Send admin mail
1566                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1567                 } elseif (isAdminNotificationEnabled()) {
1568                         // Cannot send mails to admin!
1569                         $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1570                 } else {
1571                         // No mail to admin
1572                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1573                 }
1574         } // END - if
1575
1576         // Load template
1577         loadTemplate('admin_settings_saved', false, $content);
1578 }
1579
1580 // Generates a 'selection box' from given array
1581 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1582         // Start the output
1583         $OUT = '<select name="' . $name . '" size="1" class="admin_select">
1584 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1585
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);
1592                 } else {
1593                         // Direct HTML code
1594                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1595                 }
1596         } // END - foreach
1597
1598         // Finish selection box
1599         $OUT .= '</select>';
1600
1601         // Prepare output
1602         $content = array(
1603                 'selection_box' => $OUT,
1604         );
1605
1606         // Load template and return it
1607         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1608 }
1609
1610 // Prepares the header for HTML output
1611 function loadHtmlHeader () {
1612         // Run two filters:
1613         // 1.) pre_page_header (mainly loads the page_header template and includes
1614         //     meta description)
1615         runFilterChain('pre_page_header');
1616
1617         // Here can be something be added, but normally one of the two filters
1618         // around this line should do the job for you.
1619
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');
1624 }
1625
1626 // Adds page header and footer to output array element
1627 function addPageHeaderFooter () {
1628         // Init output
1629         $OUT = '';
1630
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];
1635         } // END - foreach
1636
1637         // Transfer $OUT to 'output'
1638         $GLOBALS['output'] = $OUT;
1639 }
1640
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());
1647
1648                 // Output it directly
1649                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1650         } // END - if
1651
1652         // Remove depth
1653         unset($GLOBALS['ref_level']);
1654 }
1655
1656 // Generates an FQFN for template cache from the given template name
1657 function generateCacheFqfn ($template, $mode = 'html') {
1658         // Is this cached?
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",
1663                         getCachePath(),
1664                         $mode,
1665                         $template
1666                 );
1667         } // END - if
1668
1669         // Return it
1670         return $GLOBALS['template_cache_fqfn'][$template];
1671 }
1672
1673 // "Fixes" null or empty string to count of dashes
1674 function fixNullEmptyToDashes ($str, $num) {
1675         // Use str as default
1676         $return = $str;
1677
1678         // Is it empty?
1679         if ((is_null($str)) || (trim($str) == '')) {
1680                 // Set it
1681                 $return = str_repeat('-', $num);
1682         } // END - if
1683
1684         // Return final string
1685         return $return;
1686 }
1687
1688 // [EOF]
1689 ?>