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