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