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