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