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