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