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