8f1349c454df6a6b5093b3c363c55b87b4b2dfc0
[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  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Wrapper until we merged to the EL branch
44 function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
45         return compileCode($code, false, true, $full);
46 }
47
48 // Setter for 'is_template_html'
49 function enableTemplateHtml ($enable = true) {
50         $GLOBALS['is_template_html'] = (bool) $enable;
51 }
52
53 // Checks wether the template is HTML or not by previously set flag
54 // Default: true
55 function isTemplateHtml () {
56         // Is the output_mode other than 0 (HTML), then no comments are enabled
57         if (!isHtmlOutputMode()) {
58                 // No HTML
59                 return false;
60         } else {
61                 // Maybe HTML?
62                 return $GLOBALS['is_template_html'];
63         }
64 }
65
66 // Wrapper for writing debug informations to the browser
67 function debugOutput ($message) {
68         outputHtml('<div class="debug_message">' . $message . '</div>');
69 }
70
71 // "Fixes" an empty string into three dashes (use for templates)
72 function fixEmptyContentToDashes ($str) {
73         // Trim the string
74         $str = trim($str);
75
76         // Is the string empty?
77         if (empty($str)) $str = '---';
78
79         // Return string
80         return $str;
81 }
82
83 // Init color switch
84 function initTemplateColorSwitch ($template) {
85         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
86         $GLOBALS['color_switch'][$template] = 2;
87 }
88
89 // "Getter" for color switch code
90 function getColorSwitchCode ($template) {
91         // Prepare the code
92         $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
93
94         // And return it
95         return $code;
96 }
97
98 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
99 function outputHtml ($htmlCode, $newLine = true) {
100         // Init output
101         if (!isset($GLOBALS['output'])) {
102                 $GLOBALS['output'] = '';
103         } // END - if
104
105         // Do we have HTML-Code here?
106         if (!empty($htmlCode)) {
107                 // Yes, so we handle it as you have configured
108                 switch (getOutputMode()) {
109                         case 'render':
110                                 // That's why you don't need any \n at the end of your HTML code... :-)
111                                 if (getPhpCaching() == 'on') {
112                                         // Output into PHP's internal buffer
113                                         outputRawCode($htmlCode);
114
115                                         // That's why you don't need any \n at the end of your HTML code... :-)
116                                         if ($newLine === true) print("\n");
117                                 } else {
118                                         // Render mode for old or lame servers...
119                                         $GLOBALS['output'] .= $htmlCode;
120
121                                         // That's why you don't need any \n at the end of your HTML code... :-)
122                                         if ($newLine === true) $GLOBALS['output'] .= "\n";
123                                 }
124                                 break;
125
126                         case 'direct':
127                                 // If we are switching from render to direct output rendered code
128                                 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
129
130                                 // The same as above... ^
131                                 outputRawCode($htmlCode);
132                                 if ($newLine === true) print("\n");
133                                 break;
134
135                         default:
136                                 // Huh, something goes wrong or maybe you have edited config.php ???
137                                 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
138                                 break;
139                 } // END - switch
140         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
141                 // Output cached HTML code
142                 $GLOBALS['output'] = ob_get_contents();
143
144                 // Clear output buffer for later output if output is found
145                 if (!empty($GLOBALS['output'])) {
146                         clearOutputBuffer();
147                 } // END - if
148
149                 // Send all HTTP headers
150                 sendHttpHeaders();
151
152                 // Compile and run finished rendered HTML code
153                 compileFinalOutput();
154
155                 // Output code here, DO NOT REMOVE! ;-)
156                 outputRawCode($GLOBALS['output']);
157         } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
158                 // Send all HTTP headers
159                 sendHttpHeaders();
160
161                 // Compile and run finished rendered HTML code
162                 compileFinalOutput();
163
164                 // Output code here, DO NOT REMOVE! ;-)
165                 outputRawCode($GLOBALS['output']);
166         } else {
167                 // And flush all headers
168                 flushHeaders();
169         }
170 }
171
172 // Compiles the final output
173 function compileFinalOutput () {
174         // Add page header and footer
175         addPageHeaderFooter();
176
177         // Do the final compilation
178         $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
179
180         // Extension 'rewrite' installed?
181         if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
182                 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
183         } // END - if
184
185         // Compress it?
186         /**
187          * @TODO On some pages this is buggy
188         if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
189                 // Compress it for HTTP gzip
190                 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9);
191
192                 // Add header
193                 sendHeader('Content-Encoding: gzip');
194         } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
195                 // Compress it for HTTP deflate
196                 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
197
198                 // Add header
199                 sendHeader('Content-Encoding: deflate');
200         }
201         */
202
203         // Add final length
204         sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
205
206         // Flush all headers
207         flushHeaders();
208 }
209
210 // Main compilation loop
211 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
212         // Insert comments? (Only valid with HTML templates, of course)
213         enableTemplateHtml($insertComments);
214
215         // Init counter
216         $cnt = 0;
217
218         // Compile all out
219         while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
220                 // Init common variables
221                 $content = array();
222                 $newContent = '';
223
224                 // Compile it
225                 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
226                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
227                 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
228                 eval($eval);
229                 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
230                 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
231
232                 // Was that eval okay?
233                 if (empty($newContent)) {
234                         // Something went wrong!
235                         debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
236                 } // END - if
237
238                 // Use it again
239                 $code = $newContent;
240
241                 // Count round
242                 $cnt++;
243         } // END - while
244
245         // Return the compiled code
246         return $code;
247 }
248
249 // Output the raw HTML code
250 function outputRawCode ($htmlCode) {
251         // Output stripped HTML code to avoid broken JavaScript code, etc.
252         print(str_replace('{BACK}', "\\", $htmlCode));
253
254         // Flush the output if only getPhpCaching() is not 'on'
255         if (getPhpCaching() != 'on') {
256                 // Flush it
257                 flush();
258         } // END - if
259 }
260
261 // Load a template file and return it's content (only it's name; do not use ' or ")
262 function loadTemplate ($template, $return = false, $content = array()) {
263         // @TODO Remove this sanity-check if all is fine
264         if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
265
266         // Set current template
267         $GLOBALS['current_template'] = $template;
268
269         // Do we have cache?
270         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
271                 // Evaluate the cache
272                 eval(readTemplateCache($template));
273         } elseif (!isset($GLOBALS['template_eval'][$template])) {
274                 // Make all template names lowercase
275                 $template = strtolower($template);
276
277                 // Init some data
278                 $ret = '';
279                 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
280
281                 // Base directory
282                 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
283                 $extraPath = detectExtraTemplatePath($template);;
284
285                 // Generate FQFN
286                 $FQFN = $basePath . $extraPath . $template . '.tpl';
287
288                 // Does the special template exists?
289                 if (!isFileReadable($FQFN)) {
290                         // Reset to default template
291                         $FQFN = $basePath . $template . '.tpl';
292                 } // END - if
293
294                 // Now does the final template exists?
295                 if (isFileReadable($FQFN)) {
296                         // Count the template load
297                         incrementConfigEntry('num_templates');
298
299                         // The local file does exists so we load it. :)
300                         $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
301
302                         // Do we have to compile the code?
303                         $ret = '';
304                         if ((strpos($GLOBALS['tpl_content'][$template], '$') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{--') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{?') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{%') !== false)) {
305                                 // Normal HTML output?
306                                 if (isHtmlOutputMode()) {
307                                         // Add surrounding HTML comments to help finding bugs faster
308                                         $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
309
310                                         // Prepare eval() command
311                                         $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
312                                 } elseif (substr($template, 0, 3) == 'js_') {
313                                         // JavaScripts don't like entities and timings
314                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template])) . '");';
315                                 } else {
316                                         // Prepare eval() command, other output doesn't like entities, maybe
317                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
318                                 }
319                         } else {
320                                 // Add surrounding HTML comments to help finding bugs faster
321                                 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
322                                 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
323                         } // END - if
324                 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
325                         // Only admins shall see this warning or when installation mode is active
326                         $ret = '<div class="para">
327         <span class="notice">{--TEMPLATE_404--}</span>
328 </div>
329 <div class="para">
330         (' . $template . ')
331 </div>
332 <div class="para">
333         {--TEMPLATE_CONTENT--}
334         <pre>' . print_r($content, true) . '</pre>
335 </div>';
336                 } else {
337                         // No file!
338                         $GLOBALS['template_eval'][$template] = '404';
339                 }
340         }
341
342         // Code set?
343         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
344                 // Eval the code
345                 eval($GLOBALS['template_eval'][$template]);
346         } // END - if
347
348         // Do we have some content to output or return?
349         if (!empty($ret)) {
350                 // Not empty so let's put it out! ;)
351                 if ($return === true) {
352                         // Return the HTML code
353                         return $ret;
354                 } else {
355                         // Output directly
356                         outputHtml($ret);
357                 }
358         } elseif (isDebugModeEnabled()) {
359                 // Warning, empty output!
360                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
361         }
362 }
363
364 // Detects the extra template path from given template name
365 function detectExtraTemplatePath ($template) {
366         // Default is empty
367         $extraPath = '';
368
369         // Do we have cache?
370         if (!isset($GLOBALS['extra_path'][$template])) {
371                 // Check for admin/guest/member/etc. templates
372                 if (substr($template, 0, 6) == 'admin_') {
373                         // Admin template found
374                         $extraPath = 'admin/';
375                 } elseif (substr($template, 0, 6) == 'guest_') {
376                         // Guest template found
377                         $extraPath = 'guest/';
378                 } elseif (substr($template, 0, 7) == 'member_') {
379                         // Member template found
380                         $extraPath = 'member/';
381                 } elseif (substr($template, 0, 7) == 'select_') {
382                         // Selection template found
383                         $extraPath = 'select/';
384                 } elseif (substr($template, 0, 8) == 'install_') {
385                         // Installation template found
386                         $extraPath = 'install/';
387                 } elseif (substr($template, 0, 4) == 'ext_') {
388                         // Extension template found
389                         $extraPath = 'ext/';
390                 } elseif (substr($template, 0, 3) == 'la_') {
391                         // 'Logical-area' template found
392                         $extraPath = 'la/';
393                 } elseif (substr($template, 0, 3) == 'js_') {
394                         // JavaScript template found
395                         $extraPath = 'js/';
396                 } elseif (substr($template, 0, 5) == 'menu_') {
397                         // Menu template found
398                         $extraPath = 'menu/';
399                 } else {
400                         // Test for extension
401                         $test = substr($template, 0, strpos($template, '_'));
402
403                         // Probe for valid extension name
404                         if (isExtensionNameValid($test)) {
405                                 // Set extra path to extension's name
406                                 $extraPath = $test . '/';
407                         } // END - if
408                 }
409
410                 // Store it in cache
411                 $GLOBALS['extra_path'][$template] = $extraPath;
412         } // END - if
413
414         // Return result
415         return $GLOBALS['extra_path'][$template];
416 }
417
418 // Loads an email template and compiles it
419 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
420         global $DATA;
421
422         // Make sure all template names are lowercase!
423         $template = strtolower($template);
424
425         // Is content an array?
426         if (is_array($content)) {
427                 // Add expiration to array
428                 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
429                         // Will never expire!
430                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
431                 } elseif (isConfigEntrySet('auto_purge')) {
432                         // Create nice date string
433                         $content['expiration'] = '{%pipe,getAutoPurge,createFancyTime%}';
434                 } else {
435                         // Missing entry
436                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
437                 }
438         } // END - if
439
440         // Load user's data
441         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
442         if ((isValidUserId($userid)) && (is_array($content))) {
443                 // If nickname extension is installed, fetch nickname as well
444                 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
445                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
446                         // Load by nickname
447                         fetchUserData($userid, 'nickname');
448                 } else {
449                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
450                         /// Load by userid
451                         fetchUserData($userid);
452                 }
453
454                 // Merge data if valid
455                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
456                 if (isUserDataValid()) {
457                         $content = merge_array($content, getUserDataArray());
458                 } // END - if
459                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
460         } // END - if
461
462         // Base directory
463         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
464
465         // Detect extra path
466         $extraPath = detectExtraTemplatePath($template);
467
468         // Generate full FQFN
469         $FQFN = $basePath . $extraPath . $template . '.tpl';
470
471         // Does the special template exists?
472         if (!isFileReadable($FQFN)) {
473                 // Reset to default template
474                 $FQFN = $basePath . $template . '.tpl';
475         } // END - if
476
477         // Now does the final template exists?
478         $newContent = '';
479         if (isFileReadable($FQFN)) {
480                 // The local file does exists so we load it. :)
481                 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
482
483                 // Run code
484                 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
485                 eval($GLOBALS['tpl_content'][$template]);
486         } elseif (!empty($template)) {
487                 // Template file not found!
488                 $newContent = '<div class="para">
489         {--TEMPLATE_404--}: ' . $template . '
490 </div>
491 <div class="para">
492         {--TEMPLATE_CONTENT--}
493         <pre>' . print_r($content, true) . '</pre>
494         {--TEMPLATE_DATA--}
495         <pre>' . print_r($DATA, true) . '</pre>
496 </div>';
497
498                 // Debug mode not active? Then remove the HTML tags
499                 if (!isDebugModeEnabled()) {
500                         // Remove HTML tags
501                         $newContent = secureString($newContent);
502                 } // END - if
503         } else {
504                 // No template name supplied!
505                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
506         }
507
508         // Is there some content?
509         if (empty($newContent)) {
510                 // Compiling failed
511                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
512
513                 // Add last error if the required function exists
514                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
515         } // END - if
516
517         // Remove content and data
518         unset($content);
519         unset($DATA);
520
521         // Return content
522         return $newContent;
523 }
524
525 // "Getter" for menu CSS classes, mainly used in templates
526 function getMenuCssClasses ($data) {
527         // $data needs to be converted into an array
528         $content = explode('|', $data);
529
530         // Non-existent index 2 will happen in menu blocks
531         if (!isset($content[2])) $content[2] = '';
532
533         // Re-construct the array: 0=visible,1=locked,2=prefix
534         $content['visible'] = $content[0];
535         $content['locked']  = $content[1];
536
537         // Call our "translator" function
538         $content = translateMenuVisibleLocked($content, $content[2]);
539
540         // Return CSS classes
541         return ($content['visible_css'] . ' ' . $content['locked_css']);
542 }
543
544 // Generate XHTML code for the CAPTCHA
545 function generateCaptchaCode ($code, $type, $DATA, $userid) {
546         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '%}" />';
547 }
548
549 // Compiles the given HTML/mail code
550 function compileCode ($code, $simple = false, $constants = true, $full = true) {
551         // Is the code a string?
552         if (!is_string($code)) {
553                 // Silently return it
554                 return $code;
555         } // END - if
556
557         // Start couting
558         $startCompile = microtime(true);
559
560         // Comile the code
561         $code = compileRawCode($code, $simple, $constants, $full);
562
563         // Get timing
564         $compiled = microtime(true);
565
566         // Add timing if enabled
567         if (isTemplateHtml()) {
568                 // Add timing, this should be disabled in
569                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
570         } // END - if
571
572         // Return compiled code
573         return $code;
574 }
575
576 // Compiles the code (use compileCode() only for HTML because of the comments)
577 // @TODO $simple/$constants are deprecated
578 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
579         // Is the code a string?
580         if (!is_string($code)) {
581                 // Silently return it
582                 return $code;
583         } // END - if
584
585         // Init replacement-array with smaller set of security characters
586         $secChars = $GLOBALS['url_chars'];
587
588         // Select full set of chars to replace when we e.g. want to compile URLs
589         if ($full === true) $secChars = $GLOBALS['security_chars'];
590
591         // Compile more through a filter
592         $code = runFilterChain('compile_code', $code);
593
594         // Compile message strings
595         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
596
597         // Compile QUOT and other non-HTML codes
598         foreach ($secChars['to'] as $k => $to) {
599                 // Do the reversed thing as in inc/libs/security_functions.php
600                 $code = str_replace($to, $secChars['from'][$k], $code);
601         } // END - foreach
602
603         // Find $content[bla][blub] entries
604         // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
605         preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
606
607         // Are some matches found?
608         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
609                 // Replace all matches
610                 $matchesFound = array();
611                 foreach ($matches[0] as $key => $match) {
612                         // Fuzzy look has failed by default
613                         $fuzzyFound = false;
614
615                         // Fuzzy look on match if already found
616                         foreach ($matchesFound as $found => $set) {
617                                 // Get test part
618                                 $test = substr($found, 0, strlen($match));
619
620                                 // Does this entry exist?
621                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
622                                 if ($test == $match) {
623                                         // Match found!
624                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
625                                         $fuzzyFound = true;
626                                         break;
627                                 } // END - if
628                         } // END - foreach
629
630                         // Skip this entry?
631                         if ($fuzzyFound === true) continue;
632
633                         // Take all string elements
634                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
635                                 // Replace it in the code
636                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
637                                 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
638                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
639                                 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
640                                 $matchesFound[$match] = 1;
641                         } elseif (!isset($matchesFound[$match])) {
642                                 // Not yet replaced!
643                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
644                                 $code = str_replace($match, '".' . $match . '."', $code);
645                                 $matchesFound[$match] = 1;
646                         }
647                 } // END - foreach
648         } // END - if
649
650         // Return it
651         return $code;
652 }
653
654 //
655 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
656         $OUT = '';
657
658         if ($type == 'yn') {
659                 // This is a yes/no selection only!
660                 if ($id > 0) $prefix .= '[' . $id . ']';
661                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
662         } else {
663                 // Begin with regular selection box here
664                 if (!empty($prefix)) $prefix .= '_';
665                 $type2 = $type;
666                 if ($id > 0) $type2 .= '[' . $id . ']';
667                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
668         }
669
670         switch ($type) {
671                 case 'day': // Day
672                         for ($idx = 1; $idx < 32; $idx++) {
673                                 $OUT .= '<option value="' . $idx . '"';
674                                 if ($default == $idx) $OUT .= ' selected="selected"';
675                                 $OUT .= '>' . $idx . '</option>';
676                         } // END - for
677                         break;
678
679                 case 'month': // Month
680                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
681                                 $OUT .= '<option value="' . $idx . '"';
682                                 if ($default == $idx) $OUT .= ' selected="selected"';
683                                 $OUT .= '>' . $descr . '</option>';
684                         } // END - for
685                         break;
686
687                 case 'year': // Year
688                         // Get current year
689                         $year = getYear();
690
691                         // Use configured min age or fixed?
692                         if (isExtensionInstalledAndNewer('order', '0.2.1')) {
693                                 // Configured
694                                 $startYear = $year - getConfig('min_age');
695                         } else {
696                                 // Fixed 16 years
697                                 $startYear = $year - 16;
698                         }
699
700                         // Calculate earliest year (100 years old people can still enter Internet???)
701                         $minYear = $year - 100;
702
703                         // Check if the default value is larger than minimum and bigger than actual year
704                         if (($default > $minYear) && ($default >= $year)) {
705                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
706                                         $OUT .= '<option value="' . $idx . '"';
707                                         if ($default == $idx) $OUT .= ' selected="selected"';
708                                         $OUT .= '>' . $idx . '</option>';
709                                 } // END - for
710                         } elseif ($default == -1) {
711                                 // Current year minus 1
712                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
713                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
714                                 } // END - for
715                         } else {
716                                 // Get current year and subtract the configured minimum age
717                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
718                                 // Calculate earliest year depending on extension version
719                                 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
720                                         // Use configured minimum age
721                                         $year = getYear() - getConfig('min_age');
722                                 } else {
723                                         // Use fixed 16 years age
724                                         $year = getYear() - 16;
725                                 }
726
727                                 // Construct year selection list
728                                 for ($idx = $minYear; $idx <= $year; $idx++) {
729                                         $OUT .= '<option value="' . $idx . '"';
730                                         if ($default == $idx) $OUT .= ' selected="selected"';
731                                         $OUT .= '>' . $idx . '</option>';
732                                 } // END - for
733                         }
734                         break;
735
736                 case 'sec':
737                 case 'min':
738                         for ($idx = 0; $idx < 60; $idx+=5) {
739                                 if (strlen($idx) == 1) $idx = '0' . $idx;
740                                 $OUT .= '<option value="' . $idx . '"';
741                                 if ($default == $idx) $OUT .= ' selected="selected"';
742                                 $OUT .= '>' . $idx . '</option>';
743                         } // END - for
744                         break;
745
746                 case 'hour':
747                         for ($idx = 0; $idx < 24; $idx++) {
748                                 if (strlen($idx) == 1) $idx = '0' . $idx;
749                                 $OUT .= '<option value="' . $idx . '"';
750                                 if ($default == $idx) $OUT .= ' selected="selected"';
751                                 $OUT .= '>' . $idx . '</option>';
752                         } // END - for
753                         break;
754
755                 case 'yn':
756                         $OUT .= '<option value="Y"';
757                         if ($default == 'Y') $OUT .= ' selected="selected"';
758                         $OUT .= '>{--YES--}</option><option value="N"';
759                         if ($default != 'Y') $OUT .= ' selected="selected"';
760                         $OUT .= '>{--NO--}</option>';
761                         break;
762         }
763         $OUT .= '</select>';
764         return $OUT;
765 }
766
767 // Insert the code in $img_code into jpeg or PNG image
768 function generateImageOrCode ($img_code, $headerSent = true) {
769         // Is the code size oversized or shouldn't we display it?
770         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
771                 // Stop execution of function here because of over-sized code length
772                 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
773         } elseif ($headerSent === false) {
774                 // Return an HTML code here
775                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
776         }
777
778         // Load image
779         $img = sprintf("%s/theme/%s/images/code_bg.%s",
780                 getPath(),
781                 getCurrentTheme(),
782                 getConfig('img_type')
783         );
784
785         // Is it readable?
786         if (isFileReadable($img)) {
787                 // Switch image type
788                 switch (getConfig('img_type')) {
789                         case 'jpg':
790                                 // Okay, load image and hide all errors
791                                 $image = imagecreatefromjpeg($img);
792                                 break;
793
794                         case 'png':
795                                 // Okay, load image and hide all errors
796                                 $image = imagecreatefrompng($img);
797                                 break;
798                 } // END - switch
799         } else {
800                 // Exit function here
801                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
802                 return;
803         }
804
805         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
806         $text_color = imagecolorallocate($image, 0, 0, 0);
807
808         // Insert code into image
809         imagestring($image, 5, 14, 2, $img_code, $text_color);
810
811         // Return to browser
812         sendHeader('Content-Type: image/' . getConfig('img_type'));
813
814         // Output image with matching image factory
815         switch (getConfig('img_type')) {
816                 case 'jpg': imagejpeg($image); break;
817                 case 'png': imagepng($image);  break;
818         } // END - switch
819
820         // Remove image from memory
821         imagedestroy($image);
822 }
823 // Create selection box or array of splitted timestamp
824 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
825         // Do not continue if ONE_DAY is absend
826         if (!isConfigEntrySet('ONE_DAY')) {
827                 // And return the timestamp itself or empty array
828                 if ($return_array === true) {
829                         return array();
830                 } else {
831                         return $timestamp;
832                 }
833         } // END - if
834
835         // Calculate 2-seconds timestamp
836         $stamp = round($timestamp);
837         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
838
839         // Do we have a leap year?
840         $SWITCH = '0';
841         $TEST = getYear() / 4;
842         $M1 = getMonth();
843         $M2 = getMonth(time() + $timestamp);
844
845         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
846         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  $SWITCH = getConfig('ONE_DAY');
847
848         // First of all years...
849         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
850         //* DEBUG: */ debugOutput('Y=' . $Y);
851         // Next months...
852         $M = abs(floor($timestamp / 2628000 - $Y * 12));
853         //* DEBUG: */ debugOutput('M=' . $M);
854         // Next weeks
855         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
856         //* DEBUG: */ debugOutput('W=' . $W);
857         // Next days...
858         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
859         //* DEBUG: */ debugOutput('D=' . $D);
860         // Next hours...
861         $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));
862         //* DEBUG: */ debugOutput('h=' . $h);
863         // Next minutes..
864         $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));
865         //* DEBUG: */ debugOutput('m=' . $m);
866         // And at last seconds...
867         $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));
868         //* DEBUG: */ debugOutput('s=' . $s);
869
870         // Is seconds zero and time is < 60 seconds?
871         if (($s == '0') && ($timestamp < 60)) {
872                 // Fix seconds
873                 $s = round($timestamp);
874         } // END - if
875
876         //
877         // Now we convert them in seconds...
878         //
879         if ($return_array) {
880                 // Just put all data in an array for later use
881                 $OUT = array(
882                         'YEARS'   => $Y,
883                         'MONTHS'  => $M,
884                         'WEEKS'   => $W,
885                         'DAYS'    => $D,
886                         'HOURS'   => $h,
887                         'MINUTES' => $m,
888                         'SECONDS' => $s
889                 );
890         } else {
891                 // Generate table
892                 $OUT  = '<div align="' . $align . '">';
893                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
894                 $OUT .= '<tr>';
895
896                 if (isInString('Y', $display) || (empty($display))) {
897                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
898                 } // END - if
899
900                 if (isInString('M', $display) || (empty($display))) {
901                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
902                 } // END - if
903
904                 if (isInString('W', $display) || (empty($display))) {
905                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
906                 } // END - if
907
908                 if (isInString('D', $display) || (empty($display))) {
909                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
910                 } // END - if
911
912                 if (isInString('h', $display) || (empty($display))) {
913                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</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">{--_MINUTES--}</strong></td>';
918                 } // END - if
919
920                 if (isInString('s', $display) || (empty($display))) {
921                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
922                 } // END - if
923
924                 $OUT .= '</tr>';
925                 $OUT .= '<tr>';
926
927                 if (isInString('Y', $display) || (empty($display))) {
928                         // Generate year selection
929                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
930                         for ($idx = 0; $idx <= 10; $idx++) {
931                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
932                                 if ($idx == $Y) $OUT .= ' selected="selected"';
933                                 $OUT .= '>' . $idx . '</option>';
934                         } // END - for
935                         $OUT .= '</select></td>';
936                 } else {
937                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
938                 }
939
940                 if (isInString('M', $display) || (empty($display))) {
941                         // Generate month selection
942                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
943                         for ($idx = 0; $idx <= 11; $idx++) {
944                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
945                                 if ($idx == $M) $OUT .= ' selected="selected"';
946                                 $OUT .= '>' . $idx . '</option>';
947                         } // END - for
948                         $OUT .= '</select></td>';
949                 } else {
950                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
951                 }
952
953                 if (isInString('W', $display) || (empty($display))) {
954                         // Generate week selection
955                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
956                         for ($idx = 0; $idx <= 4; $idx++) {
957                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
958                                 if ($idx == $W) $OUT .= ' selected="selected"';
959                                 $OUT .= '>' . $idx . '</option>';
960                         } // END - for
961                         $OUT .= '</select></td>';
962                 } else {
963                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
964                 }
965
966                 if (isInString('D', $display) || (empty($display))) {
967                         // Generate day selection
968                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
969                         for ($idx = 0; $idx <= 31; $idx++) {
970                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
971                                 if ($idx == $D) $OUT .= ' selected="selected"';
972                                 $OUT .= '>' . $idx . '</option>';
973                         } // END - for
974                         $OUT .= '</select></td>';
975                 } else {
976                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
977                 }
978
979                 if (isInString('h', $display) || (empty($display))) {
980                         // Generate hour selection
981                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
982                         for ($idx = 0; $idx <= 23; $idx++) {
983                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
984                                 if ($idx == $h) $OUT .= ' selected="selected"';
985                                 $OUT .= '>' . $idx . '</option>';
986                         } // END - for
987                         $OUT .= '</select></td>';
988                 } else {
989                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
990                 }
991
992                 if (isInString('m', $display) || (empty($display))) {
993                         // Generate minute selection
994                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
995                         for ($idx = 0; $idx <= 59; $idx++) {
996                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
997                                 if ($idx == $m) $OUT .= ' selected="selected"';
998                                 $OUT .= '>' . $idx . '</option>';
999                         } // END - for
1000                         $OUT .= '</select></td>';
1001                 } else {
1002                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1003                 }
1004
1005                 if (isInString('s', $display) || (empty($display))) {
1006                         // Generate second selection
1007                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1008                         for ($idx = 0; $idx <= 59; $idx++) {
1009                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1010                                 if ($idx == $s) $OUT .= ' selected="selected"';
1011                                 $OUT .= '>' . $idx . '</option>';
1012                         } // END - for
1013                         $OUT .= '</select></td>';
1014                 } else {
1015                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1016                 }
1017                 $OUT .= '</tr>';
1018                 $OUT .= '</table>';
1019                 $OUT .= '</div>';
1020         }
1021
1022         // Return generated HTML code
1023         return $OUT;
1024 }
1025
1026 // Generate a list of administrative links to a given userid
1027 function generateMemberAdminActionLinks ($userid) {
1028         // Make sure userid is a number
1029         if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1030
1031         // Define all main targets
1032         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1033
1034         // Get user status
1035         $status = getFetchedUserData('userid', $userid, 'status');
1036
1037         // Begin of navigation links
1038         $OUT = '[';
1039
1040         foreach ($targetArray as $tar) {
1041                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1042                 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1043                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1044                         // Locked accounts shall be unlocked
1045                         $OUT .= 'UNLOCK_USER';
1046                 } elseif ($tar == 'del_user') {
1047                         // @TODO Deprecate this thing
1048                         $OUT .= 'DELETE_USER';
1049                 } else {
1050                         // All other status is fine
1051                         $OUT .= strtoupper($tar);
1052                 }
1053                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1054                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1055                         // Locked accounts shall be unlocked
1056                         $OUT .= 'UNLOCK_USER';
1057                 } elseif ($tar == 'del_user') {
1058                         // @TODO Deprecate this thing
1059                         $OUT .= 'DELETE_USER';
1060                 } else {
1061                         // All other status is fine
1062                         $OUT .= strtoupper($tar);
1063                 }
1064                 $OUT .= '--}</a></span>|';
1065         } // END - foreach
1066
1067         // Finish navigation link
1068         $OUT = substr($OUT, 0, -1) . ']';
1069
1070         // Return string
1071         return $OUT;
1072 }
1073
1074 // Generate an email link
1075 function generateEmailLink ($email, $table = 'admins') {
1076         // Default email link (INSECURE! Spammer can read this by harvester programs)
1077         $EMAIL = 'mailto:' . $email;
1078
1079         // Check for several extensions
1080         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1081                 // Create email link for contacting admin in guest area
1082                 $EMAIL = generateAdminEmailLink($email);
1083         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1084                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1085                 $EMAIL = generateUserEmailLink($email);
1086         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1087                 // Create email link to contact sponsor within admin area (or like the link above?)
1088                 $EMAIL = generateSponsorEmailLink($email);
1089         }
1090
1091         // Shall I close the link when there is no admin?
1092         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1093
1094         // Return email link
1095         return $EMAIL;
1096 }
1097
1098 // Output error messages in a fasioned way and die...
1099 function app_die ($F, $L, $message) {
1100         // Check if Script is already dieing and not let it kill itself another 1000 times
1101         if (!isset($GLOBALS['app_died'])) {
1102                 // Make sure, that the script realy realy diese here and now
1103                 $GLOBALS['app_died'] = true;
1104
1105                 // Set content type as text/html
1106                 setContentType('text/html');
1107
1108                 // Load header
1109                 loadIncludeOnce('inc/header.php');
1110
1111                 // Rewrite message for output
1112                 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1113
1114                 // Load the message template
1115                 loadTemplate('app_die_message', false, $message);
1116
1117                 // Load footer
1118                 loadIncludeOnce('inc/footer.php');
1119         } else {
1120                 // Script tried to kill itself twice
1121                 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1122         }
1123 }
1124
1125 // Display parsing time and number of SQL queries in footer
1126 function displayParsingTime () {
1127         // Is the timer started?
1128         if (!isset($GLOBALS['startTime'])) {
1129                 // Abort here
1130                 return false;
1131         } // END - if
1132
1133         // Get end time
1134         $endTime = microtime(true);
1135
1136         // "Explode" both times
1137         $start = explode(' ', $GLOBALS['startTime']);
1138         $end = explode(' ', $endTime);
1139         $runTime = $end[0] - $start[0];
1140         if ($runTime < 0) {
1141                 $runTime = '0';
1142         } // END - if
1143
1144         // Prepare output
1145         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1146         $content = array(
1147                 'run_time' => $runTime,
1148                 'sql_time' => (getConfig('sql_time') * 1000),
1149         );
1150
1151         // Load the template
1152         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1153 }
1154
1155 // Output a debug backtrace to the user
1156 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1157         // Is this already called?
1158         if (isset($GLOBALS[__FUNCTION__])) {
1159                 // Other backtrace
1160                 print 'Message:' . $message . '<br />Backtrace:<pre>';
1161                 debug_print_backtrace();
1162                 die('</pre>');
1163         } // END - if
1164
1165         // Set this function as called
1166         $GLOBALS[__FUNCTION__] = true;
1167
1168         // Init message
1169         $debug = '';
1170
1171         // Is the optional message set?
1172         if (!empty($message)) {
1173                 // Use and log it
1174                 $debug = sprintf("Note: %s<br />\n",
1175                         $message
1176                 );
1177
1178                 // @TODO Add a little more infos here
1179                 logDebugMessage($F, $L, strip_tags($message));
1180         } // END - if
1181
1182         // Add output
1183         $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>';
1184         $debug .= debug_get_printable_backtrace();
1185         $debug .= '</pre>';
1186         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1187         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1188
1189         // Send an email? (e.g. not wanted for evaluation errors)
1190         if (($sendEmail === true) && (!isInstallationPhase())) {
1191                 // Prepare content
1192                 $content = array(
1193                         'message'   => trim($message),
1194                         'backtrace' => trim(debug_get_mailable_backtrace())
1195                 );
1196
1197                 // Send email to webmaster
1198                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1199         } // END - if
1200
1201         // And abort here
1202         app_die($F, $L, $debug);
1203 }
1204
1205 // Compile characters which are allowed in URLs
1206 function compileUriCode ($code, $simple = true) {
1207         // Compile constants
1208         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1209
1210         // Compile QUOT and other non-HTML codes
1211         $code = str_replace('{DOT}', '.',
1212                 str_replace('{SLASH}', '/',
1213                 str_replace('{QUOT}', "'",
1214                 str_replace('{DOLLAR}', '$',
1215                 str_replace('{OPEN_ANCHOR}', '(',
1216                 str_replace('{CLOSE_ANCHOR}', ')',
1217                 str_replace('{OPEN_SQR}', '[',
1218                 str_replace('{CLOSE_SQR}', ']',
1219                 str_replace('{PER}', '%',
1220                 $code
1221         )))))))));
1222
1223         // Return compiled code
1224         return $code;
1225 }
1226
1227 // Handle message codes from URL
1228 function handleCodeMessage () {
1229         if (isGetRequestParameterSet('code')) {
1230                 // Default extension is 'unknown'
1231                 $ext = 'unknown';
1232
1233                 // Is extension given?
1234                 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1235
1236                 // Convert the 'code' parameter from URL to a human-readable message
1237                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1238
1239                 // Load message template
1240                 loadTemplate('message', false, $message);
1241         } // END - if
1242 }
1243
1244 // Generates a 'extension foo inactive' message
1245 function generateExtensionInactiveMessage ($ext_name) {
1246         // Is the extension empty?
1247         if (empty($ext_name)) {
1248                 // This should not happen
1249                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1250         } // END - if
1251
1252         // Default message
1253         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1254
1255         // Is an admin logged in?
1256         if (isAdmin()) {
1257                 // Then output admin message
1258                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1259         } // END - if
1260
1261         // Return prepared message
1262         return $message;
1263 }
1264
1265 // Generates a 'extension foo not installed' message
1266 function generateExtensionNotInstalledMessage ($ext_name) {
1267         // Is the extension empty?
1268         if (empty($ext_name)) {
1269                 // This should not happen
1270                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1271         } // END - if
1272
1273         // Default message
1274         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1275
1276         // Is an admin logged in?
1277         if (isAdmin()) {
1278                 // Then output admin message
1279                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1280         } // END - if
1281
1282         // Return prepared message
1283         return $message;
1284 }
1285
1286 // Generates a message depending on if the extension is not installed or not
1287 // just activated
1288 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1289         // Init message
1290         $message = '';
1291
1292         // Is the extension not installed or just deactivated?
1293         switch (isExtensionInstalled($ext_name)) {
1294                 case true; // Deactivated!
1295                         $message = generateExtensionInactiveMessage($ext_name);
1296                         break;
1297
1298                 case false; // Not installed!
1299                         $message = generateExtensionNotInstalledMessage($ext_name);
1300                         break;
1301
1302                 default: // Should not happen!
1303                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1304                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1305                         break;
1306         } // END - switch
1307
1308         // Return the message
1309         return $message;
1310 }
1311
1312 // Print code with line numbers
1313 function linenumberCode ($code)    {
1314         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1315         $count_lines = count($codeE);
1316
1317         $r = 'Line | Code:<br />';
1318         foreach($codeE as $line => $c) {
1319                 $r .= '<div class="line"><span class="linenum">';
1320                 if ($count_lines == 1) {
1321                         $r .= 1;
1322                 } else {
1323                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
1324                 }
1325                 $r .= '</span>|';
1326
1327                 // Add code
1328                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1329         }
1330
1331         return '<div class="code">' . $r . '</div>';
1332 }
1333
1334 // Determines the right page title
1335 function determinePageTitle () {
1336         // Config and database connection valid?
1337         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1338                 // Init title
1339                 $TITLE = '';
1340
1341                 // Title decoration enabled?
1342                 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1343
1344                 // Do we have some extra title?
1345                 if (isExtraTitleSet()) {
1346                         // Then prepent it
1347                         $TITLE .= getExtraTitle() . ' by ';
1348                 } // END - if
1349
1350                 // Add main title
1351                 $TITLE .= getMainTitle();
1352
1353                 // Add title of module? (middle decoration will also be added!)
1354                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1355                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1356                 } // END - if
1357
1358                 // Add title from what file
1359                 $mode = '';
1360                 if (getModule() == 'login') $mode = 'member';
1361                 elseif (getModule() == 'index') $mode = 'guest';
1362                 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1363
1364                 // Add title decorations? (right)
1365                 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1366
1367                 // Remember title in constant for the template
1368                 $pageTitle = $TITLE;
1369         } elseif ((isInstalled()) && (isAdminRegistered())) {
1370                 // Installed, admin registered but no ext-sql_patches
1371                 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1372         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1373                 // Installed but no admin registered
1374                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1375         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1376                 // Installation mode
1377                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1378         } else {
1379                 // Configuration not found!
1380                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1381
1382                 // Do not add the fatal message in installation mode
1383                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1384         }
1385
1386         // Return title
1387         return decodeEntities($pageTitle);
1388 }
1389
1390 // Checks wethere there is a cache file there. This function is cached.
1391 function isTemplateCached ($template) {
1392         // Do we have cached this result?
1393         if (!isset($GLOBALS['template_cache'][$template])) {
1394                 // Generate FQFN
1395                 $FQFN = generateCacheFqfn($template);
1396
1397                 // Is it there?
1398                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1399         } // END - if
1400
1401         // Return it
1402         return $GLOBALS['template_cache'][$template];
1403 }
1404
1405 // Flushes non-flushed template cache to disk
1406 function flushTemplateCache ($template, $eval) {
1407         // Is this cache flushed?
1408         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1409                 // Generate FQFN
1410                 $FQFN = generateCacheFqfn($template);
1411
1412                 // And flush it
1413                 writeToFile($FQFN, $eval, true);
1414         } // END - if
1415 }
1416
1417 // Reads a template cache
1418 function readTemplateCache ($template) {
1419         // Check it again
1420         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1421                 // This should not happen
1422                 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1423         } // END - if
1424
1425         // Is it cached?
1426         if (!isset($GLOBALS['template_eval'][$template])) {
1427                 // Generate FQFN
1428                 $FQFN = generateCacheFqfn($template);
1429
1430                 // And read from it
1431                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1432         } // END - if
1433
1434         // And return it
1435         return $GLOBALS['template_eval'][$template];
1436 }
1437
1438 // Escapes quotes (default is only double-quotes)
1439 function escapeQuotes ($str, $single = false) {
1440         // Should we escape all?
1441         if ($single === true) {
1442                 // Escape all (including null)
1443                 $str = addslashes($str);
1444         } else {
1445                 // Remove escaping of single quotes
1446                 $str = str_replace("\'", "'", $str);
1447
1448                 // Escape only double-quotes but prevent double-quoting
1449                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1450         }
1451
1452         // Return the escaped string
1453         return $str;
1454 }
1455
1456 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1457 function escapeJavaScriptQuotes ($str) {
1458         // Replace all double-quotes and secure back-ticks
1459         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1460
1461         // Return it
1462         return $str;
1463 }
1464
1465 // Send out mails depending on the 'mod/modes' combination
1466 // @TODO Lame description for this function
1467 function sendModeMails ($mod, $modes) {
1468         // Load hash
1469         if (fetchUserData(getMemberId())) {
1470                 // Extract salt from cookie
1471                 $salt = substr(getSession('u_hash'), 0, -40);
1472
1473                 // Now let's compare passwords
1474                 $hash = encodeHashForCookie(getUserData('password'));
1475
1476                 // Does the hash match or should we change it?
1477                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1478                         // Load the data
1479                         $content = getUserDataArray();
1480
1481                         // Clear/init the content variable
1482                         $content['message'] = '';
1483
1484                         // Which mail?
1485                         // @TODO Move this in a filter
1486                         switch ($mod) {
1487                                 case 'mydata':
1488                                         foreach ($modes as $mode) {
1489                                                 switch ($mode) {
1490                                                         case 'normal': break; // Do not add any special lines
1491                                                         case 'email': // Email was changed!
1492                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1493                                                                 break;
1494
1495                                                         case 'password': // Password was changed
1496                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1497                                                                 break;
1498
1499                                                         default:
1500                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1501                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1502                                                                 break;
1503                                                 } // END - switch
1504                                         } // END - foreach
1505
1506                                         if (isExtensionActive('country')) {
1507                                                 // Replace code with description
1508                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1509                                         } // END - if
1510
1511                                         // Merge content with data from POST
1512                                         $content = merge_array($content, postRequestArray());
1513
1514                                         // Load template
1515                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1516
1517                                         if (isAdminNotificationEnabled()) {
1518                                                 // The admin needs to be notified about a profile change
1519                                                 $message_admin = 'admin_mydata_notify';
1520                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1521                                         } else {
1522                                                 // No mail to admin
1523                                                 $message_admin = '';
1524                                                 $sub_adm   = '';
1525                                         }
1526
1527                                         // Set subject lines
1528                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1529
1530                                         // Output success message
1531                                         $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1532                                         break;
1533
1534                                 default: // Unsupported module!
1535                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1536                                         $content = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1537                                         break;
1538                         } // END - switch
1539                 } else {
1540                         // Passwords mismatch
1541                         $content = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1542                 }
1543         } else {
1544                 // Could not load profile
1545                 $content = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1546         }
1547
1548         // Send email to user if required
1549         if ((!empty($sub_mem)) && (!empty($message))) {
1550                 // Send member mail
1551                 sendEmail($content['email'], $sub_mem, $message);
1552         } // END - if
1553
1554         // Send only if no other error has occured
1555         if (empty($content)) {
1556                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1557                         // Send admin mail
1558                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1559                 } elseif (isAdminNotificationEnabled()) {
1560                         // Cannot send mails to admin!
1561                         $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1562                 } else {
1563                         // No mail to admin
1564                         $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1565                 }
1566         } // END - if
1567
1568         // Load template
1569         loadTemplate('admin_settings_saved', false, $content);
1570 }
1571
1572 // Generates a 'selection box' from given array
1573 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1574         // Start the output
1575         $OUT = '<select name="' . $name . '" size="1" class="form_select">
1576 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1577
1578         // Walk through all options
1579         foreach ($options as $option) {
1580                 // Add the <option> entry
1581                 if (empty($optionContent)) {
1582                         // ... from template
1583                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1584                 } else {
1585                         // Direct HTML code
1586                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1587                 }
1588         } // END - foreach
1589
1590         // Finish selection box
1591         $OUT .= '</select>';
1592
1593         // Prepare output
1594         $content = array(
1595                 'selection_box' => $OUT,
1596         );
1597
1598         // Load template and return it
1599         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1600 }
1601
1602 // Prepares the header for HTML output
1603 function loadHtmlHeader () {
1604         // Run two filters:
1605         // 1.) pre_page_header (mainly loads the page_header template and includes
1606         //     meta description)
1607         runFilterChain('pre_page_header');
1608
1609         // Here can be something be added, but normally one of the two filters
1610         // around this line should do the job for you.
1611
1612         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1613         //     to close the head-tag)
1614         // Include more header data here
1615         runFilterChain('post_page_header');
1616 }
1617
1618 // Adds page header and footer to output array element
1619 function addPageHeaderFooter () {
1620         // Init output
1621         $OUT = '';
1622
1623         // Add them all together. This is maybe to simple
1624         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1625                 // Add page part if set
1626                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1627         } // END - foreach
1628
1629         // Transfer $OUT to 'output'
1630         $GLOBALS['output'] = $OUT;
1631 }
1632
1633 // Generates meta description for current module and 'what' value
1634 function generateMetaDescriptionCode () {
1635         // Only include from guest area and if sql_patches has correct version
1636         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1637                 // Construct dynamic description
1638                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1639
1640                 // Output it directly
1641                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1642         } // END - if
1643
1644         // Remove depth
1645         unset($GLOBALS['ref_level']);
1646 }
1647
1648 // Generates an FQFN for template cache from the given template name
1649 function generateCacheFqfn ($template, $mode = 'html') {
1650         // Is this cached?
1651         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1652                 // Generate the FQFN
1653                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1654                         "%s_compiled/%s/%s.tpl.cache",
1655                         getCachePath(),
1656                         $mode,
1657                         $template
1658                 );
1659         } // END - if
1660
1661         // Return it
1662         return $GLOBALS['template_cache_fqfn'][$template];
1663 }
1664
1665 // "Fixes" null or empty string to count of dashes
1666 function fixNullEmptyToDashes ($str, $num) {
1667         // Use str as default
1668         $return = $str;
1669
1670         // Is it empty?
1671         if ((is_null($str)) || (trim($str) == '')) {
1672                 // Set it
1673                 $return = str_repeat('-', $num);
1674         } // END - if
1675
1676         // Return final string
1677         return $return;
1678 }
1679
1680 //-----------------------------------------------------------------------------
1681 //                       Template Helper Functions
1682 //-----------------------------------------------------------------------------
1683
1684 // Color-switch helper function
1685 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1686         // Is it there?
1687         if (!isset($GLOBALS['color_switch'][$template])) {
1688                 // Initialize it
1689                 initTemplateColorSwitch($template);
1690         } elseif ($clear === false) {
1691                 // Switch color if called from loadTemplate()
1692                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1693                 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1694         } // END - if
1695
1696         // Return CSS class name
1697         if ($return === true) {
1698                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1699                 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1700         } // END - if
1701 }
1702
1703 // Helper function for extension registration link
1704 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1705         // Default is all productive
1706         $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&amp;what=extensions&amp;reg_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
1707
1708         // Is the given extension non-productive?
1709         if (!isExtensionProductive($ext_name)) {
1710                 // Non-productive code
1711                 $OUT = '<em style="cursor:help" class="notice" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</em>';
1712         } // END - if
1713
1714         // Return code
1715         return $OUT;
1716 }
1717
1718 // [EOF]
1719 ?>