Even more rewrites to make usage of EL
[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 (getOutputMode() != 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 (getConfig('OUTPUT_MODE')) {
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 ((getConfig('OUTPUT_MODE') == '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')) && (getOutputMode() != 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 < 4)) {
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) die('<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/", getConfig('PATH'), 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 (getOutputMode() == '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         {--TEMPLATE_DATA--}
355         <pre>' . print_r($DATA, true) . '</pre>
356 </div>';
357                 } else {
358                         // No file!
359                         $GLOBALS['template_eval'][$template] = '404';
360                 }
361         }
362
363         // Code set?
364         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
365                 // Eval the code
366                 eval($GLOBALS['template_eval'][$template]);
367         } // END - if
368
369         // Do we have some content to output or return?
370         if (!empty($ret)) {
371                 // Not empty so let's put it out! ;)
372                 if ($return === true) {
373                         // Return the HTML code
374                         return $ret;
375                 } else {
376                         // Output directly
377                         outputHtml($ret);
378                 }
379         } elseif (isDebugModeEnabled()) {
380                 // Warning, empty output!
381                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
382         }
383 }
384
385 // Detects the extra template path from given template name
386 function detectExtraTemplatePath ($template) {
387         // Default is empty
388         $extraPath = '';
389
390         // Do we have cache?
391         if (!isset($GLOBALS['extra_path'][$template])) {
392                 // Check for admin/guest/member/etc. templates
393                 if (substr($template, 0, 6) == 'admin_') {
394                         // Admin template found
395                         $extraPath = 'admin/';
396                 } elseif (substr($template, 0, 6) == 'guest_') {
397                         // Guest template found
398                         $extraPath = 'guest/';
399                 } elseif (substr($template, 0, 7) == 'member_') {
400                         // Member template found
401                         $extraPath = 'member/';
402                 } elseif (substr($template, 0, 7) == 'select_') {
403                         // Selection template found
404                         $extraPath = 'select/';
405                 } elseif (substr($template, 0, 8) == 'install_') {
406                         // Installation template found
407                         $extraPath = 'install/';
408                 } elseif (substr($template, 0, 4) == 'ext_') {
409                         // Extension template found
410                         $extraPath = 'ext/';
411                 } elseif (substr($template, 0, 3) == 'la_') {
412                         // 'Logical-area' template found
413                         $extraPath = 'la/';
414                 } elseif (substr($template, 0, 3) == 'js_') {
415                         // JavaScript template found
416                         $extraPath = 'js/';
417                 } elseif (substr($template, 0, 5) == 'menu_') {
418                         // Menu template found
419                         $extraPath = 'menu/';
420                 } else {
421                         // Test for extension
422                         $test = substr($template, 0, strpos($template, '_'));
423
424                         // Probe for valid extension name
425                         if (isExtensionNameValid($test)) {
426                                 // Set extra path to extension's name
427                                 $extraPath = $test . '/';
428                         } // END - if
429                 }
430
431                 // Store it in cache
432                 $GLOBALS['extra_path'][$template] = $extraPath;
433         } // END - if
434
435         // Return result
436         return $GLOBALS['extra_path'][$template];
437 }
438
439 // Loads an email template and compiles it
440 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
441         global $DATA;
442
443         // Make sure all template names are lowercase!
444         $template = strtolower($template);
445
446         // Is content an array?
447         if (is_array($content)) {
448                 // Add expiration to array
449                 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
450                         // Will never expire!
451                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
452                 } elseif (isConfigEntrySet('auto_purge')) {
453                         // Create nice date string
454                         $content['expiration'] = createFancyTime(getConfig('auto_purge'));
455                 } else {
456                         // Missing entry
457                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
458                 }
459         } // END - if
460
461         // Load user's data
462         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
463         if (($userid > 0) && (is_array($content))) {
464                 // If nickname extension is installed, fetch nickname as well
465                 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
466                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
467                         // Load by nickname
468                         fetchUserData($userid, 'nickname');
469                 } else {
470                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
471                         /// Load by userid
472                         fetchUserData($userid);
473                 }
474
475                 // Merge data if valid
476                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
477                 if (isUserDataValid()) {
478                         $content = merge_array($content, getUserDataArray());
479                 } // END - if
480                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
481         } // END - if
482
483         // Base directory
484         $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
485
486         // Detect extra path
487         $extraPath = detectExtraTemplatePath($template);
488
489         // Generate full FQFN
490         $FQFN = $basePath . $extraPath . $template . '.tpl';
491
492         // Does the special template exists?
493         if (!isFileReadable($FQFN)) {
494                 // Reset to default template
495                 $FQFN = $basePath . $template . '.tpl';
496         } // END - if
497
498         // Now does the final template exists?
499         $newContent = '';
500         if (isFileReadable($FQFN)) {
501                 // The local file does exists so we load it. :)
502                 $GLOBALS['tpl_content'] = readFromFile($FQFN);
503
504                 // Run code
505                 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
506                 eval($GLOBALS['tpl_content']);
507         } elseif (!empty($template)) {
508                 // Template file not found!
509                 $newContent = '<div class="para">
510         {--TEMPLATE_404--}: ' . $template . '
511 </div>
512 <div class="para">
513         {--TEMPLATE_CONTENT--}
514         <pre>' . print_r($content, true) . '</pre>
515         {--TEMPLATE_DATA--}
516         <pre>' . print_r($DATA, true) . '</pre>
517 </div>';
518
519                 // Debug mode not active? Then remove the HTML tags
520                 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
521         } else {
522                 // No template name supplied!
523                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
524         }
525
526         // Is there some content?
527         if (empty($newContent)) {
528                 // Compiling failed
529                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
530
531                 // Add last error if the required function exists
532                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
533         } // END - if
534
535         // Remove content and data
536         unset($content);
537         unset($DATA);
538
539         // Return content
540         return $newContent;
541 }
542
543 // "Getter" for menu CSS classes, mainly used in templates
544 function getMenuCssClasses ($data) {
545         // $data needs to be converted into an array
546         $content = explode('|', $data);
547
548         // Non-existent index 2 will happen in menu blocks
549         if (!isset($content[2])) $content[2] = '';
550
551         // Re-construct the array: 0=visible,1=locked,2=prefix
552         $content['visible'] = $content[0];
553         $content['locked']  = $content[1];
554
555         // Call our "translator" function
556         $content = translateMenuVisibleLocked($content, $content[2]);
557
558         // Return CSS classes
559         return ($content['visible_css'] . ' ' . $content['locked_css']);
560 }
561
562 // Generate XHTML code for the CAPTCHA
563 function generateCaptchaCode ($code, $type, $DATA, $userid) {
564         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '%}" />';
565 }
566
567 // Compiles the given HTML/mail code
568 function compileCode ($code, $simple = false, $constants = true, $full = true) {
569         // Is the code a string?
570         if (!is_string($code)) {
571                 // Silently return it
572                 return $code;
573         } // END - if
574
575         // Start couting
576         $startCompile = microtime(true);
577
578         // Comile the code
579         $code = compileRawCode($code, $simple, $constants, $full);
580
581         // Get timing
582         $compiled = microtime(true);
583
584         // Add timing if enabled
585         if (isTemplateHtml()) {
586                 // Add timing, this should be disabled in
587                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
588         } // END - if
589
590         // Return compiled code
591         return $code;
592 }
593
594 // Compiles the code (use compileCode() only for HTML because of the comments)
595 // @TODO $simple/$constants are deprecated
596 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
597         // Is the code a string?
598         if (!is_string($code)) {
599                 // Silently return it
600                 return $code;
601         } // END - if
602
603         // Init replacement-array with smaller set of security characters
604         $secChars = $GLOBALS['url_chars'];
605
606         // Select full set of chars to replace when we e.g. want to compile URLs
607         if ($full === true) $secChars = $GLOBALS['security_chars'];
608
609         // Compile more through a filter
610         $code = runFilterChain('compile_code', $code);
611
612         // Compile message strings
613         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
614
615         // Compile QUOT and other non-HTML codes
616         foreach ($secChars['to'] as $k => $to) {
617                 // Do the reversed thing as in inc/libs/security_functions.php
618                 $code = str_replace($to, $secChars['from'][$k], $code);
619         } // END - foreach
620
621         // Find $content[bla][blub] entries
622         // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
623         preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
624
625         // Are some matches found?
626         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
627                 // Replace all matches
628                 $matchesFound = array();
629                 foreach ($matches[0] as $key => $match) {
630                         // Fuzzy look has failed by default
631                         $fuzzyFound = false;
632
633                         // Fuzzy look on match if already found
634                         foreach ($matchesFound as $found => $set) {
635                                 // Get test part
636                                 $test = substr($found, 0, strlen($match));
637
638                                 // Does this entry exist?
639                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
640                                 if ($test == $match) {
641                                         // Match found!
642                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
643                                         $fuzzyFound = true;
644                                         break;
645                                 } // END - if
646                         } // END - foreach
647
648                         // Skip this entry?
649                         if ($fuzzyFound === true) continue;
650
651                         // Take all string elements
652                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
653                                 // Replace it in the code
654                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
655                                 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
656                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
657                                 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
658                                 $matchesFound[$match] = 1;
659                         } elseif (!isset($matchesFound[$match])) {
660                                 // Not yet replaced!
661                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
662                                 $code = str_replace($match, '".' . $match . '."', $code);
663                                 $matchesFound[$match] = 1;
664                         }
665                 } // END - foreach
666         } // END - if
667
668         // Return it
669         return $code;
670 }
671
672 //
673 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
674         $OUT = '';
675
676         if ($type == 'yn') {
677                 // This is a yes/no selection only!
678                 if ($id > 0) $prefix .= '[' . $id . ']';
679                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
680         } else {
681                 // Begin with regular selection box here
682                 if (!empty($prefix)) $prefix .= '_';
683                 $type2 = $type;
684                 if ($id > 0) $type2 .= '[' . $id . ']';
685                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
686         }
687
688         switch ($type) {
689                 case 'day': // Day
690                         for ($idx = 1; $idx < 32; $idx++) {
691                                 $OUT .= '<option value="' . $idx . '"';
692                                 if ($default == $idx) $OUT .= ' selected="selected"';
693                                 $OUT .= '>' . $idx . '</option>';
694                         } // END - for
695                         break;
696
697                 case 'month': // Month
698                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
699                                 $OUT .= '<option value="' . $idx . '"';
700                                 if ($default == $idx) $OUT .= ' selected="selected"';
701                                 $OUT .= '>' . $descr . '</option>';
702                         } // END - for
703                         break;
704
705                 case 'year': // Year
706                         // Get current year
707                         $year = date('Y', time());
708
709                         // Use configured min age or fixed?
710                         if (isExtensionInstalledAndNewer('order', '0.2.1')) {
711                                 // Configured
712                                 $startYear = $year - getConfig('min_age');
713                         } else {
714                                 // Fixed 16 years
715                                 $startYear = $year - 16;
716                         }
717
718                         // Calculate earliest year (100 years old people can still enter Internet???)
719                         $minYear = $year - 100;
720
721                         // Check if the default value is larger than minimum and bigger than actual year
722                         if (($default > $minYear) && ($default >= $year)) {
723                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
724                                         $OUT .= '<option value="' . $idx . '"';
725                                         if ($default == $idx) $OUT .= ' selected="selected"';
726                                         $OUT .= '>' . $idx . '</option>';
727                                 } // END - for
728                         } elseif ($default == -1) {
729                                 // Current year minus 1
730                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
731                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
732                                 } // END - for
733                         } else {
734                                 // Get current year and subtract the configured minimum age
735                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
736                                 // Calculate earliest year depending on extension version
737                                 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
738                                         // Use configured minimum age
739                                         $year = date('Y', time()) - getConfig('min_age');
740                                 } else {
741                                         // Use fixed 16 years age
742                                         $year = date('Y', time()) - 16;
743                                 }
744
745                                 // Construct year selection list
746                                 for ($idx = $minYear; $idx <= $year; $idx++) {
747                                         $OUT .= '<option value="' . $idx . '"';
748                                         if ($default == $idx) $OUT .= ' selected="selected"';
749                                         $OUT .= '>' . $idx . '</option>';
750                                 } // END - for
751                         }
752                         break;
753
754                 case 'sec':
755                 case 'min':
756                         for ($idx = 0; $idx < 60; $idx+=5) {
757                                 if (strlen($idx) == 1) $idx = '0' . $idx;
758                                 $OUT .= '<option value="' . $idx . '"';
759                                 if ($default == $idx) $OUT .= ' selected="selected"';
760                                 $OUT .= '>' . $idx . '</option>';
761                         } // END - for
762                         break;
763
764                 case 'hour':
765                         for ($idx = 0; $idx < 24; $idx++) {
766                                 if (strlen($idx) == 1) $idx = '0' . $idx;
767                                 $OUT .= '<option value="' . $idx . '"';
768                                 if ($default == $idx) $OUT .= ' selected="selected"';
769                                 $OUT .= '>' . $idx . '</option>';
770                         } // END - for
771                         break;
772
773                 case 'yn':
774                         $OUT .= '<option value="Y"';
775                         if ($default == 'Y') $OUT .= ' selected="selected"';
776                         $OUT .= '>{--YES--}</option><option value="N"';
777                         if ($default != 'Y') $OUT .= ' selected="selected"';
778                         $OUT .= '>{--NO--}</option>';
779                         break;
780         }
781         $OUT .= '</select>';
782         return $OUT;
783 }
784
785 // Insert the code in $img_code into jpeg or PNG image
786 function generateImageOrCode ($img_code, $headerSent = true) {
787         // Is the code size oversized or shouldn't we display it?
788         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
789                 // Stop execution of function here because of over-sized code length
790                 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
791         } elseif ($headerSent === false) {
792                 // Return an HTML code here
793                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
794         }
795
796         // Load image
797         $img = sprintf("%s/theme/%s/images/code_bg.%s",
798                 getConfig('PATH'),
799                 getCurrentTheme(),
800                 getConfig('img_type')
801         );
802
803         // Is it readable?
804         if (isFileReadable($img)) {
805                 // Switch image type
806                 switch (getConfig('img_type')) {
807                         case 'jpg':
808                                 // Okay, load image and hide all errors
809                                 $image = imagecreatefromjpeg($img);
810                                 break;
811
812                         case 'png':
813                                 // Okay, load image and hide all errors
814                                 $image = imagecreatefrompng($img);
815                                 break;
816                 } // END - switch
817         } else {
818                 // Exit function here
819                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
820                 return;
821         }
822
823         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
824         $text_color = imagecolorallocate($image, 0, 0, 0);
825
826         // Insert code into image
827         imagestring($image, 5, 14, 2, $img_code, $text_color);
828
829         // Return to browser
830         sendHeader('Content-Type: image/' . getConfig('img_type'));
831
832         // Output image with matching image factory
833         switch (getConfig('img_type')) {
834                 case 'jpg': imagejpeg($image); break;
835                 case 'png': imagepng($image);  break;
836         } // END - switch
837
838         // Remove image from memory
839         imagedestroy($image);
840 }
841 // Create selection box or array of splitted timestamp
842 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
843         // Do not continue if ONE_DAY is absend
844         if (!isConfigEntrySet('ONE_DAY')) {
845                 // And return the timestamp itself or empty array
846                 if ($return_array === true) {
847                         return array();
848                 } else {
849                         return $timestamp;
850                 }
851         } // END - if
852
853         // Calculate 2-seconds timestamp
854         $stamp = round($timestamp);
855         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
856
857         // Do we have a leap year?
858         $SWITCH = '0';
859         $TEST = date('Y', time()) / 4;
860         $M1 = date('m', time());
861         $M2 = date('m', (time() + $timestamp));
862
863         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
864         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  $SWITCH = getConfig('ONE_DAY');
865
866         // First of all years...
867         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
868         //* DEBUG: */ debugOutput('Y=' . $Y);
869         // Next months...
870         $M = abs(floor($timestamp / 2628000 - $Y * 12));
871         //* DEBUG: */ debugOutput('M=' . $M);
872         // Next weeks
873         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
874         //* DEBUG: */ debugOutput('W=' . $W);
875         // Next days...
876         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
877         //* DEBUG: */ debugOutput('D=' . $D);
878         // Next hours...
879         $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));
880         //* DEBUG: */ debugOutput('h=' . $h);
881         // Next minutes..
882         $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));
883         //* DEBUG: */ debugOutput('m=' . $m);
884         // And at last seconds...
885         $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));
886         //* DEBUG: */ debugOutput('s=' . $s);
887
888         // Is seconds zero and time is < 60 seconds?
889         if (($s == '0') && ($timestamp < 60)) {
890                 // Fix seconds
891                 $s = round($timestamp);
892         } // END - if
893
894         //
895         // Now we convert them in seconds...
896         //
897         if ($return_array) {
898                 // Just put all data in an array for later use
899                 $OUT = array(
900                         'YEARS'   => $Y,
901                         'MONTHS'  => $M,
902                         'WEEKS'   => $W,
903                         'DAYS'    => $D,
904                         'HOURS'   => $h,
905                         'MINUTES' => $m,
906                         'SECONDS' => $s
907                 );
908         } else {
909                 // Generate table
910                 $OUT  = '<div align="' . $align . '">';
911                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
912                 $OUT .= '<tr>';
913
914                 if (isInString('Y', $display) || (empty($display))) {
915                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
916                 } // END - if
917
918                 if (isInString('M', $display) || (empty($display))) {
919                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
920                 } // END - if
921
922                 if (isInString('W', $display) || (empty($display))) {
923                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
924                 } // END - if
925
926                 if (isInString('D', $display) || (empty($display))) {
927                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
928                 } // END - if
929
930                 if (isInString('h', $display) || (empty($display))) {
931                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
932                 } // END - if
933
934                 if (isInString('m', $display) || (empty($display))) {
935                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
936                 } // END - if
937
938                 if (isInString('s', $display) || (empty($display))) {
939                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
940                 } // END - if
941
942                 $OUT .= '</tr>';
943                 $OUT .= '<tr>';
944
945                 if (isInString('Y', $display) || (empty($display))) {
946                         // Generate year selection
947                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
948                         for ($idx = 0; $idx <= 10; $idx++) {
949                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
950                                 if ($idx == $Y) $OUT .= ' selected="selected"';
951                                 $OUT .= '>' . $idx . '</option>';
952                         } // END - for
953                         $OUT .= '</select></td>';
954                 } else {
955                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
956                 }
957
958                 if (isInString('M', $display) || (empty($display))) {
959                         // Generate month selection
960                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
961                         for ($idx = 0; $idx <= 11; $idx++) {
962                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
963                                 if ($idx == $M) $OUT .= ' selected="selected"';
964                                 $OUT .= '>' . $idx . '</option>';
965                         } // END - for
966                         $OUT .= '</select></td>';
967                 } else {
968                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
969                 }
970
971                 if (isInString('W', $display) || (empty($display))) {
972                         // Generate week selection
973                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
974                         for ($idx = 0; $idx <= 4; $idx++) {
975                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
976                                 if ($idx == $W) $OUT .= ' selected="selected"';
977                                 $OUT .= '>' . $idx . '</option>';
978                         } // END - for
979                         $OUT .= '</select></td>';
980                 } else {
981                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
982                 }
983
984                 if (isInString('D', $display) || (empty($display))) {
985                         // Generate day selection
986                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
987                         for ($idx = 0; $idx <= 31; $idx++) {
988                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
989                                 if ($idx == $D) $OUT .= ' selected="selected"';
990                                 $OUT .= '>' . $idx . '</option>';
991                         } // END - for
992                         $OUT .= '</select></td>';
993                 } else {
994                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
995                 }
996
997                 if (isInString('h', $display) || (empty($display))) {
998                         // Generate hour selection
999                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1000                         for ($idx = 0; $idx <= 23; $idx++) {
1001                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1002                                 if ($idx == $h) $OUT .= ' selected="selected"';
1003                                 $OUT .= '>' . $idx . '</option>';
1004                         } // END - for
1005                         $OUT .= '</select></td>';
1006                 } else {
1007                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1008                 }
1009
1010                 if (isInString('m', $display) || (empty($display))) {
1011                         // Generate minute selection
1012                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1013                         for ($idx = 0; $idx <= 59; $idx++) {
1014                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1015                                 if ($idx == $m) $OUT .= ' selected="selected"';
1016                                 $OUT .= '>' . $idx . '</option>';
1017                         } // END - for
1018                         $OUT .= '</select></td>';
1019                 } else {
1020                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1021                 }
1022
1023                 if (isInString('s', $display) || (empty($display))) {
1024                         // Generate second selection
1025                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1026                         for ($idx = 0; $idx <= 59; $idx++) {
1027                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1028                                 if ($idx == $s) $OUT .= ' selected="selected"';
1029                                 $OUT .= '>' . $idx . '</option>';
1030                         } // END - for
1031                         $OUT .= '</select></td>';
1032                 } else {
1033                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1034                 }
1035                 $OUT .= '</tr>';
1036                 $OUT .= '</table>';
1037                 $OUT .= '</div>';
1038         }
1039
1040         // Return generated HTML code
1041         return $OUT;
1042 }
1043
1044 // Generate a list of administrative links to a given userid
1045 function generateMemberAdminActionLinks ($userid) {
1046         // Make sure userid is a number
1047         if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1048
1049         // Define all main targets
1050         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1051
1052         // Get user status
1053         $status = getFetchedUserData('userid', $userid, 'status');
1054
1055         // Begin of navigation links
1056         $OUT = '[';
1057
1058         foreach ($targetArray as $tar) {
1059                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1060                 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1061                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1062                         // Locked accounts shall be unlocked
1063                         $OUT .= 'UNLOCK_USER';
1064                 } else {
1065                         // All other status is fine
1066                         $OUT .= strtoupper($tar);
1067                 }
1068                 $OUT .= '_TITLE--}">{--ADMIN_';
1069                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1070                         // Locked accounts shall be unlocked
1071                         $OUT .= 'UNLOCK_USER';
1072                 } else {
1073                         // All other status is fine
1074                         $OUT .= strtoupper($tar);
1075                 }
1076                 $OUT .= '--}</a></span>|';
1077         } // END - foreach
1078
1079         // Finish navigation link
1080         $OUT = substr($OUT, 0, -1) . ']';
1081
1082         // Return string
1083         return $OUT;
1084 }
1085
1086 // Generate an email link
1087 function generateEmailLink ($email, $table = 'admins') {
1088         // Default email link (INSECURE! Spammer can read this by harvester programs)
1089         $EMAIL = 'mailto:' . $email;
1090
1091         // Check for several extensions
1092         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1093                 // Create email link for contacting admin in guest area
1094                 $EMAIL = generateAdminEmailLink($email);
1095         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1096                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1097                 $EMAIL = generateUserEmailLink($email, 'admin');
1098         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1099                 // Create email link to contact sponsor within admin area (or like the link above?)
1100                 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1101         }
1102
1103         // Shall I close the link when there is no admin?
1104         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1105
1106         // Return email link
1107         return $EMAIL;
1108 }
1109
1110 // Output error messages in a fasioned way and die...
1111 function app_die ($F, $L, $message) {
1112         // Check if Script is already dieing and not let it kill itself another 1000 times
1113         if (!isset($GLOBALS['app_died'])) {
1114                 // Make sure, that the script realy realy diese here and now
1115                 $GLOBALS['app_died'] = true;
1116
1117                 // Set content type as text/html
1118                 setContentType('text/html');
1119
1120                 // Load header
1121                 loadIncludeOnce('inc/header.php');
1122
1123                 // Rewrite message for output
1124                 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1125
1126                 // Load the message template
1127                 loadTemplate('app_die_message', false, $message);
1128
1129                 // Load footer
1130                 loadIncludeOnce('inc/footer.php');
1131         } else {
1132                 // Script tried to kill itself twice
1133                 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1134         }
1135 }
1136
1137 // Display parsing time and number of SQL queries in footer
1138 function displayParsingTime () {
1139         // Is the timer started?
1140         if (!isset($GLOBALS['startTime'])) {
1141                 // Abort here
1142                 return false;
1143         } // END - if
1144
1145         // Get end time
1146         $endTime = microtime(true);
1147
1148         // "Explode" both times
1149         $start = explode(' ', $GLOBALS['startTime']);
1150         $end = explode(' ', $endTime);
1151         $runTime = $end[0] - $start[0];
1152         if ($runTime < 0) $runTime = '0';
1153
1154         // Prepare output
1155         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1156         $content = array(
1157                 'run_time' => $runTime,
1158                 'sql_time' => (getConfig('sql_time') * 1000),
1159         );
1160
1161         // Load the template
1162         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1163 }
1164
1165 // Output a debug backtrace to the user
1166 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1167         // Is this already called?
1168         if (isset($GLOBALS[__FUNCTION__])) {
1169                 // Other backtrace
1170                 print 'Message:'.$message.'<br />Backtrace:<pre>';
1171                 debug_print_backtrace();
1172                 die('</pre>');
1173         } // END - if
1174
1175         // Set this function as called
1176         $GLOBALS[__FUNCTION__] = true;
1177
1178         // Init message
1179         $debug = '';
1180
1181         // Is the optional message set?
1182         if (!empty($message)) {
1183                 // Use and log it
1184                 $debug = sprintf("Note: %s<br />\n",
1185                         $message
1186                 );
1187
1188                 // @TODO Add a little more infos here
1189                 logDebugMessage($F, $L, strip_tags($message));
1190         } // END - if
1191
1192         // Add output
1193         $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(getConfig('PATH'), '', getConfig('CACHE_PATH')) . 'debug.log</strong> in your report (you can now attach files):<pre>';
1194         $debug .= debug_get_printable_backtrace();
1195         $debug .= '</pre>';
1196         $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
1197         $debug .= '<div>Thank you for finding bugs.</div>';
1198
1199         // Send an email? (e.g. not wanted for evaluation errors)
1200         if (($sendEmail === true) && (!isInstallationPhase())) {
1201                 // Prepare content
1202                 $content = array(
1203                         'message'   => trim($message),
1204                         'backtrace' => trim(debug_get_mailable_backtrace())
1205                 );
1206
1207                 // Send email to webmaster
1208                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1209         } // END - if
1210
1211         // And abort here
1212         app_die($F, $L, $debug);
1213 }
1214
1215 // Compile characters which are allowed in URLs
1216 function compileUriCode ($code, $simple = true) {
1217         // Compile constants
1218         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1219
1220         // Compile QUOT and other non-HTML codes
1221         $code = str_replace('{DOT}', '.',
1222                 str_replace('{SLASH}', '/',
1223                 str_replace('{QUOT}', "'",
1224                 str_replace('{DOLLAR}', '$',
1225                 str_replace('{OPEN_ANCHOR}', '(',
1226                 str_replace('{CLOSE_ANCHOR}', ')',
1227                 str_replace('{OPEN_SQR}', '[',
1228                 str_replace('{CLOSE_SQR}', ']',
1229                 str_replace('{PER}', '%',
1230                 $code
1231         )))))))));
1232
1233         // Return compiled code
1234         return $code;
1235 }
1236
1237 // Handle message codes from URL
1238 function handleCodeMessage () {
1239         if (isGetRequestParameterSet('code')) {
1240                 // Default extension is 'unknown'
1241                 $ext = 'unknown';
1242
1243                 // Is extension given?
1244                 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1245
1246                 // Convert the 'code' parameter from URL to a human-readable message
1247                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1248
1249                 // Load message template
1250                 loadTemplate('message', false, $message);
1251         } // END - if
1252 }
1253
1254 // Generates a 'extension foo inactive' message
1255 function generateExtensionInactiveMessage ($ext_name) {
1256         // Is the extension empty?
1257         if (empty($ext_name)) {
1258                 // This should not happen
1259                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1260         } // END - if
1261
1262         // Default message
1263         $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1264
1265         // Is an admin logged in?
1266         if (isAdmin()) {
1267                 // Then output admin message
1268                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
1269         } // END - if
1270
1271         // Return prepared message
1272         return $message;
1273 }
1274
1275 // Generates a 'extension foo not installed' message
1276 function generateExtensionNotInstalledMessage ($ext_name) {
1277         // Is the extension empty?
1278         if (empty($ext_name)) {
1279                 // This should not happen
1280                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1281         } // END - if
1282
1283         // Default message
1284         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1285
1286         // Is an admin logged in?
1287         if (isAdmin()) {
1288                 // Then output admin message
1289                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1290         } // END - if
1291
1292         // Return prepared message
1293         return $message;
1294 }
1295
1296 // Generates a message depending on if the extension is not installed or not
1297 // just activated
1298 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1299         // Init message
1300         $message = '';
1301
1302         // Is the extension not installed or just deactivated?
1303         switch (isExtensionInstalled($ext_name)) {
1304                 case true; // Deactivated!
1305                         $message = generateExtensionInactiveMessage($ext_name);
1306                         break;
1307
1308                 case false; // Not installed!
1309                         $message = generateExtensionNotInstalledMessage($ext_name);
1310                         break;
1311
1312                 default: // Should not happen!
1313                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1314                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1315                         break;
1316         } // END - switch
1317
1318         // Return the message
1319         return $message;
1320 }
1321
1322 // Print code with line numbers
1323 function linenumberCode ($code)    {
1324         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1325         $count_lines = count($codeE);
1326
1327         $r = 'Line | Code:<br />';
1328         foreach($codeE as $line => $c) {
1329                 $r .= '<div class="line"><span class="linenum">';
1330                 if ($count_lines == 1) {
1331                         $r .= 1;
1332                 } else {
1333                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
1334                 }
1335                 $r .= '</span>|';
1336
1337                 // Add code
1338                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1339         }
1340
1341         return '<div class="code">' . $r . '</div>';
1342 }
1343
1344 // Determines the right page title
1345 function determinePageTitle () {
1346         // Config and database connection valid?
1347         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1348                 // Init title
1349                 $TITLE = '';
1350
1351                 // Title decoration enabled?
1352                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1353
1354                 // Do we have some extra title?
1355                 if (isExtraTitleSet()) {
1356                         // Then prepent it
1357                         $TITLE .= getExtraTitle() . ' by ';
1358                 } // END - if
1359
1360                 // Add main title
1361                 $TITLE .= getConfig('MAIN_TITLE');
1362
1363                 // Add title of module? (middle decoration will also be added!)
1364                 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1365                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
1366                 } // END - if
1367
1368                 // Add title from what file
1369                 $mode = '';
1370                 if (getModule() == 'login') $mode = 'member';
1371                 elseif (getModule() == 'index') $mode = 'guest';
1372                 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1373
1374                 // Add title decorations? (right)
1375                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1376
1377                 // Remember title in constant for the template
1378                 $pageTitle = $TITLE;
1379         } elseif ((isInstalled()) && (isAdminRegistered())) {
1380                 // Installed, admin registered but no ext-sql_patches
1381                 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
1382         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1383                 // Installed but no admin registered
1384                 $pageTitle = '{--SETUP_OF_MAILER--}';
1385         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1386                 // Installation mode
1387                 $pageTitle = '{--INSTALLATION_OF_MAILER--}';
1388         } else {
1389                 // Configuration not found!
1390                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1391
1392                 // Do not add the fatal message in installation mode
1393                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1394         }
1395
1396         // Return title
1397         return decodeEntities($pageTitle);
1398 }
1399
1400 // Checks wethere there is a cache file there. This function is cached.
1401 function isTemplateCached ($template) {
1402         // Do we have cached this result?
1403         if (!isset($GLOBALS['template_cache'][$template])) {
1404                 // Generate FQFN
1405                 $FQFN = generateCacheFqfn($template);
1406
1407                 // Is it there?
1408                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1409         } // END - if
1410
1411         // Return it
1412         return $GLOBALS['template_cache'][$template];
1413 }
1414
1415 // Flushes non-flushed template cache to disk
1416 function flushTemplateCache ($template, $eval) {
1417         // Is this cache flushed?
1418         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1419                 // Generate FQFN
1420                 $FQFN = generateCacheFqfn($template);
1421
1422                 // And flush it
1423                 writeToFile($FQFN, $eval, true);
1424         } // END - if
1425 }
1426
1427 // Reads a template cache
1428 function readTemplateCache ($template) {
1429         // Check it again
1430         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1431                 // This should not happen
1432                 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1433         } // END - if
1434
1435         // Is it cached?
1436         if (!isset($GLOBALS['template_eval'][$template])) {
1437                 // Generate FQFN
1438                 $FQFN = generateCacheFqfn($template);
1439
1440                 // And read from it
1441                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1442         } // END - if
1443
1444         // And return it
1445         return $GLOBALS['template_eval'][$template];
1446 }
1447
1448 // Escapes quotes (default is only double-quotes)
1449 function escapeQuotes ($str, $single = false) {
1450         // Should we escape all?
1451         if ($single === true) {
1452                 // Escape all (including null)
1453                 $str = addslashes($str);
1454         } else {
1455                 // Escape only double-quotes but prevent double-quoting
1456                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1457         }
1458
1459         // Return the escaped string
1460         return $str;
1461 }
1462
1463 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1464 function escapeJavaScriptQuotes ($str) {
1465         // Replace all double-quotes and secure back-ticks
1466         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1467
1468         // Return it
1469         return $str;
1470 }
1471
1472 // Send out mails depending on the 'mod/modes' combination
1473 // @TODO Lame description for this function
1474 function sendModeMails ($mod, $modes) {
1475         // Load hash
1476         if (fetchUserData(getMemberId())) {
1477                 // Extract salt from cookie
1478                 $salt = substr(getSession('u_hash'), 0, -40);
1479
1480                 // Now let's compare passwords
1481                 $hash = encodeHashForCookie(getUserData('password'));
1482
1483                 // Does the hash match or should we change it?
1484                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1485                         // Load the data
1486                         $content = getUserDataArray();
1487
1488                         // Clear/init the content variable
1489                         $content['message'] = '';
1490
1491                         // Which mail?
1492                         // @TODO Move this in a filter
1493                         switch ($mod) {
1494                                 case 'mydata':
1495                                         foreach ($modes as $mode) {
1496                                                 switch ($mode) {
1497                                                         case 'normal': break; // Do not add any special lines
1498                                                         case 'email': // Email was changed!
1499                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1500                                                                 break;
1501
1502                                                         case 'pass': // Password was changed
1503                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1504                                                                 break;
1505
1506                                                         default:
1507                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1508                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1509                                                                 break;
1510                                                 } // END - switch
1511                                         } // END - foreach
1512
1513                                         if (isExtensionActive('country')) {
1514                                                 // Replace code with description
1515                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1516                                         } // END - if
1517
1518                                         // Merge content with data from POST
1519                                         $content = merge_array($content, postRequestArray());
1520
1521                                         // Load template
1522                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1523
1524                                         if (getConfig('admin_notify') == 'Y') {
1525                                                 // The admin needs to be notified about a profile change
1526                                                 $message_admin = 'admin_mydata_notify';
1527                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1528                                         } else {
1529                                                 // No mail to admin
1530                                                 $message_admin = '';
1531                                                 $sub_adm   = '';
1532                                         }
1533
1534                                         // Set subject lines
1535                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1536
1537                                         // Output success message
1538                                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1539                                         break;
1540
1541                                 default: // Unsupported module!
1542                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1543                                         $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
1544                                         break;
1545                         } // END - switch
1546                 } else {
1547                         // Passwords mismatch
1548                         $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
1549                 }
1550         } else {
1551                 // Could not load profile
1552                 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1553         }
1554
1555         // Send email to user if required
1556         if ((!empty($sub_mem)) && (!empty($message))) {
1557                 // Send member mail
1558                 sendEmail($content['email'], $sub_mem, $message);
1559         } // END - if
1560
1561         // Send only if no other error has occured
1562         if (empty($content)) {
1563                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1564                         // Send admin mail
1565                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1566                 } elseif (getConfig('admin_notify') == 'Y') {
1567                         // Cannot send mails to admin!
1568                         $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1569                 } else {
1570                         // No mail to admin
1571                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
1572                 }
1573         } // END - if
1574
1575         // Load template
1576         loadTemplate('admin_settings_saved', false, $content);
1577 }
1578
1579 // Generates a 'selection box' from given array
1580 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1581         // Start the output
1582         $OUT = '<select name="' . $name . '" size="1" class="admin_select">
1583 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1584
1585         // Walk through all options
1586         foreach ($options as $option) {
1587                 // Add the <option> entry
1588                 if (empty($optionContent)) {
1589                         // ... from template
1590                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1591                 } else {
1592                         // Direct HTML code
1593                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1594                 }
1595         } // END - foreach
1596
1597         // Finish selection box
1598         $OUT .= '</select>';
1599
1600         // Prepare output
1601         $content = array(
1602                 'selection_box' => $OUT,
1603                 'module'        => getModule(),
1604                 'what'          => getWhat()
1605         );
1606
1607         // Load template and return it
1608         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1609 }
1610
1611 // Prepares the header for HTML output
1612 function loadHtmlHeader () {
1613         // Run two filters:
1614         // 1.) pre_page_header (mainly loads the page_header template and includes
1615         //     meta description)
1616         runFilterChain('pre_page_header');
1617
1618         // Here can be something be added, but normally one of the two filters
1619         // around this line should do the job for you.
1620
1621         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1622         //     to close the head-tag)
1623         // Include more header data here
1624         runFilterChain('post_page_header');
1625 }
1626
1627 // Adds page header and footer to output array element
1628 function addPageHeaderFooter () {
1629         // Init output
1630         $OUT = '';
1631
1632         // Add them all together. This is maybe to simple
1633         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1634                 // Add page part if set
1635                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1636         } // END - foreach
1637
1638         // Transfer $OUT to 'output'
1639         $GLOBALS['output'] = $OUT;
1640 }
1641
1642 // Generates meta description for current module and 'what' value
1643 function generateMetaDescriptionCode () {
1644         // Only include from guest area and if sql_patches has correct version
1645         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1646                 // Construct dynamic description
1647                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1648
1649                 // Output it directly
1650                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1651         } // END - if
1652
1653         // Remove depth
1654         unset($GLOBALS['ref_level']);
1655 }
1656
1657 // Generates an FQFN for template cache from the given template name
1658 function generateCacheFqfn ($template, $mode = 'html') {
1659         // Is this cached?
1660         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1661                 // Generate the FQFN
1662                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1663                         "%s_compiled/%s/%s.tpl.cache",
1664                         getConfig('CACHE_PATH'),
1665                         $mode,
1666                         $template
1667                 );
1668         } // END - if
1669
1670         // Return it
1671         return $GLOBALS['template_cache_fqfn'][$template];
1672 }
1673
1674 // "Fixes" null or empty string to count of dashes
1675 function fixNullEmptyToDashes ($str, $num) {
1676         // Use str as default
1677         $return = $str;
1678
1679         // Is it empty?
1680         if ((is_null($str)) || (trim($str) == '')) {
1681                 // Set it
1682                 $return = str_repeat('-', $num);
1683         } // END - if
1684
1685         // Return final string
1686         return $return;
1687 }
1688
1689 // [EOF]
1690 ?>