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