73d0de026f2ef828888290dd5d92bb77952c2ef0
[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 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://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 whether 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         // Call inner function
74         $str = fixNullEmptyToDashes($str, 3);
75
76         // Return string
77         return $str;
78 }
79
80 // Init color switch
81 function initTemplateColorSwitch ($template) {
82         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
83         $GLOBALS['color_switch'][$template] = 2;
84 }
85
86 // "Getter" for color switch code
87 function getColorSwitchCode ($template) {
88         // Prepare the code
89         $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
90
91         // And return it
92         return $code;
93 }
94
95 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
96 function outputHtml ($htmlCode, $newLine = true) {
97         // Init output
98         if (!isset($GLOBALS['__output'])) {
99                 $GLOBALS['__output'] = '';
100         } // END - if
101
102         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getOutputMode()=' . getOutputMode() . ',htmlCode(length)=' . strlen($htmlCode) . ',output(length)=' . strlen($GLOBALS['__output']));
103         // Do we have HTML-Code here?
104         if (!empty($htmlCode)) {
105                 // Yes, so we handle it as you have configured
106                 switch (getOutputMode()) {
107                         case 'render':
108                                 // But if PHP is caching, then we don't need to do that
109                                 if (getPhpCaching() == 'on') {
110                                         // Output into PHP's internal buffer
111                                         outputRawCode($htmlCode);
112
113                                         // That's why you don't need any \n at the end of your HTML code... :-)
114                                         if ($newLine === true) {
115                                                 outputRawCode(chr(10));
116                                         } // END - if
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) {
123                                                 $GLOBALS['__output'] .= chr(10);
124                                         } // END - if
125                                 }
126                                 break;
127
128                         case 'direct':
129                                 // If we are switching from 'render' to 'direct' mode, all data in '__output' must be flushed and cleared
130                                 if ((!empty($GLOBALS['__output'])) && (getPhpCaching() != 'on')) {
131                                         outputRawCode($GLOBALS['__output']);
132                                         $GLOBALS['__output'] = '';
133                                 } // END - if
134
135                                 // The same as above... ^
136                                 outputRawCode($htmlCode);
137                                 if ($newLine === true) {
138                                         outputRawCode(chr(10));
139                                 } // END - if
140                                 break;
141
142                         default:
143                                 // Huh, something goes wrong or maybe you have edited config.php ???
144                                 reportBug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
145                                 break;
146                 } // END - switch
147         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['http_header'])) || (count($GLOBALS['http_header']) == 0)) && (!isRawOutputMode())) {
148                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getPhpCaching()=' . getPhpCaching() . ',isset(http_header)=' . intval(isset($GLOBALS['http_header'])) . ',getScriptOutputMode()=' . getScriptOutputMode() . '');
149                 // Output cached HTML code
150                 $GLOBALS['__output'] = ob_get_contents();
151
152                 // Clear output buffer for later output if output is found
153                 if (!empty($GLOBALS['__output'])) {
154                         clearOutputBuffer();
155                 } // END - if
156
157                 // Send all HTTP headers
158                 sendHttpHeaders();
159
160                 // Compile and run finished rendered HTML code
161                 compileFinalOutput();
162
163                 // Output code here, DO NOT REMOVE! ;-)
164                 outputRawCode($GLOBALS['__output']);
165         } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['__output'])) && (!isRawOutputMode())) {
166                 // Send all HTTP headers
167                 sendHttpHeaders();
168
169                 // Compile and run finished rendered HTML code
170                 compileFinalOutput();
171
172                 // Output code here, DO NOT REMOVE! ;-)
173                 outputRawCode($GLOBALS['__output']);
174         } else {
175                 // And flush all headers
176                 flushHttpHeaders();
177         }
178 }
179
180 // Compiles the final output
181 function compileFinalOutput () {
182         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ',getScriptOutputMode()=' . getScriptOutputMode() . ' - ENTERED!');
183         // Add page header and footer
184         addPageHeaderFooter();
185         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ' - After addPageHeaderFooter() call.');
186
187         // Do the final compilation
188         $GLOBALS['__output'] = compileUriCode(doFinalCompilation($GLOBALS['__output']));
189
190         // Extension 'rewrite' installed?
191         if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
192                 $GLOBALS['__output'] = rewriteLinksInCode($GLOBALS['__output']);
193         } // END - if
194
195         // Compress it?
196         /**
197          * @TODO On some pages this is buggy
198         if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
199                 // Compress it for HTTP gzip
200                 $GLOBALS['__output'] = gzencode($GLOBALS['__output'], 9);
201
202                 // Add header
203                 addHttpHeader('Content-Encoding: gzip');
204         } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
205                 // Compress it for HTTP deflate
206                 $GLOBALS['__output'] = gzcompress($GLOBALS['__output'], 9);
207
208                 // Add header
209                 addHttpHeader('Content-Encoding: deflate');
210         }
211         */
212
213         // Add final length
214         addHttpHeader('Content-Length: ' . strlen($GLOBALS['__output']));
215
216         // Flush all headers
217         flushHttpHeaders();
218 }
219
220 // Main compilation loop
221 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
222         // Insert comments? (Only valid with HTML templates, of course)
223         enableTemplateHtml($insertComments);
224
225         // Init counter
226         $count = 0;
227
228         // Compile all out
229         while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== false)) && ($count < 7)) {
230                 // Init common variables
231                 $content = array();
232                 $newContent = '';
233
234                 // Compile it
235                 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
236                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
237                 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
238                 eval($eval);
239                 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
240                 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
241
242                 // Was that eval okay?
243                 if (empty($newContent)) {
244                         // Something went wrong!
245                         reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
246                 } // END - if
247
248                 // Use it again
249                 $code = $newContent;
250
251                 // Compile the final code if insertComments is true
252                 if ($insertComments == true) {
253                         // ... because SQL queries shall keep OPEN_CONFIG and such in
254                         $code = compileRawCode($code);
255                 } // END - if
256
257                 // Count round
258                 $count++;
259         } // END - while
260
261         // Add debugging data in HTML code, if mode is enabled
262         if ((isDebugModeEnabled()) && ($insertComments === true) && ((isHtmlOutputMode()) || (isCssOutputMode()))) {
263                 // Add loop count
264                 $code .= '<!-- Total compilation loop=' . $count . ' //-->';
265         } // END - if
266
267         // Return the compiled code
268         return $code;
269 }
270
271 // Output the raw HTML code
272 function outputRawCode ($htmlCode) {
273         // Output stripped HTML code to avoid broken JavaScript code, etc.
274         print(str_replace('{BACK}', chr(92), $htmlCode));
275
276         // Flush the output if only getPhpCaching() is not 'on'
277         if (getPhpCaching() != 'on') {
278                 // Flush it
279                 flush();
280         } // END - if
281 }
282
283 // Load a template file and return it's content (only it's name; do not use ' or ")
284 function loadTemplate ($template, $return = false, $content = array(), $compileCode = true) {
285         // @TODO Remove these sanity checks if all is fine
286         if (!is_bool($return)) {
287                 // $return has to be boolean
288                 reportBug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
289         } elseif (!is_string($template)) {
290                 // $template has to be string
291                 reportBug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
292         }
293
294         // Init returned content
295         $ret = '';
296
297         // Set current template
298         $GLOBALS['current_template'] = $template;
299
300         // Do we have cache?
301         if ((!isDebuggingTemplateCache()) && (isTemplateCached($template))) {
302                 // Evaluate the cache
303                 eval(readTemplateCache($template));
304         } elseif (!isset($GLOBALS['template_eval'][$template])) {
305                 // Make all template names lowercase
306                 $template = strtolower($template);
307
308                 // Base directory
309                 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
310                 $extraPath = detectExtraTemplatePath($template);
311
312                 // Generate FQFN
313                 $FQFN = $basePath . $extraPath . $template . '.tpl';
314                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Template ' . $template . ' is solved to FQFN=' . $FQFN);
315
316                 // Does the special template exists?
317                 if (!isFileReadable($FQFN)) {
318                         // Reset to default template
319                         $FQFN = $basePath . $template . '.tpl';
320                 } // END - if
321
322                 // Now does the final template exists?
323                 if (isFileReadable($FQFN)) {
324                         // Count the template load
325                         incrementConfigEntry('num_templates');
326
327                         // The local file does exists so we load it. :)
328                         $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
329
330                         // Do we have to compile the code?
331                         if ((isInString('$', $GLOBALS['tpl_content'][$template])) || (isInString('{--', $GLOBALS['tpl_content'][$template])) || (isInString('{?', $GLOBALS['tpl_content'][$template])) || (isInString('{%', $GLOBALS['tpl_content'][$template]))) {
332                                 // Normal HTML output?
333                                 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
334                                         // Add surrounding HTML comments to help finding bugs faster
335                                         $code = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
336
337                                         // Prepare eval() command
338                                         $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($code), false, true, true, $compileCode) . '";';
339                                 } elseif (substr($template, 0, 3) == 'js_') {
340                                         // JavaScripts don't like entities, dollar signs and timings
341                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
342                                 } else {
343                                         // Prepare eval() command, other output doesn't like entities, maybe
344                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
345                                 }
346                         } elseif (isHtmlOutputMode()) {
347                                 // Add surrounding HTML comments to help finding bugs faster
348                                 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
349                                 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret), false, true, true, $compileCode) . '";';
350                         } else {
351                                 // JavaScript again
352                                 $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template]), false, true, true, $compileCode) . '");';
353                         } // END - if
354                 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
355                         // Only admins shall see this warning or when installation mode is active
356                         $ret = '<div class="para">
357         {--TEMPLATE_404--}
358 </div>
359 <div class="para">
360         (' . $template . ')
361 </div>
362 <div class="para">
363         {--TEMPLATE_CONTENT--}:
364         <pre>' . print_r($content, true) . '</pre>
365 </div>';
366                 } else {
367                         // No file!
368                         $GLOBALS['template_eval'][$template] = '404';
369                 }
370         }
371
372         // Code set?
373         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
374                 // Eval the code
375                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
376                 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval'][$template]).'</pre>');
377                 eval($GLOBALS['template_eval'][$template]);
378                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
379         } // END - if
380
381         // Do we have some content to output or return?
382         if (!empty($ret)) {
383                 // Not empty so let's put it out! ;)
384                 if ($return === true) {
385                         // Return the HTML code
386                         return $ret;
387                 } else {
388                         // Output directly
389                         outputHtml($ret);
390                 }
391         } elseif (isDebugModeEnabled()) {
392                 // Warning, empty output!
393                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
394         }
395 }
396
397 // Detects the extra template path from given template name
398 function detectExtraTemplatePath ($template) {
399         // Default is empty
400         $extraPath = '';
401
402         // Do we have cache?
403         if (!isset($GLOBALS['extra_path'][$template])) {
404                 // Check for admin/guest/member/etc. templates
405                 if (substr($template, 0, 6) == 'admin_') {
406                         // Admin template found
407                         $extraPath = 'admin/';
408                 } elseif (substr($template, 0, 6) == 'guest_') {
409                         // Guest template found
410                         $extraPath = 'guest/';
411                 } elseif (substr($template, 0, 7) == 'member_') {
412                         // Member template found
413                         $extraPath = 'member/';
414                 } elseif (substr($template, 0, 7) == 'select_') {
415                         // Selection template found
416                         $extraPath = 'select/';
417                 } elseif (substr($template, 0, 8) == 'install_') {
418                         // Installation template found
419                         $extraPath = 'install/';
420                 } elseif (substr($template, 0, 4) == 'ext_') {
421                         // Extension template found
422                         $extraPath = 'ext/';
423                 } elseif (substr($template, 0, 3) == 'la_') {
424                         // 'Logical-area' template found
425                         $extraPath = 'la/';
426                 } elseif (substr($template, 0, 3) == 'js_') {
427                         // JavaScript template found
428                         $extraPath = 'js/';
429                 } elseif (substr($template, 0, 5) == 'menu_') {
430                         // Menu template found
431                         $extraPath = 'menu/';
432                 } else {
433                         // Test for extension
434                         $test = substr($template, 0, strpos($template, '_'));
435
436                         // Probe for valid extension name
437                         if (isExtensionNameValid($test)) {
438                                 // Set extra path to extension's name
439                                 $extraPath = $test . '/';
440                         } // END - if
441                 }
442
443                 // Store it in cache
444                 $GLOBALS['extra_path'][$template] = $extraPath;
445         } // END - if
446
447         // Return result
448         return $GLOBALS['extra_path'][$template];
449 }
450
451 // Loads an email template and compiles it
452 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = true) {
453         // Make sure all template names are lowercase!
454         $template = strtolower($template);
455
456         // Set current template
457         $GLOBALS['current_template'] = $template;
458
459         // Is content an array?
460         if (is_array($content)) {
461                 // Add expiration to array
462                 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
463                         // Will never expire!
464                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
465                 } elseif (isConfigEntrySet('auto_purge')) {
466                         // Create nice date string
467                         $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
468                 } else {
469                         // Missing entry
470                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
471                 }
472         } // END - if
473
474         // Base directory
475         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
476
477         // Detect extra path
478         $extraPath = detectExtraTemplatePath($template);
479
480         // Generate full FQFN
481         $FQFN = $basePath . $extraPath . $template . '.tpl';
482
483         // Does the special template exists?
484         if (!isFileReadable($FQFN)) {
485                 // Reset to default template
486                 $FQFN = $basePath . $template . '.tpl';
487         } // END - if
488
489         // Now does the final template exists?
490         $newContent = '';
491         if (isFileReadable($FQFN)) {
492                 // The local file does exists so we load it. :)
493                 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
494
495                 // Run code
496                 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
497                 eval($GLOBALS['tpl_content'][$template]);
498         } elseif (!empty($template)) {
499                 // Template file not found
500                 $newContent = '<div class="para">
501         {--TEMPLATE_404--}: ' . $template . '
502 </div>
503 <div class="para">
504         {--TEMPLATE_CONTENT--}:
505         <pre>' . print_r($content, true) . '</pre>
506 </div>';
507
508                 // Debug mode not active? Then remove the HTML tags
509                 if (!isDebugModeEnabled()) {
510                         // Remove HTML tags
511                         $newContent = secureString($newContent);
512                 } // END - if
513         } else {
514                 // No template name supplied!
515                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
516         }
517
518         // Is there some content?
519         if (empty($newContent)) {
520                 // Compiling failed
521                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
522
523                 // Add last error if the required function exists
524                 if (function_exists('error_get_last')) {
525                         // Add last error and some lines for better overview
526                         $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
527                 } // END - if
528         } // END - if
529
530         // Remove content and data
531         unset($content);
532
533         // Return content
534         return $newContent;
535 }
536
537 // "Getter" for menu CSS classes, mainly used in templates
538 function getMenuCssClasses ($data) {
539         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
540
541         // Do we have cache?
542         if (!isset($GLOBALS[__FUNCTION__][$data])) {
543                 // $data needs to be converted into an array
544                 $content = explode('|', $data);
545
546                 // Non-existent index 2 will happen in menu blocks
547                 if (!isset($content[2])) {
548                         $content[2] = '';
549                 } // END - if
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                 // Set it in cache
559                 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
560         } // END - if
561
562         // Return cache
563         return $GLOBALS[__FUNCTION__][$data];
564 }
565
566 // Generate XHTML code for the CAPTCHA
567 function generateCaptchaCode ($code, $type, $urlId, $userid) {
568         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $urlId . '&amp;do=img&amp;code=' . $code . '%}" />';
569 }
570
571 // Compiles the given HTML/mail code
572 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
573         // Is the code a string or should we not compile?
574         if ((!is_string($code)) || ($compileCode === false)) {
575                 // Silently return it
576                 return $code;
577         } // END - if
578
579         // Start couting
580         $startCompile = microtime(true);
581
582         // Comile the code
583         $code = compileRawCode($code, $simple, $constants, $full);
584
585         // Get timing
586         $compilationTime = $startCompile - microtime(true);
587
588         // Add timing if enabled
589         if (isTemplateHtml()) {
590                 // Add timing, this should be disabled in
591                 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
592         } // END - if
593
594         // Return compiled code
595         return $code;
596 }
597
598 // Compiles the code
599 // @TODO $simple/$constants are deprecated
600 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
601         // Is the code a string or shall we not compile?
602         if ((!is_string($code)) || ($compileCode === false)) {
603                 // Silently return it
604                 return $code;
605         } // END - if
606
607         // Init replacement-array with smaller set of security characters
608         $secChars = $GLOBALS['url_chars'];
609
610         // Select full set of chars to replace when we e.g. want to compile URLs
611         if ($full === true) {
612                 $secChars = $GLOBALS['security_chars'];
613         } // END - if
614
615         // Compile more through a filter
616         $code = runFilterChain('compile_code', $code);
617
618         // First compile these chars
619         array_unshift($secChars['to']  , '{--'       , '--}');
620         array_unshift($secChars['from'], '{%message,', '%}' );
621
622         // Compile QUOT and other non-HTML codes
623         $code = str_replace($secChars['to'], $secChars['from'], $code);
624
625         // Find $content[bla][blub] entries
626         preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
627         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
628
629         // Are some matches found?
630         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
631                 // Replace all matches
632                 $matchesFound = array();
633                 foreach ($matches[0] as $key => $match) {
634                         // Fuzzy look has failed by default
635                         $fuzzyFound = false;
636
637                         // Fuzzy look on match if already found
638                         foreach ($matchesFound as $found => $set) {
639                                 // Get test part
640                                 $test = substr($found, 0, strlen($match));
641
642                                 // Does this entry exist?
643                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
644                                 if ($test == $match) {
645                                         // Match found
646                                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
647                                         $fuzzyFound = true;
648                                         break;
649                                 } // END - if
650                         } // END - foreach
651
652                         // Skip this entry?
653                         if ($fuzzyFound === true) {
654                                 continue;
655                         } // END - if
656
657                         // Take all string elements
658                         if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
659                                 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
660                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
661                                 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
662                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
663                                 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
664                                 $matchesFound[$match] = true;
665                         } elseif (!isset($matchesFound[$match])) {
666                                 // Not yet replaced!
667                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
668                                 $code = str_replace($match, '".' . $match . '."', $code);
669                                 $matchesFound[$match] = 1;
670                         } else {
671                                 // Everthing else should be a least logged
672                                 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
673                         }
674                 } // END - foreach
675         } // END - if
676
677         /*
678          * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
679          * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
680          * therefore the variable's value won't be inserted. This is why
681          * {COMPILE_DOLLAR} is being used in above loop and at the end of this
682          * function being replace with the original dollar sign again.
683          */
684         preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
685
686         // Are some matches found?
687         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
688                 // Scan all matches for not $content
689                 foreach ($matches[0] as $match) {
690                         // Trim match
691                         $match = trim($match);
692
693                         // Debug message
694                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
695
696                         // Is the first part not $content/$userid and not empty?
697                         // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
698                         if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
699                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
700                                 // Then replace $ with {DOLLAR}
701                                 $matchSecured = str_replace('$', '{DOLLAR}', $match);
702
703                                 // And in $code as well
704                                 $code = str_replace($match, $matchSecured, $code);
705                         } // END - if
706                 } // END - if
707         } // END - if
708
709         // Replace {COMPILE_DOLLAR} back to dollar sign
710         $code = str_replace('{COMPILE_DOLLAR}', '$', $code);
711
712         // Finally return it
713         return $code;
714 }
715
716 //
717 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
718         $OUT = '';
719
720         if ($type == 'yn') {
721                 // This is a yes/no selection only!
722                 if ($id > 0) $prefix .= '[' . $id . ']';
723                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
724         } else {
725                 // Begin with regular selection box here
726                 if (!empty($prefix)) $prefix .= '_';
727                 $type2 = $type;
728                 if ($id > 0) $type2 .= '[' . $id . ']';
729                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
730         }
731
732         switch ($type) {
733                 case 'day': // Day
734                         for ($idx = 1; $idx < 32; $idx++) {
735                                 $OUT .= '<option value="' . $idx . '"';
736                                 if ($default == $idx) $OUT .= ' selected="selected"';
737                                 $OUT .= '>' . $idx . '</option>';
738                         } // END - for
739                         break;
740
741                 case 'month': // Month
742                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
743                                 $OUT .= '<option value="' . $idx . '"';
744                                 if ($default == $idx) $OUT .= ' selected="selected"';
745                                 $OUT .= '>' . $descr . '</option>';
746                         } // END - for
747                         break;
748
749                 case 'year': // Year
750                         // Get current year
751                         $year = getYear();
752
753                         // Use configured min age or fixed?
754                         if (isExtensionInstalledAndNewer('other', '0.2.1')) {
755                                 // Configured
756                                 $startYear = $year - getConfig('min_age');
757                         } else {
758                                 // Fixed 16 years
759                                 $startYear = $year - 16;
760                         }
761
762                         // Calculate earliest year (100 years old people can still enter Internet???)
763                         $minYear = $year - 100;
764
765                         // Check if the default value is larger than minimum and bigger than actual year
766                         if (($default > $minYear) && ($default >= $year)) {
767                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
768                                         $OUT .= '<option value="' . $idx . '"';
769                                         if ($default == $idx) $OUT .= ' selected="selected"';
770                                         $OUT .= '>' . $idx . '</option>';
771                                 } // END - for
772                         } elseif ($default == -1) {
773                                 // Current year minus 1
774                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
775                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
776                                 } // END - for
777                         } else {
778                                 // Get current year and subtract the configured minimum age
779                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
780                                 // Calculate earliest year depending on extension version
781                                 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
782                                         // Use configured minimum age
783                                         $year = getYear() - getConfig('min_age');
784                                 } else {
785                                         // Use fixed 16 years age
786                                         $year = getYear() - 16;
787                                 }
788
789                                 // Construct year selection list
790                                 for ($idx = $minYear; $idx <= $year; $idx++) {
791                                         $OUT .= '<option value="' . $idx . '"';
792                                         if ($default == $idx) $OUT .= ' selected="selected"';
793                                         $OUT .= '>' . $idx . '</option>';
794                                 } // END - for
795                         }
796                         break;
797
798                 case 'sec':
799                 case 'min':
800                         for ($idx = 0; $idx < 60; $idx+=5) {
801                                 if (strlen($idx) == 1) $idx = 0 . $idx;
802                                 $OUT .= '<option value="' . $idx . '"';
803                                 if ($default == $idx) $OUT .= ' selected="selected"';
804                                 $OUT .= '>' . $idx . '</option>';
805                         } // END - for
806                         break;
807
808                 case 'hour':
809                         for ($idx = 0; $idx < 24; $idx++) {
810                                 if (strlen($idx) == 1) $idx = 0 . $idx;
811                                 $OUT .= '<option value="' . $idx . '"';
812                                 if ($default == $idx) $OUT .= ' selected="selected"';
813                                 $OUT .= '>' . $idx . '</option>';
814                         } // END - for
815                         break;
816
817                 case 'yn':
818                         $OUT .= '<option value="Y"';
819                         if ($default == 'Y') $OUT .= ' selected="selected"';
820                         $OUT .= '>{--YES--}</option><option value="N"';
821                         if ($default != 'Y') $OUT .= ' selected="selected"';
822                         $OUT .= '>{--NO--}</option>';
823                         break;
824         }
825         $OUT .= '</select>';
826         return $OUT;
827 }
828
829 // Insert the code in $img_code into jpeg or PNG image
830 function generateImageOrCode ($img_code, $headerSent = true) {
831         // Is the code size oversized or shouldn't we display it?
832         if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
833                 // Stop execution of function here because of over-sized code length
834                 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
835         } elseif ($headerSent === false) {
836                 // Return an HTML code here
837                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
838         }
839
840         // Load image
841         $img = sprintf("%s/theme/%s/images/code_bg.%s",
842                 getPath(),
843                 getCurrentTheme(),
844                 getImgType()
845         );
846
847         // Is it readable?
848         if (isFileReadable($img)) {
849                 // Switch image type
850                 switch (getImgType()) {
851                         case 'jpg': // Okay, load image and hide all errors
852                                 $image = imagecreatefromjpeg($img);
853                                 break;
854
855                         case 'png': // Okay, load image and hide all errors
856                                 $image = imagecreatefrompng($img);
857                                 break;
858                 } // END - switch
859         } else {
860                 // Silently log the error
861                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
862                 return;
863         }
864
865         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
866         $text_color = imagecolorallocate($image, 0, 0, 0);
867
868         // Insert code into image
869         imagestring($image, 5, 14, 2, $img_code, $text_color);
870
871         // Return to browser
872         setContentType('image/' . getImgType());
873
874         // Output image with matching image factory
875         switch (getImgType()) {
876                 case 'jpg': imagejpeg($image); break;
877                 case 'png': imagepng($image);  break;
878         } // END - switch
879
880         // Remove image from memory
881         imagedestroy($image);
882 }
883
884 // Create selection box or array of splitted timestamp
885 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = false) {
886         // Do not continue if ONE_DAY is absend
887         if (!isConfigEntrySet('ONE_DAY')) {
888                 // Abort here
889                 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
890         } // END - if
891
892         // Calculate 2-seconds timestamp
893         $stamp = round($timestamp);
894         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
895
896         // Do we have a leap year?
897         $SWITCH = '0';
898         $TEST = getYear() / 4;
899         $M1 = getMonth();
900         $M2 = getMonth(time() + $timestamp);
901
902         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
903         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  {
904                 $SWITCH = getOneDay();
905         } // END - switch
906
907         // First of all years...
908         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
909         //* DEBUG: */ debugOutput('Y=' . $Y);
910         // Next months...
911         $M = abs(floor($timestamp / 2628000 - $Y * 12));
912         //* DEBUG: */ debugOutput('M=' . $M);
913         // Next weeks
914         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
915         //* DEBUG: */ debugOutput('W=' . $W);
916         // Next days...
917         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
918         //* DEBUG: */ debugOutput('D=' . $D);
919         // Next hours...
920         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
921         //* DEBUG: */ debugOutput('h=' . $h);
922         // Next minutes..
923         $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getOneDay()) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
924         //* DEBUG: */ debugOutput('m=' . $m);
925         // And at last seconds...
926         $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getOneDay()) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
927         //* DEBUG: */ debugOutput('s=' . $s);
928
929         // Is seconds zero and time is < 60 seconds?
930         if (($s == '0') && ($timestamp < 60)) {
931                 // Fix seconds
932                 $s = round($timestamp);
933         } // END - if
934
935         //
936         // Now we convert them in seconds...
937         //
938         if ($asArray === true) {
939                 // Just put all data in an array for later use
940                 $OUT = array(
941                         'Y' => $Y,
942                         'M' => $M,
943                         'W' => $W,
944                         'D' => $D,
945                         'h' => $h,
946                         'm' => $m,
947                         's' => $s
948                 );
949         } else {
950                 // Generate table
951                 $OUT  = '<div align="' . $align . '">';
952                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
953                 $OUT .= '<tr>';
954
955                 if (isInString('Y', $display) || (empty($display))) {
956                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_YEAR--}</strong></td>';
957                 } // END - if
958
959                 if (isInString('M', $display) || (empty($display))) {
960                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MONTH--}</strong></td>';
961                 } // END - if
962
963                 if (isInString('W', $display) || (empty($display))) {
964                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_WEEK--}</strong></td>';
965                 } // END - if
966
967                 if (isInString('D', $display) || (empty($display))) {
968                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_DAY--}</strong></td>';
969                 } // END - if
970
971                 if (isInString('h', $display) || (empty($display))) {
972                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_HOUR--}</strong></td>';
973                 } // END - if
974
975                 if (isInString('m', $display) || (empty($display))) {
976                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MINUTE--}</strong></td>';
977                 } // END - if
978
979                 if (isInString('s', $display) || (empty($display))) {
980                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_SECOND--}</strong></td>';
981                 } // END - if
982
983                 $OUT .= '</tr>';
984                 $OUT .= '<tr>';
985
986                 if (isInString('Y', $display) || (empty($display))) {
987                         // Generate year selection
988                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
989                         for ($idx = 0; $idx <= 10; $idx++) {
990                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
991                                 if ($idx == $Y) $OUT .= ' selected="selected"';
992                                 $OUT .= '>' . $idx . '</option>';
993                         } // END - for
994                         $OUT .= '</select></td>';
995                 } else {
996                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
997                 }
998
999                 if (isInString('M', $display) || (empty($display))) {
1000                         // Generate month selection
1001                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1002                         for ($idx = 0; $idx <= 11; $idx++) {
1003                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1004                                 if ($idx == $M) $OUT .= ' selected="selected"';
1005                                 $OUT .= '>' . $idx . '</option>';
1006                         } // END - for
1007                         $OUT .= '</select></td>';
1008                 } else {
1009                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1010                 }
1011
1012                 if (isInString('W', $display) || (empty($display))) {
1013                         // Generate week selection
1014                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1015                         for ($idx = 0; $idx <= 4; $idx++) {
1016                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1017                                 if ($idx == $W) $OUT .= ' selected="selected"';
1018                                 $OUT .= '>' . $idx . '</option>';
1019                         } // END - for
1020                         $OUT .= '</select></td>';
1021                 } else {
1022                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1023                 }
1024
1025                 if (isInString('D', $display) || (empty($display))) {
1026                         // Generate day selection
1027                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1028                         for ($idx = 0; $idx <= 31; $idx++) {
1029                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1030                                 if ($idx == $D) $OUT .= ' selected="selected"';
1031                                 $OUT .= '>' . $idx . '</option>';
1032                         } // END - for
1033                         $OUT .= '</select></td>';
1034                 } else {
1035                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1036                 }
1037
1038                 if (isInString('h', $display) || (empty($display))) {
1039                         // Generate hour selection
1040                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1041                         for ($idx = 0; $idx <= 23; $idx++) {
1042                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1043                                 if ($idx == $h) $OUT .= ' selected="selected"';
1044                                 $OUT .= '>' . $idx . '</option>';
1045                         } // END - for
1046                         $OUT .= '</select></td>';
1047                 } else {
1048                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1049                 }
1050
1051                 if (isInString('m', $display) || (empty($display))) {
1052                         // Generate minute selection
1053                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1054                         for ($idx = 0; $idx <= 59; $idx++) {
1055                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1056                                 if ($idx == $m) $OUT .= ' selected="selected"';
1057                                 $OUT .= '>' . $idx . '</option>';
1058                         } // END - for
1059                         $OUT .= '</select></td>';
1060                 } else {
1061                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1062                 }
1063
1064                 if (isInString('s', $display) || (empty($display))) {
1065                         // Generate second selection
1066                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1067                         for ($idx = 0; $idx <= 59; $idx++) {
1068                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1069                                 if ($idx == $s) $OUT .= ' selected="selected"';
1070                                 $OUT .= '>' . $idx . '</option>';
1071                         } // END - for
1072                         $OUT .= '</select></td>';
1073                 } else {
1074                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1075                 }
1076                 $OUT .= '</tr>';
1077                 $OUT .= '</table>';
1078                 $OUT .= '</div>';
1079         }
1080
1081         // Return generated HTML code
1082         return $OUT;
1083 }
1084
1085 // Generate a list of administrative links to a given userid
1086 function generateMemberAdminActionLinks ($userid) {
1087         // Make sure userid is a number
1088         if ($userid != bigintval($userid)) {
1089                 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1090         } // END - if
1091
1092         // Define all main targets
1093         $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1094
1095         // Get user status
1096         $status = getFetchedUserData('userid', $userid, 'status');
1097
1098         // Begin of navigation links
1099         $OUT = '[';
1100
1101         foreach ($targetArray as $target) {
1102                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $target . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1103                 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1104                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1105                         // Locked accounts shall be unlocked
1106                         $OUT .= 'UNLOCK_USER';
1107                 } elseif ($target == 'del_user') {
1108                         // @TODO Deprecate this thing
1109                         $OUT .= 'DELETE_USER';
1110                 } else {
1111                         // All other status is fine
1112                         $OUT .= strtoupper($target);
1113                 }
1114                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1115                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1116                         // Locked accounts shall be unlocked
1117                         $OUT .= 'UNLOCK_USER';
1118                 } elseif ($target == 'del_user') {
1119                         // @TODO Deprecate this thing
1120                         $OUT .= 'DELETE_USER';
1121                 } else {
1122                         // All other status is fine
1123                         $OUT .= strtoupper($target);
1124                 }
1125                 $OUT .= '--}</a></span>|';
1126         } // END - foreach
1127
1128         // Add special link, in case of the account is unconfirmed
1129         if ($status == 'UNCONFIRMED') {
1130                 // Add it
1131                 $OUT .= '<span class="admin_user_link"><a target="_blank" title="{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT_TITLE--}" href="{%url=confirm.php?hash=' . getFetchedUserData('userid', $userid, 'user_hash') . '%}">{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT--}</a></span>|';
1132         } // END - if
1133
1134         // Finish navigation link
1135         $OUT = substr($OUT, 0, -1) . ']';
1136
1137         // Return string
1138         return $OUT;
1139 }
1140
1141 // Generate an email link
1142 function generateEmailLink ($email, $table = 'admins') {
1143         // Default email link (INSECURE! Spammer can read this by harvester programs)
1144         $EMAIL = 'mailto:' . $email;
1145
1146         // Check for several extensions
1147         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1148                 // Create email link for contacting admin in guest area
1149                 $EMAIL = generateAdminEmailLink($email);
1150         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1151                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1152                 $EMAIL = generateUserEmailLink($email);
1153         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1154                 // Create email link to contact sponsor within admin area (or like the link above?)
1155                 $EMAIL = generateSponsorEmailLink($email);
1156         }
1157
1158         // Return email link
1159         return $EMAIL;
1160 }
1161
1162 /**
1163  * Outputs an error message in a "fashioned way" to the user, by putting it into
1164  * a nice looking web page, if one of HTML or CSS output mode is active.
1165  *
1166  * Please use reportBug() instead of this function. reportBug() has more helpful
1167  * functionality like logging and admin notification (which you can configure
1168  * through your admin area).
1169  *
1170  * @param       $F                      Function or file basename where the error came from
1171  * @param       $L                      Line number where the error came from
1172  * @param       $message        Message which shall be output to web
1173  * @return      void
1174  */
1175 function app_exit ($F, $L, $message) {
1176         // Check if Script is already dieing and not let it kill itself another 1000 times
1177         if (isset($GLOBALS['app_died'])) {
1178                 // Script tried to kill itself twice
1179                 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1180         } // END - if
1181
1182         // Make sure, that the script realy realy diese here and now
1183         $GLOBALS['app_died'] = true;
1184
1185         // Set content type as text/html
1186         setContentType('text/html');
1187
1188         // Load header
1189         loadIncludeOnce('inc/header.php');
1190
1191         // Rewrite message for output
1192         $message = sprintf(
1193                 getMessage('MAILER_HAS_DIED'),
1194                 basename($F),
1195                 $L,
1196                 $message
1197         );
1198
1199         // Load the message template
1200         loadTemplate('app_exit_message', false, $message);
1201
1202         // Load footer
1203         loadIncludeOnce('inc/footer.php');
1204 }
1205
1206 // Display parsing time and number of SQL queries in footer
1207 function displayParsingTime () {
1208         // Is the timer started?
1209         if (!isset($GLOBALS['__start_time'])) {
1210                 // Abort here
1211                 return false;
1212         } // END - if
1213
1214         // Get end time
1215         $endTime = microtime(true);
1216
1217         // "Explode" both times
1218         $start = explode(' ', $GLOBALS['__start_time']);
1219         $end = explode(' ', $endTime);
1220         $runTime = $end[0] - $start[0];
1221         if ($runTime < 0) {
1222                 $runTime = '0';
1223         } // END - if
1224
1225         // Prepare output
1226         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1227         $content = array(
1228                 'run_time' => $runTime,
1229                 'sql_time' => (getConfig('sql_time') * 1000),
1230         );
1231
1232         // Load the template
1233         $GLOBALS['__page_footer'] .= loadTemplate('show_timings', true, $content);
1234 }
1235
1236 /**
1237  * Outputs an error message and backtrace to the user, by default a mail with
1238  * all relevant data is being mailed to the configured administrators.
1239  *
1240  * This function shall be used "publicly" because of logging, admin notification
1241  * and double-call prevention (see first if() block) instead of app_exit().
1242  * app_exit() is more a "private" function and will only output a bug message to
1243  * the user, no email and no logging.
1244  *
1245  * @param       $F                      Function or file basename where the error came from
1246  * @param       $L                      Line number where the error came from
1247  * @param       $sendEmail      Wether to send an email to all configured administrators
1248  * @return      void
1249  */
1250 function reportBug ($F, $L, $message = '', $sendEmail = true) {
1251         // Is this already called?
1252         if (isset($GLOBALS[__FUNCTION__])) {
1253                 // Other backtrace
1254                 print '[' . $F . ':' . $L . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
1255                 debug_print_backtrace();
1256                 die('</pre>');
1257         } // END - if
1258
1259         // Set HTTP status to 500 (e.g. for AJAX requests)
1260         setHttpStatus('500 Internal Server Error');
1261
1262         // Mark this function as called
1263         $GLOBALS[__FUNCTION__] = true;
1264
1265         // Init message
1266         $debug = '';
1267
1268         // Is the optional message set?
1269         if (!empty($message)) {
1270                 // Use and log it
1271                 $debug = sprintf("Note: %s<br />\n",
1272                         $message
1273                 );
1274
1275                 // @TODO Add a little more infos here
1276                 logDebugMessage($F, $L, strip_tags($message));
1277         } // END - if
1278
1279         // Add output
1280         $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 this whole message + logfile from <strong>' . str_replace(getPath(), '', getCachePath()) . 'debug.log</strong> in your report (you can now attach files).<br />Backtrace:<pre>';
1281         $debug .= debug_get_printable_backtrace();
1282         $debug .= '</pre>';
1283         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1284         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1285
1286         // Send an email? (e.g. not wanted for evaluation errors)
1287         if (($sendEmail === true) && (!isInstallationPhase())) {
1288                 // Prepare content
1289                 $content = array(
1290                         'message'   => trim($message),
1291                         'backtrace' => trim(debug_get_mailable_backtrace())
1292                 );
1293
1294                 // Send email to webmaster
1295                 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1296         } // END - if
1297
1298         // Do we have HTML/CSS/AJAX mode?
1299         if ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode())) {
1300                 // And abort here
1301                 app_exit($F, $L, $debug);
1302         } else {
1303                 // Raw/image output mode and all other modes doesn't work well with text ...
1304                 die();
1305         }
1306 }
1307
1308 // Compile characters which are allowed in URLs
1309 function compileUriCode ($code, $simple = true) {
1310         // Trim code
1311         $test = trim($code);
1312
1313         // Is it empty?
1314         if (empty($test)) {
1315                 // Then abort here and return the original code
1316                 return $code;
1317         } // END - if
1318
1319         // Compile these by default
1320         $charsCompile = array(
1321                 'from' => array(
1322                         '{DOT}',
1323                         '{SLASH}',
1324                         '{QUOT}',
1325                         '{DOLLAR}',
1326                         '{OPEN_ANCHOR}',
1327                         '{CLOSE_ANCHOR}',
1328                         '{OPEN_SQR}',
1329                         '{CLOSE_SQR}',
1330                         '{PER}'
1331                 ),
1332                 'to' => array(
1333                         '.',
1334                         '/',
1335                         chr(39),
1336                         '$',
1337                         '(',
1338                         ')',
1339                         '[',
1340                         ']',
1341                         '%'
1342                 )
1343         );
1344
1345         // Compile constants
1346         if ($simple === false) {
1347                 // Add more 'from'
1348                 array_push($charsCompile['from'], '{--', '--}');
1349
1350                 // Add more 'to'
1351                 array_push($charsCompile['to'], '".', '."');
1352         } // END - if
1353
1354         // Compile QUOT and other non-HTML codes
1355         $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1356
1357         // Return compiled code
1358         return $code;
1359 }
1360
1361 // Handle message codes from URL
1362 function handleCodeMessage () {
1363         // Is 'code' set?
1364         if (isGetRequestElementSet('code')) {
1365                 // Default extension is 'unknown'
1366                 $ext = 'unknown';
1367
1368                 // Is extension given?
1369                 if (isGetRequestElementSet('ext')) {
1370                         $ext = getRequestElement('ext');
1371                 } // END - if
1372
1373                 // Convert the 'code' parameter from URL to a human-readable message
1374                 $message = getMessageFromErrorCode(getRequestElement('code'));
1375
1376                 // Load message template
1377                 loadTemplate('message', false, $message);
1378         } // END - if
1379 }
1380
1381 // Generates a 'extension foo out-dated' message
1382 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1383         // Is the extension empty?
1384         if (empty($ext_name)) {
1385                 // This should not happen
1386                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1387         } // END - if
1388
1389         // Default message
1390         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1391
1392         // Is an admin logged in?
1393         if (isAdmin()) {
1394                 // Then output admin message
1395                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1396         } // END - if
1397
1398         // Return prepared message
1399         return $message;
1400 }
1401
1402 // Generates a 'extension foo inactive' message
1403 function generateExtensionInactiveMessage ($ext_name) {
1404         // Is the extension empty?
1405         if (empty($ext_name)) {
1406                 // This should not happen
1407                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1408         } // END - if
1409
1410         // Default message
1411         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1412
1413         // Is an admin logged in?
1414         if (isAdmin()) {
1415                 // Then output admin message
1416                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1417         } // END - if
1418
1419         // Return prepared message
1420         return $message;
1421 }
1422
1423 // Generates a 'extension foo not installed' message
1424 function generateExtensionNotInstalledMessage ($ext_name) {
1425         // Is the extension empty?
1426         if (empty($ext_name)) {
1427                 // This should not happen
1428                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1429         } // END - if
1430
1431         // Default message
1432         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1433
1434         // Is an admin logged in?
1435         if (isAdmin()) {
1436                 // Then output admin message
1437                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1438         } // END - if
1439
1440         // Return prepared message
1441         return $message;
1442 }
1443
1444 // Generates a message depending on if the extension is not installed or not
1445 // just activated
1446 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1447         // Init message
1448         $message = '';
1449
1450         // Is the extension not installed or just deactivated?
1451         switch (isExtensionInstalled($ext_name)) {
1452                 case true; // Deactivated!
1453                         $message = generateExtensionInactiveMessage($ext_name);
1454                         break;
1455
1456                 case false; // Not installed!
1457                         $message = generateExtensionNotInstalledMessage($ext_name);
1458                         break;
1459
1460                 default: // Should not happen!
1461                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1462                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1463                         break;
1464         } // END - switch
1465
1466         // Return the message
1467         return $message;
1468 }
1469
1470 // Print code with line numbers
1471 function linenumberCode ($code)    {
1472         // By default copy the code
1473         $codeE = $code;
1474
1475         if (!is_array($code)) {
1476                 // We need an array, so try it with the new-line character
1477                 $codeE = explode(chr(10), $code);
1478         } // END - if
1479
1480         $count_lines = count($codeE);
1481
1482         $r = 'Line | Code:<br />';
1483         foreach ($codeE as $line => $c) {
1484                 $r .= '<div class="line"><span class="linenum">';
1485                 if ($count_lines == 1) {
1486                         $r .= 1;
1487                 } else {
1488                         $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1489                 }
1490                 $r .= '</span>|';
1491
1492                 // Add code
1493                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1494         } // END - foreach
1495
1496         return '<div class="code">' . $r . '</div>';
1497 }
1498
1499 // Determines the right page title
1500 function determinePageTitle () {
1501         // Init page title
1502         $pageTitle = '';
1503
1504         // Config and database connection valid?
1505         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1506                 // Title decoration enabled?
1507                 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1508                         $pageTitle .= '{%config,trim=title_left%} ';
1509                 } // END - if
1510
1511                 // Do we have some extra title?
1512                 if (isExtraTitleSet()) {
1513                         // Then prepend it
1514                         $pageTitle .= '{%pipe,getExtraTitle%} by ';
1515                 } // END - if
1516
1517                 // Add main title
1518                 $pageTitle .= '{?MAIN_TITLE?}';
1519
1520                 // Add title of module? (middle decoration will also be added!)
1521                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1522                         $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1523                 } // END - if
1524
1525                 // Add title from what file
1526                 $menuMode = '';
1527                 if (getModule() == 'login') {
1528                         $menuMode = 'member';
1529                 } elseif (getModule() == 'index') {
1530                         $menuMode = 'guest';
1531                 } elseif (getModule() == 'admin') {
1532                         $menuMode = 'admin';
1533                 } elseif (getModule() == 'sponsor') {
1534                         $menuMode = 'sponsor';
1535                 }
1536
1537                 // Add middle part (always in admin area!)
1538                 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1539                         $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1540                 } // END - if
1541
1542                 // Add title decorations? (right)
1543                 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1544                         $pageTitle .= ' {%config,trim=title_right%}';
1545                 } // END - if
1546         } elseif ((isInstalled()) && (isAdminRegistered())) {
1547                 // Installed, admin registered but no ext-sql_patches
1548                 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1549         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1550                 // Installed but no admin registered
1551                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1552         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1553                 // Installation mode
1554                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1555         } else {
1556                 // Configuration not found
1557                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1558
1559                 // Do not add the fatal message in installation mode
1560                 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1561                         // Please report this
1562                         reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1563                 } // END - if
1564         }
1565
1566         // Return title
1567         return decodeEntities($pageTitle);
1568 }
1569
1570 // Checks whethere there is a cache file there. This function is cached.
1571 function isTemplateCached ($template) {
1572         // Do we have cached this result?
1573         if (!isset($GLOBALS['template_cache'][$template])) {
1574                 // Generate FQFN
1575                 $FQFN = generateCacheFqfn($template);
1576
1577                 // Is it there?
1578                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1579         } // END - if
1580
1581         // Return it
1582         return $GLOBALS['template_cache'][$template];
1583 }
1584
1585 // Flushes non-flushed template cache to disk
1586 function flushTemplateCache ($template, $eval) {
1587         // Is this cache flushed?
1588         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1589                 // Generate FQFN
1590                 $FQFN = generateCacheFqfn($template);
1591
1592                 // And flush it
1593                 writeToFile($FQFN, $eval, true);
1594         } // END - if
1595 }
1596
1597 // Reads a template cache
1598 function readTemplateCache ($template) {
1599         // Check it again
1600         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1601                 // This should not happen
1602                 reportBug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1603         } // END - if
1604
1605         // Is it cached?
1606         if (!isset($GLOBALS['template_eval'][$template])) {
1607                 // Generate FQFN
1608                 $FQFN = generateCacheFqfn($template);
1609
1610                 // And read from it
1611                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1612         } // END - if
1613
1614         // And return it
1615         return $GLOBALS['template_eval'][$template];
1616 }
1617
1618 // Escapes quotes (default is only double-quotes)
1619 function escapeQuotes ($str, $single = false) {
1620         // Should we escape all?
1621         if ($single === true) {
1622                 // Escape all (including null)
1623                 $str = addslashes($str);
1624         } else {
1625                 // Replace all chars at once
1626                 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1627         }
1628
1629         // Return the escaped string
1630         return $str;
1631 }
1632
1633 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1634 function escapeJavaScriptQuotes ($str) {
1635         // Replace all double-quotes and secure back-ticks
1636         $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1637
1638         // Return it
1639         return $str;
1640 }
1641
1642 // Send out mails depending on the 'mod/modes' combination
1643 // @TODO Lame description for this function
1644 function sendModeMails ($mod, $modes) {
1645         // Init user data
1646         $content = array ();
1647
1648         // Load hash
1649         if (fetchUserData(getMemberId())) {
1650                 // Extract salt from cookie
1651                 $salt = substr(getSession('u_hash'), 0, -40);
1652
1653                 // Now let's compare passwords
1654                 $hash = encodeHashForCookie(getUserData('password'));
1655
1656                 // Does the hash match or should we change it?
1657                 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
1658                         // Load the data
1659                         $content = getUserDataArray();
1660
1661                         // Clear/init the content variable
1662                         $content['message'] = '';
1663
1664                         // Which mail?
1665                         // @TODO Move this in a filter
1666                         switch ($mod) {
1667                                 case 'mydata':
1668                                         foreach ($modes as $mode) {
1669                                                 switch ($mode) {
1670                                                         case 'normal': break; // Do not add any special lines
1671                                                         case 'email': // Email was changed!
1672                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . chr(10);
1673                                                                 break;
1674
1675                                                         case 'password': // Password was changed
1676                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . chr(10);
1677                                                                 break;
1678
1679                                                         default:
1680                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1681                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1682                                                                 break;
1683                                                 } // END - switch
1684                                         } // END - foreach
1685
1686                                         if (isExtensionActive('country')) {
1687                                                 // Replace code with description
1688                                                 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1689                                         } // END - if
1690
1691                                         // Merge content with data from POST
1692                                         $content = merge_array($content, postRequestArray());
1693
1694                                         // Load template
1695                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1696
1697                                         if (isAdminNotificationEnabled()) {
1698                                                 // The admin needs to be notified about a profile change
1699                                                 $message_admin = 'admin_mydata_notify';
1700                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1701                                         } else {
1702                                                 // No mail to admin
1703                                                 $message_admin = '';
1704                                                 $sub_adm   = '';
1705                                         }
1706
1707                                         // Set subject lines
1708                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1709
1710                                         // Output success message
1711                                         $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1712                                         break;
1713
1714                                 default: // Unsupported module!
1715                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1716                                         $content['message'] = '<span class="bad">{--UNKNOWN_MODULE--}</span>';
1717                                         break;
1718                         } // END - switch
1719                 } else {
1720                         // Passwords mismatch
1721                         $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1722                 }
1723         } else {
1724                 // Could not load profile
1725                 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1726         }
1727
1728         // Send email to user if required
1729         if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1730                 // Send member mail
1731                 sendEmail($content['userid'], $sub_mem, $message);
1732         } // END - if
1733
1734         // Send only if no other error has occured
1735         if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1736                 // Send admin mail
1737                 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1738         } elseif (isAdminNotificationEnabled()) {
1739                 // Cannot send mails to admin!
1740                 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1741         } else {
1742                 // No mail to admin
1743                 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1744         }
1745
1746         // Load template
1747         displayMessage($content['message']);
1748 }
1749
1750 // Generates a 'selection box' from given array
1751 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = false, $useDefaultAsArray = false) {
1752         // Default is empty
1753         $addKey = '';
1754
1755         // Use default value as array key?
1756         if ($useDefaultAsArray === true) {
1757                 // Then set it
1758                 $addKey = '[' . convertNullToZero($default) . ']';
1759         } // END - if
1760
1761         // Start the output
1762         $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1763 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1764
1765         // Allow none?
1766         if ($allowNone === true) {
1767                 // Then add it
1768                 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1769         } // END - if
1770
1771         // Walk through all options
1772         foreach ($options as $option) {
1773                 // Default 'default' is not set
1774                 $option['default'] = '';
1775
1776                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1777                 // Is default value same as given value?
1778                 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1779                         // Then set default
1780                         $option['default'] = ' selected="selected"';
1781                 } // END - if
1782
1783                 // Is 'nameElement' set?
1784                 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1785                         // Then set this as extraName, but lower-case
1786                         $extraName = '_' . strtolower($option[$nameElement]);
1787                 } // END - if
1788
1789                 // Add the <option> entry from ...
1790                 if (empty($optionContent)) {
1791                         // Is a template name given?
1792                         if (empty($templateName)) {
1793                                 // ... $name template
1794                                 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1795                         } else {
1796                                 // ... $templateName template
1797                                 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', true, $option);
1798                         }
1799                 } else {
1800                         // ... direct HTML code
1801                         $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1802                 }
1803         } // END - foreach
1804
1805         // Finish selection box
1806         $OUT .= '</select>';
1807
1808         // Prepare output
1809         $content = array(
1810                 'selection_box' => $OUT,
1811         );
1812
1813         // Load template and return it
1814         if (empty($templateName)) {
1815                 // Use name from $name + $extraName
1816                 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1817         } else {
1818                 // Use name from $templateName + $extraName
1819                 return loadTemplate('select_' . $templateName . $extraName . '_box', true, $content);
1820         }
1821 }
1822
1823 // Prepares the header for HTML output
1824 function loadHtmlHeader () {
1825         /*
1826          * Run two filters:
1827          * 1.) pre_page_header (mainly loads the page_header template and includes
1828          *     meta description)
1829          */
1830         runFilterChain('pre_page_header');
1831
1832         /*
1833          * Here can be something be added, but normally one of the two filters
1834          * around this line should do the job for you.
1835          */
1836
1837         /*
1838          * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1839          *     to close the head-tag)
1840          * Include more header data here
1841          */
1842         runFilterChain('post_page_header');
1843 }
1844
1845 // Adds page header and footer to output array element
1846 function addPageHeaderFooter () {
1847         // Init output
1848         $OUT = '';
1849
1850         // Add them all together. This is maybe to simple
1851         foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1852                 // Add page part if set
1853                 if (isset($GLOBALS[$pagePart])) {
1854                         $OUT .= $GLOBALS[$pagePart];
1855                 } // END - if
1856         } // END - foreach
1857
1858         // Transfer $OUT to '__output'
1859         $GLOBALS['__output'] = $OUT;
1860 }
1861
1862 // Generates meta description for current module and 'what' value
1863 function generateMetaDescriptionCode () {
1864         // Only include from guest area and if sql_patches has correct version
1865         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1866                 // Output it directly
1867                 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1868         } // END - if
1869
1870         // Initialize referral system
1871         initReferralSystem();
1872 }
1873
1874 // Generates an FQFN for template cache from the given template name
1875 function generateCacheFqfn ($template, $mode = 'html') {
1876         // Is this cached?
1877         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1878                 // Generate the FQFN
1879                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1880                         "%s_compiled/%s/%s.tpl.cache",
1881                         getCachePath(),
1882                         $mode,
1883                         $template
1884                 );
1885         } // END - if
1886
1887         // Return it
1888         return $GLOBALS['template_cache_fqfn'][$template];
1889 }
1890
1891 // "Fixes" null or empty string to count of dashes
1892 function fixNullEmptyToDashes ($str, $num) {
1893         // Use str as default
1894         $return = $str;
1895
1896         // Is it empty?
1897         if ((is_null($str)) || (trim($str) == '')) {
1898                 // Set it
1899                 $return = str_repeat('-', $num);
1900         } // END - if
1901
1902         // Return final string
1903         return $return;
1904 }
1905
1906 // Translates the "pool type" into human-readable
1907 function translatePoolType ($type) {
1908         // Return "translation"
1909         return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1910 }
1911
1912 // "Translates" given time unit
1913 function translateTimeUnit ($unit) {
1914         // Default is unknown
1915         $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1916
1917         // "Detect" it
1918         if (!isset($GLOBALS['time_units'][$unit])) {
1919                 // Not found
1920                 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1921         } else {
1922                 // Translate it with generic function
1923                 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1924         }
1925
1926         // Return message
1927         return $message;
1928 }
1929
1930 // Displays given message in admin_settings_saved template
1931 function displayMessage ($message, $return = false) {
1932         // Load the template
1933         return loadTemplate('admin_settings_saved', $return, $message);
1934 }
1935
1936 // Generates a selection box for (maybe) given gender
1937 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
1938         // Start the HTML code
1939         $out  = '<select name="' . $fieldName . '" size="1" class="form_select">';
1940
1941         // Add options
1942         $out .= generateOptions(
1943                 '/ARRAY/',
1944                 array(
1945                         'M',
1946                         'F',
1947                         'C'
1948                 ), array(
1949                         '{--GENDER_M--}',
1950                         '{--GENDER_F--}',
1951                         '{--GENDER_C--}'
1952                 ),
1953                 $selectedGender
1954         );
1955
1956         // Finish HTML code
1957         $out .= '</select>';
1958
1959         // Return the code
1960         return $out;
1961 }
1962
1963 // Generates a selection box for given default value
1964 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
1965         // Init variables
1966         $messageIds = array();
1967
1968         // Generate message id array
1969         foreach ($unitArray as $unit) {
1970                 // "Translate" it
1971                 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
1972         } // END - foreach
1973
1974         // Start the HTML code
1975         $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
1976
1977         // Add options
1978         $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
1979
1980         // Finish HTML code
1981         $out .= '</select>';
1982
1983         // Return the code
1984         return $out;
1985 }
1986
1987 // Function to add style tag (whether display:none/block)
1988 function addStyleMenuContent ($menuMode, $mainAction, $action) {
1989         // Do we have foo_menu_javascript enabled?
1990         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
1991                 // Silently abort here, not enabled
1992                 return '';
1993         } // END - if
1994
1995         // Is action=mainAction?
1996         if ($action == $mainAction) {
1997                 // Add "menu open" style
1998                 return ' style="display:block"';
1999         } else {
2000                 return ' style="display:none"';
2001         }
2002 }
2003
2004 // Function to add onclick attribute
2005 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2006         // Do we have foo_menu_javascript enabled?
2007         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2008                 // Silently abort here, not enabled
2009                 return '';
2010         } // END - if
2011
2012         // Prepare output
2013         $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2014
2015         // Return output
2016         return $OUT;
2017 }
2018
2019 //-----------------------------------------------------------------------------
2020 //                     Template helper functions for EL code
2021 //-----------------------------------------------------------------------------
2022
2023 // Color-switch helper function
2024 function doTemplateColorSwitch ($templateName, $clear = false, $return = true) {
2025         // Is it there?
2026         if (!isset($GLOBALS['color_switch'][$templateName])) {
2027                 // Initialize it
2028                 initTemplateColorSwitch($templateName);
2029         } elseif ($clear === false) {
2030                 // Switch color if called from loadTemplate()
2031                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2032                 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2033         }
2034
2035         // Return CSS class name
2036         if ($return === true) {
2037                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2038                 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2039         } // END - if
2040 }
2041
2042 // Helper function for extension registration link
2043 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2044         // Default is all non-productive
2045         $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2046
2047         // Is the given extension non-productive?
2048         if (isExtensionDeprecated($ext_name)) {
2049                 // Is deprecated
2050                 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2051         } elseif (isExtensionProductive($ext_name)) {
2052                 // Productive code
2053                 $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>';
2054         }
2055
2056         // Return code
2057         return $OUT;
2058 }
2059
2060 // Helper function to create bonus mail admin links
2061 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2062         // Call the inner function
2063         return generateAdminMailLinks('bid', $bonusId);
2064 }
2065
2066 // Helper function to create member mail admin links
2067 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2068         // Call the inner function
2069         return generateAdminMailLinks('mid', $mailId);
2070 }
2071
2072 // Helper function to create a selection box for YES/NO configuration entries
2073 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2074         // Default is a "missing entry" warning
2075         $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2076
2077         // Generate the HTML code
2078         if (isConfigEntrySet($configEntry)) {
2079                 // Configuration entry is found
2080                 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2081 {%config,generateYesNoOptions=' . $configEntry . '%}
2082 </select>';
2083         } // END - if
2084
2085         // Return it
2086         return $OUT;
2087 }
2088
2089 // Helper function to create a selection box for YES/NO form fields
2090 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2091         // Generate the HTML code
2092         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2093 {%pipe,generateYesNoOptions%}
2094 </select>';
2095
2096         // Return it
2097         return $OUT;
2098 }
2099
2100 // Helper function to create a selection box for YES/NO form fields, by NO is default
2101 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2102         // Generate the HTML code
2103         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2104 {%pipe,generateYesNoOptions=N%}
2105 </select>';
2106
2107         // Return it
2108         return $OUT;
2109 }
2110
2111 // Helper function to add extra content for member area (module=login)
2112 function doTemplateMemberFooterExtras ($templateName, $clear) {
2113         // Is a member logged in?
2114         if (!isMember()) {
2115                 // This shall not happen
2116                 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2117         } // END - if
2118
2119         // Init filter data
2120         $filterData = array(
2121                 // Current user's id number
2122                 'userid'   => getMemberId(),
2123                 // Name of used template
2124                 'template' => $templateName,
2125                 // Target array for gathered data
2126                 '__data'   => array(),
2127                 // Where the HTML output will go
2128                 '__output' => '',
2129         );
2130
2131         // Run the filter chain
2132         $filterData = runFilterChain('member_footer_extras', $filterData);
2133
2134         // Return output
2135         return $filterData['__output'];
2136 }
2137
2138 /**
2139  * Helper function to determine whether current userid is set, if none is set,
2140  * return a zero, else an EL code is being returned as of this function is used
2141  * only in templates.
2142  *
2143  * @param       $templateName   Name of template (unused)
2144  * @param       $clear                  Wether to clear something (unused)
2145  * @return      $userId                 Wether zero or EL code snippet
2146  */
2147 function doTemplateUserId ($templateName, $clear) {
2148         // By default no userid is set
2149         $userId = '0';
2150
2151         // Is there a user id currently set?
2152         if (isCurrentUserIdSet()) {
2153                 // Then get the current user id
2154                 $userId = getCurrentUserId();
2155         } // END - if
2156
2157         // Return it
2158         return $userId;
2159 }
2160
2161 // Template helper function to generate "Terms&Conditions" link (EL code again)
2162 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2163         /*
2164          * Use default link by default ;-) This link, however, will become
2165          * deprecated once ext-terms is rolled out.
2166          */
2167         $linkCode = '{%url=modules.php?module=index&amp;what=agb%}';
2168
2169         // Is ext-terms installed?
2170         if (isExtensionInstalled('terms')) {
2171                 // Then use that link (only 'what' has changed)
2172                 $linkCode = '{%url=modules.php?module=index&amp;what=terms%}';
2173         } // END - if
2174
2175         // Return link (EL) code
2176         return $linkCode;
2177 }
2178
2179 // Template helper function to create selection box for "locked points mode"
2180 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = false, $default = NULL) {
2181         // Init array
2182         $lockedModes = array(
2183                 0 => array('mode' => 'LOCKED'),
2184                 1 => array('mode' => 'UNLOCKED'),
2185         );
2186
2187         // Handle it over to generateSelectionBoxFromArray()
2188         $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2189
2190         // Return prepared content
2191         return $content;
2192 }
2193
2194 // Template helper function to create selection box for payment method
2195 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = false, $default = NULL) {
2196         // Init array
2197         $paymentMethods = array(
2198                 0 => array('method' => 'DIRECT'),
2199                 1 => array('method' => 'REFERRAL'),
2200         );
2201
2202         // Handle it over to generateSelectionBoxFromArray()
2203         $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2204
2205         // Return prepared content
2206         return $content;
2207 }
2208
2209 // [EOF]
2210 ?>