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