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