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