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