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