Fixes for referal system, shell scripts overworked:
[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         global $DATA;
433
434         // Make sure all template names are lowercase!
435         $template = strtolower($template);
436
437         // Is content an array?
438         if (is_array($content)) {
439                 // Add expiration to array
440                 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
441                         // Will never expire!
442                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
443                 } elseif (isConfigEntrySet('auto_purge')) {
444                         // Create nice date string
445                         $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
446                 } else {
447                         // Missing entry
448                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
449                 }
450         } // END - if
451
452         // Load user's data
453         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UID=' . $userid . ',template=' . $template . ',content[]=' . gettype($content));
454         if ((isValidUserId($userid)) && (is_array($content))) {
455                 // If nickname extension is installed, fetch nickname as well
456                 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
457                         // Load by nickname
458                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - NICKNAME!');
459                         fetchUserData($userid, 'nickname');
460                 } elseif (isNicknameUsed($userid)) {
461                         // Non-number characters entered but no ext-nickname found
462                         debug_report_bug(__FUNCTION__, __LINE__, 'userid=' . $userid . ': is no id number and ext-nickname is gone.');
463                 } else {
464                         // Load by userid
465                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - USERID!');
466                         fetchUserData($userid);
467                 }
468
469                 // Merge data if valid
470                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - PRE!');
471                 if ((isUserDataValid()) && ($loadUserData === true)) {
472                         // It is valid
473                         $content = merge_array($content, getUserDataArray());
474
475                         // But we don't like hashed passwords be mailed
476                         unset($content['password']);
477                 } // END - if
478
479                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content()=' . count($content) . ' - AFTER!');
480         } // END - if
481
482         // Base directory
483         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
484
485         // Detect extra path
486         $extraPath = detectExtraTemplatePath($template);
487
488         // Generate full FQFN
489         $FQFN = $basePath . $extraPath . $template . '.tpl';
490
491         // Does the special template exists?
492         if (!isFileReadable($FQFN)) {
493                 // Reset to default template
494                 $FQFN = $basePath . $template . '.tpl';
495         } // END - if
496
497         // Now does the final template exists?
498         $newContent = '';
499         if (isFileReadable($FQFN)) {
500                 // The local file does exists so we load it. :)
501                 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
502
503                 // Run code
504                 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
505                 eval($GLOBALS['tpl_content'][$template]);
506         } elseif (!empty($template)) {
507                 // Template file not found
508                 $newContent = '<div class="para">
509         {--TEMPLATE_404--}: ' . $template . '
510 </div>
511 <div class="para">
512         {--TEMPLATE_CONTENT--}:
513         <pre>' . print_r($content, true) . '</pre>
514         {--TEMPLATE_DATA--}:
515         <pre>' . print_r($DATA, 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         unset($DATA);
540
541         // Return content
542         return $newContent;
543 }
544
545 // "Getter" for menu CSS classes, mainly used in templates
546 function getMenuCssClasses ($data) {
547         // $data needs to be converted into an array
548         $content = explode('|', $data);
549
550         // Non-existent index 2 will happen in menu blocks
551         if (!isset($content[2])) $content[2] = '';
552
553         // Re-construct the array: 0=visible,1=locked,2=prefix
554         $content['visible'] = $content[0];
555         $content['locked']  = $content[1];
556
557         // Call our "translator" function
558         $content = translateMenuVisibleLocked($content, $content[2]);
559
560         // Return CSS classes
561         return ($content['visible_css'] . ' ' . $content['locked_css']);
562 }
563
564 // Generate XHTML code for the CAPTCHA
565 function generateCaptchaCode ($code, $type, $type, $userid) {
566         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $type . '&amp;mode=img&amp;code=' . $code . '%}" />';
567 }
568
569 // Compiles the given HTML/mail code
570 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
571         // Is the code a string or should we not compile?
572         if ((!is_string($code)) || ($compileCode === false)) {
573                 // Silently return it
574                 return $code;
575         } // END - if
576
577         // Start couting
578         $startCompile = microtime(true);
579
580         // Comile the code
581         $code = compileRawCode($code, $simple, $constants, $full);
582
583         // Get timing
584         $compiled = microtime(true);
585
586         // Add timing if enabled
587         if (isTemplateHtml()) {
588                 // Add timing, this should be disabled in
589                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
590         } // END - if
591
592         // Return compiled code
593         return $code;
594 }
595
596 // Compiles the code (use compileCode() only for HTML because of the comments)
597 // @TODO $simple/$constants are deprecated
598 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
599         // Is the code a string or shall we not compile?
600         if ((!is_string($code)) || ($compileCode === false)) {
601                 // Silently return it
602                 return $code;
603         } // END - if
604
605         // Init replacement-array with smaller set of security characters
606         $secChars = $GLOBALS['url_chars'];
607
608         // Select full set of chars to replace when we e.g. want to compile URLs
609         if ($full === true) {
610                 $secChars = $GLOBALS['security_chars'];
611         } // END - if
612
613         // Compile more through a filter
614         $code = runFilterChain('compile_code', $code);
615
616         // Compile message strings
617         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
618
619         // Compile QUOT and other non-HTML codes
620         $code = str_replace($secChars['to'], $secChars['from'], $code);
621
622         // Find $content[bla][blub] entries
623         // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
624         preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
625
626         // Are some matches found?
627         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
628                 // Replace all matches
629                 $matchesFound = array();
630                 foreach ($matches[0] as $key => $match) {
631                         // Fuzzy look has failed by default
632                         $fuzzyFound = false;
633
634                         // Fuzzy look on match if already found
635                         foreach ($matchesFound as $found => $set) {
636                                 // Get test part
637                                 $test = substr($found, 0, strlen($match));
638
639                                 // Does this entry exist?
640                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
641                                 if ($test == $match) {
642                                         // Match found
643                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
644                                         $fuzzyFound = true;
645                                         break;
646                                 } // END - if
647                         } // END - foreach
648
649                         // Skip this entry?
650                         if ($fuzzyFound === true) continue;
651
652                         // Take all string elements
653                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$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[4][$key]] = 1;
659                                 $matchesFound[$match] = 1;
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                         }
666                 } // END - foreach
667         } // END - if
668
669         // Return it
670         return $code;
671 }
672
673 //
674 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
675         $OUT = '';
676
677         if ($type == 'yn') {
678                 // This is a yes/no selection only!
679                 if ($id > 0) $prefix .= '[' . $id . ']';
680                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
681         } else {
682                 // Begin with regular selection box here
683                 if (!empty($prefix)) $prefix .= '_';
684                 $type2 = $type;
685                 if ($id > 0) $type2 .= '[' . $id . ']';
686                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
687         }
688
689         switch ($type) {
690                 case 'day': // Day
691                         for ($idx = 1; $idx < 32; $idx++) {
692                                 $OUT .= '<option value="' . $idx . '"';
693                                 if ($default == $idx) $OUT .= ' selected="selected"';
694                                 $OUT .= '>' . $idx . '</option>';
695                         } // END - for
696                         break;
697
698                 case 'month': // Month
699                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
700                                 $OUT .= '<option value="' . $idx . '"';
701                                 if ($default == $idx) $OUT .= ' selected="selected"';
702                                 $OUT .= '>' . $descr . '</option>';
703                         } // END - for
704                         break;
705
706                 case 'year': // Year
707                         // Get current year
708                         $year = getYear();
709
710                         // Use configured min age or fixed?
711                         if (isExtensionInstalledAndNewer('other', '0.2.1')) {
712                                 // Configured
713                                 $startYear = $year - getConfig('min_age');
714                         } else {
715                                 // Fixed 16 years
716                                 $startYear = $year - 16;
717                         }
718
719                         // Calculate earliest year (100 years old people can still enter Internet???)
720                         $minYear = $year - 100;
721
722                         // Check if the default value is larger than minimum and bigger than actual year
723                         if (($default > $minYear) && ($default >= $year)) {
724                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
725                                         $OUT .= '<option value="' . $idx . '"';
726                                         if ($default == $idx) $OUT .= ' selected="selected"';
727                                         $OUT .= '>' . $idx . '</option>';
728                                 } // END - for
729                         } elseif ($default == -1) {
730                                 // Current year minus 1
731                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
732                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
733                                 } // END - for
734                         } else {
735                                 // Get current year and subtract the configured minimum age
736                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
737                                 // Calculate earliest year depending on extension version
738                                 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
739                                         // Use configured minimum age
740                                         $year = getYear() - getConfig('min_age');
741                                 } else {
742                                         // Use fixed 16 years age
743                                         $year = getYear() - 16;
744                                 }
745
746                                 // Construct year selection list
747                                 for ($idx = $minYear; $idx <= $year; $idx++) {
748                                         $OUT .= '<option value="' . $idx . '"';
749                                         if ($default == $idx) $OUT .= ' selected="selected"';
750                                         $OUT .= '>' . $idx . '</option>';
751                                 } // END - for
752                         }
753                         break;
754
755                 case 'sec':
756                 case 'min':
757                         for ($idx = 0; $idx < 60; $idx+=5) {
758                                 if (strlen($idx) == 1) $idx = '0' . $idx;
759                                 $OUT .= '<option value="' . $idx . '"';
760                                 if ($default == $idx) $OUT .= ' selected="selected"';
761                                 $OUT .= '>' . $idx . '</option>';
762                         } // END - for
763                         break;
764
765                 case 'hour':
766                         for ($idx = 0; $idx < 24; $idx++) {
767                                 if (strlen($idx) == 1) $idx = '0' . $idx;
768                                 $OUT .= '<option value="' . $idx . '"';
769                                 if ($default == $idx) $OUT .= ' selected="selected"';
770                                 $OUT .= '>' . $idx . '</option>';
771                         } // END - for
772                         break;
773
774                 case 'yn':
775                         $OUT .= '<option value="Y"';
776                         if ($default == 'Y') $OUT .= ' selected="selected"';
777                         $OUT .= '>{--YES--}</option><option value="N"';
778                         if ($default != 'Y') $OUT .= ' selected="selected"';
779                         $OUT .= '>{--NO--}</option>';
780                         break;
781         }
782         $OUT .= '</select>';
783         return $OUT;
784 }
785
786 // Insert the code in $img_code into jpeg or PNG image
787 function generateImageOrCode ($img_code, $headerSent = true) {
788         // Is the code size oversized or shouldn't we display it?
789         if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
790                 // Stop execution of function here because of over-sized code length
791                 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
792         } elseif ($headerSent === false) {
793                 // Return an HTML code here
794                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
795         }
796
797         // Load image
798         $img = sprintf("%s/theme/%s/images/code_bg.%s",
799                 getPath(),
800                 getCurrentTheme(),
801                 getImgType()
802         );
803
804         // Is it readable?
805         if (isFileReadable($img)) {
806                 // Switch image type
807                 switch (getImgType()) {
808                         case 'jpg': // Okay, load image and hide all errors
809                                 $image = imagecreatefromjpeg($img);
810                                 break;
811
812                         case 'png': // Okay, load image and hide all errors
813                                 $image = imagecreatefrompng($img);
814                                 break;
815                 } // END - switch
816         } else {
817                 // Silently log the error
818                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
819                 return;
820         }
821
822         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
823         $text_color = imagecolorallocate($image, 0, 0, 0);
824
825         // Insert code into image
826         imagestring($image, 5, 14, 2, $img_code, $text_color);
827
828         // Return to browser
829         setContentType('image/' . getImgType());
830
831         // Output image with matching image factory
832         switch (getImgType()) {
833                 case 'jpg': imagejpeg($image); break;
834                 case 'png': imagepng($image);  break;
835         } // END - switch
836
837         // Remove image from memory
838         imagedestroy($image);
839 }
840
841 // Create selection box or array of splitted timestamp
842 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
843         // Do not continue if ONE_DAY is absend
844         if (!isConfigEntrySet('ONE_DAY')) {
845                 // And return the timestamp itself or empty array
846                 if ($return_array === true) {
847                         return array();
848                 } else {
849                         return $timestamp;
850                 }
851         } // END - if
852
853         // Calculate 2-seconds timestamp
854         $stamp = round($timestamp);
855         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
856
857         // Do we have a leap year?
858         $SWITCH = '0';
859         $TEST = getYear() / 4;
860         $M1 = getMonth();
861         $M2 = getMonth(time() + $timestamp);
862
863         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
864         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  {
865                 $SWITCH = getOneDay();
866         } // END - switch
867
868         // First of all years...
869         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
870         //* DEBUG: */ debugOutput('Y=' . $Y);
871         // Next months...
872         $M = abs(floor($timestamp / 2628000 - $Y * 12));
873         //* DEBUG: */ debugOutput('M=' . $M);
874         // Next weeks
875         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
876         //* DEBUG: */ debugOutput('W=' . $W);
877         // Next days...
878         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
879         //* DEBUG: */ debugOutput('D=' . $D);
880         // Next hours...
881         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
882         //* DEBUG: */ debugOutput('h=' . $h);
883         // Next minutes..
884         $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));
885         //* DEBUG: */ debugOutput('m=' . $m);
886         // And at last seconds...
887         $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));
888         //* DEBUG: */ debugOutput('s=' . $s);
889
890         // Is seconds zero and time is < 60 seconds?
891         if (($s == '0') && ($timestamp < 60)) {
892                 // Fix seconds
893                 $s = round($timestamp);
894         } // END - if
895
896         //
897         // Now we convert them in seconds...
898         //
899         if ($return_array) {
900                 // Just put all data in an array for later use
901                 $OUT = array(
902                         'YEARS'   => $Y,
903                         'MONTHS'  => $M,
904                         'WEEKS'   => $W,
905                         'DAYS'    => $D,
906                         'HOURS'   => $h,
907                         'MINUTES' => $m,
908                         'SECONDS' => $s
909                 );
910         } else {
911                 // Generate table
912                 $OUT  = '<div align="' . $align . '">';
913                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
914                 $OUT .= '<tr>';
915
916                 if (isInString('Y', $display) || (empty($display))) {
917                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
918                 } // END - if
919
920                 if (isInString('M', $display) || (empty($display))) {
921                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
922                 } // END - if
923
924                 if (isInString('W', $display) || (empty($display))) {
925                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
926                 } // END - if
927
928                 if (isInString('D', $display) || (empty($display))) {
929                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
930                 } // END - if
931
932                 if (isInString('h', $display) || (empty($display))) {
933                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
934                 } // END - if
935
936                 if (isInString('m', $display) || (empty($display))) {
937                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
938                 } // END - if
939
940                 if (isInString('s', $display) || (empty($display))) {
941                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
942                 } // END - if
943
944                 $OUT .= '</tr>';
945                 $OUT .= '<tr>';
946
947                 if (isInString('Y', $display) || (empty($display))) {
948                         // Generate year selection
949                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
950                         for ($idx = 0; $idx <= 10; $idx++) {
951                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
952                                 if ($idx == $Y) $OUT .= ' selected="selected"';
953                                 $OUT .= '>' . $idx . '</option>';
954                         } // END - for
955                         $OUT .= '</select></td>';
956                 } else {
957                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
958                 }
959
960                 if (isInString('M', $display) || (empty($display))) {
961                         // Generate month selection
962                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
963                         for ($idx = 0; $idx <= 11; $idx++) {
964                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
965                                 if ($idx == $M) $OUT .= ' selected="selected"';
966                                 $OUT .= '>' . $idx . '</option>';
967                         } // END - for
968                         $OUT .= '</select></td>';
969                 } else {
970                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
971                 }
972
973                 if (isInString('W', $display) || (empty($display))) {
974                         // Generate week selection
975                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
976                         for ($idx = 0; $idx <= 4; $idx++) {
977                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
978                                 if ($idx == $W) $OUT .= ' selected="selected"';
979                                 $OUT .= '>' . $idx . '</option>';
980                         } // END - for
981                         $OUT .= '</select></td>';
982                 } else {
983                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
984                 }
985
986                 if (isInString('D', $display) || (empty($display))) {
987                         // Generate day selection
988                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
989                         for ($idx = 0; $idx <= 31; $idx++) {
990                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
991                                 if ($idx == $D) $OUT .= ' selected="selected"';
992                                 $OUT .= '>' . $idx . '</option>';
993                         } // END - for
994                         $OUT .= '</select></td>';
995                 } else {
996                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
997                 }
998
999                 if (isInString('h', $display) || (empty($display))) {
1000                         // Generate hour selection
1001                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1002                         for ($idx = 0; $idx <= 23; $idx++) {
1003                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1004                                 if ($idx == $h) $OUT .= ' selected="selected"';
1005                                 $OUT .= '>' . $idx . '</option>';
1006                         } // END - for
1007                         $OUT .= '</select></td>';
1008                 } else {
1009                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1010                 }
1011
1012                 if (isInString('m', $display) || (empty($display))) {
1013                         // Generate minute selection
1014                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1015                         for ($idx = 0; $idx <= 59; $idx++) {
1016                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1017                                 if ($idx == $m) $OUT .= ' selected="selected"';
1018                                 $OUT .= '>' . $idx . '</option>';
1019                         } // END - for
1020                         $OUT .= '</select></td>';
1021                 } else {
1022                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1023                 }
1024
1025                 if (isInString('s', $display) || (empty($display))) {
1026                         // Generate second selection
1027                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1028                         for ($idx = 0; $idx <= 59; $idx++) {
1029                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1030                                 if ($idx == $s) $OUT .= ' selected="selected"';
1031                                 $OUT .= '>' . $idx . '</option>';
1032                         } // END - for
1033                         $OUT .= '</select></td>';
1034                 } else {
1035                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1036                 }
1037                 $OUT .= '</tr>';
1038                 $OUT .= '</table>';
1039                 $OUT .= '</div>';
1040         }
1041
1042         // Return generated HTML code
1043         return $OUT;
1044 }
1045
1046 // Generate a list of administrative links to a given userid
1047 function generateMemberAdminActionLinks ($userid) {
1048         // Make sure userid is a number
1049         if ($userid != bigintval($userid)) {
1050                 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1051         } // END - if
1052
1053         // Define all main targets
1054         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1055
1056         // Get user status
1057         $status = getFetchedUserData('userid', $userid, 'status');
1058
1059         // Begin of navigation links
1060         $OUT = '[';
1061
1062         foreach ($targetArray as $tar) {
1063                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1064                 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1065                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1066                         // Locked accounts shall be unlocked
1067                         $OUT .= 'UNLOCK_USER';
1068                 } elseif ($tar == 'del_user') {
1069                         // @TODO Deprecate this thing
1070                         $OUT .= 'DELETE_USER';
1071                 } else {
1072                         // All other status is fine
1073                         $OUT .= strtoupper($tar);
1074                 }
1075                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1076                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1077                         // Locked accounts shall be unlocked
1078                         $OUT .= 'UNLOCK_USER';
1079                 } elseif ($tar == 'del_user') {
1080                         // @TODO Deprecate this thing
1081                         $OUT .= 'DELETE_USER';
1082                 } else {
1083                         // All other status is fine
1084                         $OUT .= strtoupper($tar);
1085                 }
1086                 $OUT .= '--}</a></span>|';
1087         } // END - foreach
1088
1089         // Add special link, in case of the account is unconfirmed
1090         if ($status == 'UNCONFIRMED') {
1091                 // Add it
1092                 $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>|';
1093         } // END - if
1094
1095         // Finish navigation link
1096         $OUT = substr($OUT, 0, -1) . ']';
1097
1098         // Return string
1099         return $OUT;
1100 }
1101
1102 // Generate an email link
1103 function generateEmailLink ($email, $table = 'admins') {
1104         // Default email link (INSECURE! Spammer can read this by harvester programs)
1105         $EMAIL = 'mailto:' . $email;
1106
1107         // Check for several extensions
1108         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1109                 // Create email link for contacting admin in guest area
1110                 $EMAIL = generateAdminEmailLink($email);
1111         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1112                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1113                 $EMAIL = generateUserEmailLink($email);
1114         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1115                 // Create email link to contact sponsor within admin area (or like the link above?)
1116                 $EMAIL = generateSponsorEmailLink($email);
1117         }
1118
1119         // Shall I close the link when there is no admin?
1120         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1121
1122         // Return email link
1123         return $EMAIL;
1124 }
1125
1126 // Output error messages in a fasioned way and die...
1127 function app_die ($F, $L, $message) {
1128         // Check if Script is already dieing and not let it kill itself another 1000 times
1129         if (isset($GLOBALS['app_died'])) {
1130                 // Script tried to kill itself twice
1131                 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1132         } // END - if
1133
1134         // Make sure, that the script realy realy diese here and now
1135         $GLOBALS['app_died'] = true;
1136
1137         // Set content type as text/html
1138         setContentType('text/html');
1139
1140         // Load header
1141         loadIncludeOnce('inc/header.php');
1142
1143         // Rewrite message for output
1144         $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1145
1146         // Load the message template
1147         loadTemplate('app_die_message', false, $message);
1148
1149         // Load footer
1150         loadIncludeOnce('inc/footer.php');
1151 }
1152
1153 // Display parsing time and number of SQL queries in footer
1154 function displayParsingTime () {
1155         // Is the timer started?
1156         if (!isset($GLOBALS['startTime'])) {
1157                 // Abort here
1158                 return false;
1159         } // END - if
1160
1161         // Get end time
1162         $endTime = microtime(true);
1163
1164         // "Explode" both times
1165         $start = explode(' ', $GLOBALS['startTime']);
1166         $end = explode(' ', $endTime);
1167         $runTime = $end[0] - $start[0];
1168         if ($runTime < 0) {
1169                 $runTime = '0';
1170         } // END - if
1171
1172         // Prepare output
1173         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1174         $content = array(
1175                 'run_time' => $runTime,
1176                 'sql_time' => (getConfig('sql_time') * 1000),
1177         );
1178
1179         // Load the template
1180         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1181 }
1182
1183 // Output a debug backtrace to the user
1184 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1185         // Is this already called?
1186         if (isset($GLOBALS[__FUNCTION__])) {
1187                 // Other backtrace
1188                 print 'Message:' . $message . '<br />Backtrace:<pre>';
1189                 debug_print_backtrace();
1190                 die('</pre>');
1191         } // END - if
1192
1193         // Set this function as called
1194         $GLOBALS[__FUNCTION__] = true;
1195
1196         // Init message
1197         $debug = '';
1198
1199         // Is the optional message set?
1200         if (!empty($message)) {
1201                 // Use and log it
1202                 $debug = sprintf("Note: %s<br />\n",
1203                         $message
1204                 );
1205
1206                 // @TODO Add a little more infos here
1207                 logDebugMessage($F, $L, strip_tags($message));
1208         } // END - if
1209
1210         // Add output
1211         $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>';
1212         $debug .= debug_get_printable_backtrace();
1213         $debug .= '</pre>';
1214         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1215         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1216
1217         // Send an email? (e.g. not wanted for evaluation errors)
1218         if (($sendEmail === true) && (!isInstallationPhase())) {
1219                 // Prepare content
1220                 $content = array(
1221                         'message'   => trim($message),
1222                         'backtrace' => trim(debug_get_mailable_backtrace())
1223                 );
1224
1225                 // Send email to webmaster
1226                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1227         } // END - if
1228
1229         // And abort here
1230         app_die($F, $L, $debug);
1231 }
1232
1233 // Compile characters which are allowed in URLs
1234 function compileUriCode ($code, $simple = true) {
1235         // Compile constants
1236         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1237
1238         // Compile QUOT and other non-HTML codes
1239         $code = str_replace('{DOT}', '.',
1240                 str_replace('{SLASH}', '/',
1241                 str_replace('{QUOT}', "'",
1242                 str_replace('{DOLLAR}', '$',
1243                 str_replace('{OPEN_ANCHOR}', '(',
1244                 str_replace('{CLOSE_ANCHOR}', ')',
1245                 str_replace('{OPEN_SQR}', '[',
1246                 str_replace('{CLOSE_SQR}', ']',
1247                 str_replace('{PER}', '%',
1248                 $code
1249         )))))))));
1250
1251         // Return compiled code
1252         return $code;
1253 }
1254
1255 // Handle message codes from URL
1256 function handleCodeMessage () {
1257         if (isGetRequestParameterSet('code')) {
1258                 // Default extension is 'unknown'
1259                 $ext = 'unknown';
1260
1261                 // Is extension given?
1262                 if (isGetRequestParameterSet('ext')) {
1263                         $ext = getRequestParameter('ext');
1264                 } // END - if
1265
1266                 // Convert the 'code' parameter from URL to a human-readable message
1267                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1268
1269                 // Load message template
1270                 loadTemplate('message', false, $message);
1271         } // END - if
1272 }
1273
1274 // Generates a 'extension foo out-dated' message
1275 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1276         // Is the extension empty?
1277         if (empty($ext_name)) {
1278                 // This should not happen
1279                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1280         } // END - if
1281
1282         // Default message
1283         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1284
1285         // Is an admin logged in?
1286         if (isAdmin()) {
1287                 // Then output admin message
1288                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1289         } // END - if
1290
1291         // Return prepared message
1292         return $message;
1293 }
1294
1295 // Generates a 'extension foo inactive' message
1296 function generateExtensionInactiveMessage ($ext_name) {
1297         // Is the extension empty?
1298         if (empty($ext_name)) {
1299                 // This should not happen
1300                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1301         } // END - if
1302
1303         // Default message
1304         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1305
1306         // Is an admin logged in?
1307         if (isAdmin()) {
1308                 // Then output admin message
1309                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1310         } // END - if
1311
1312         // Return prepared message
1313         return $message;
1314 }
1315
1316 // Generates a 'extension foo not installed' message
1317 function generateExtensionNotInstalledMessage ($ext_name) {
1318         // Is the extension empty?
1319         if (empty($ext_name)) {
1320                 // This should not happen
1321                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1322         } // END - if
1323
1324         // Default message
1325         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1326
1327         // Is an admin logged in?
1328         if (isAdmin()) {
1329                 // Then output admin message
1330                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1331         } // END - if
1332
1333         // Return prepared message
1334         return $message;
1335 }
1336
1337 // Generates a message depending on if the extension is not installed or not
1338 // just activated
1339 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1340         // Init message
1341         $message = '';
1342
1343         // Is the extension not installed or just deactivated?
1344         switch (isExtensionInstalled($ext_name)) {
1345                 case true; // Deactivated!
1346                         $message = generateExtensionInactiveMessage($ext_name);
1347                         break;
1348
1349                 case false; // Not installed!
1350                         $message = generateExtensionNotInstalledMessage($ext_name);
1351                         break;
1352
1353                 default: // Should not happen!
1354                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1355                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1356                         break;
1357         } // END - switch
1358
1359         // Return the message
1360         return $message;
1361 }
1362
1363 // Print code with line numbers
1364 function linenumberCode ($code)    {
1365         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1366         $count_lines = count($codeE);
1367
1368         $r = 'Line | Code:<br />';
1369         foreach ($codeE as $line => $c) {
1370                 $r .= '<div class="line"><span class="linenum">';
1371                 if ($count_lines == 1) {
1372                         $r .= 1;
1373                 } else {
1374                         $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1375                 }
1376                 $r .= '</span>|';
1377
1378                 // Add code
1379                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1380         } // END - foreach
1381
1382         return '<div class="code">' . $r . '</div>';
1383 }
1384
1385 // Determines the right page title
1386 function determinePageTitle () {
1387         // Config and database connection valid?
1388         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1389                 // Init title
1390                 $TITLE = '';
1391
1392                 // Title decoration enabled?
1393                 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1394
1395                 // Do we have some extra title?
1396                 if (isExtraTitleSet()) {
1397                         // Then prepent it
1398                         $TITLE .= getExtraTitle() . ' by ';
1399                 } // END - if
1400
1401                 // Add main title
1402                 $TITLE .= getMainTitle();
1403
1404                 // Add title of module? (middle decoration will also be added!)
1405                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1406                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1407                 } // END - if
1408
1409                 // Add title from what file
1410                 $mode = '';
1411                 if (getModule() == 'login') $mode = 'member';
1412                 elseif (getModule() == 'index') $mode = 'guest';
1413                 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1414
1415                 // Add title decorations? (right)
1416                 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1417
1418                 // Remember title in constant for the template
1419                 $pageTitle = $TITLE;
1420         } elseif ((isInstalled()) && (isAdminRegistered())) {
1421                 // Installed, admin registered but no ext-sql_patches
1422                 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1423         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1424                 // Installed but no admin registered
1425                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1426         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1427                 // Installation mode
1428                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1429         } else {
1430                 // Configuration not found
1431                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1432
1433                 // Do not add the fatal message in installation mode
1434                 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1435                         // Please report this
1436                         debug_report_bug(__FUNCTION__, __LINE__, 'No configuration data found!');
1437                 } // END - if
1438         }
1439
1440         // Return title
1441         return decodeEntities($pageTitle);
1442 }
1443
1444 // Checks wethere there is a cache file there. This function is cached.
1445 function isTemplateCached ($template) {
1446         // Do we have cached this result?
1447         if (!isset($GLOBALS['template_cache'][$template])) {
1448                 // Generate FQFN
1449                 $FQFN = generateCacheFqfn($template);
1450
1451                 // Is it there?
1452                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1453         } // END - if
1454
1455         // Return it
1456         return $GLOBALS['template_cache'][$template];
1457 }
1458
1459 // Flushes non-flushed template cache to disk
1460 function flushTemplateCache ($template, $eval) {
1461         // Is this cache flushed?
1462         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1463                 // Generate FQFN
1464                 $FQFN = generateCacheFqfn($template);
1465
1466                 // And flush it
1467                 writeToFile($FQFN, $eval, true);
1468         } // END - if
1469 }
1470
1471 // Reads a template cache
1472 function readTemplateCache ($template) {
1473         // Check it again
1474         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1475                 // This should not happen
1476                 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1477         } // END - if
1478
1479         // Is it cached?
1480         if (!isset($GLOBALS['template_eval'][$template])) {
1481                 // Generate FQFN
1482                 $FQFN = generateCacheFqfn($template);
1483
1484                 // And read from it
1485                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1486         } // END - if
1487
1488         // And return it
1489         return $GLOBALS['template_eval'][$template];
1490 }
1491
1492 // Escapes quotes (default is only double-quotes)
1493 function escapeQuotes ($str, $single = false) {
1494         // Should we escape all?
1495         if ($single === true) {
1496                 // Escape all (including null)
1497                 $str = addslashes($str);
1498         } else {
1499                 // Remove escaping of single quotes
1500                 $str = str_replace("\\'", "'", $str);
1501
1502                 // Escape only double-quotes but prevent double-quoting
1503                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1504         }
1505
1506         // Return the escaped string
1507         return $str;
1508 }
1509
1510 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1511 function escapeJavaScriptQuotes ($str) {
1512         // Replace all double-quotes and secure back-ticks
1513         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1514
1515         // Return it
1516         return $str;
1517 }
1518
1519 // Send out mails depending on the 'mod/modes' combination
1520 // @TODO Lame description for this function
1521 function sendModeMails ($mod, $modes) {
1522         // Init user data
1523         $content = array ();
1524
1525         // Load hash
1526         if (fetchUserData(getMemberId())) {
1527                 // Extract salt from cookie
1528                 $salt = substr(getSession('u_hash'), 0, -40);
1529
1530                 // Now let's compare passwords
1531                 $hash = encodeHashForCookie(getUserData('password'));
1532
1533                 // Does the hash match or should we change it?
1534                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1535                         // Load the data
1536                         $content = getUserDataArray();
1537
1538                         // Clear/init the content variable
1539                         $content['message'] = '';
1540
1541                         // Which mail?
1542                         // @TODO Move this in a filter
1543                         switch ($mod) {
1544                                 case 'mydata':
1545                                         foreach ($modes as $mode) {
1546                                                 switch ($mode) {
1547                                                         case 'normal': break; // Do not add any special lines
1548                                                         case 'email': // Email was changed!
1549                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1550                                                                 break;
1551
1552                                                         case 'password': // Password was changed
1553                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1554                                                                 break;
1555
1556                                                         default:
1557                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1558                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1559                                                                 break;
1560                                                 } // END - switch
1561                                         } // END - foreach
1562
1563                                         if (isExtensionActive('country')) {
1564                                                 // Replace code with description
1565                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1566                                         } // END - if
1567
1568                                         // Merge content with data from POST
1569                                         $content = merge_array($content, postRequestArray());
1570
1571                                         // Load template
1572                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1573
1574                                         if (isAdminNotificationEnabled()) {
1575                                                 // The admin needs to be notified about a profile change
1576                                                 $message_admin = 'admin_mydata_notify';
1577                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1578                                         } else {
1579                                                 // No mail to admin
1580                                                 $message_admin = '';
1581                                                 $sub_adm   = '';
1582                                         }
1583
1584                                         // Set subject lines
1585                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1586
1587                                         // Output success message
1588                                         $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1589                                         break;
1590
1591                                 default: // Unsupported module!
1592                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1593                                         $content['message'] = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1594                                         break;
1595                         } // END - switch
1596                 } else {
1597                         // Passwords mismatch
1598                         $content['message'] = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1599                 }
1600         } else {
1601                 // Could not load profile
1602                 $content['message'] = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1603         }
1604
1605         // Send email to user if required
1606         if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1607                 // Send member mail
1608                 sendEmail($content['userid'], $sub_mem, $message);
1609         } // END - if
1610
1611         // Send only if no other error has occured
1612         if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1613                 // Send admin mail
1614                 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1615         } elseif (isAdminNotificationEnabled()) {
1616                 // Cannot send mails to admin!
1617                 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1618         } else {
1619                 // No mail to admin
1620                 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1621         }
1622
1623         // Load template
1624         displayMessage($content['message']);
1625 }
1626
1627 // Generates a 'selection box' from given array
1628 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1629         // Start the output
1630         $OUT = '<select name="' . $name . '" size="1" class="form_select">
1631 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1632
1633         // Walk through all options
1634         foreach ($options as $option) {
1635                 // Add the <option> entry from ...
1636                 if (empty($optionContent)) {
1637                         // ... template
1638                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1639                 } else {
1640                         // ... direct HTML code
1641                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1642                 }
1643         } // END - foreach
1644
1645         // Finish selection box
1646         $OUT .= '</select>';
1647
1648         // Prepare output
1649         $content = array(
1650                 'selection_box' => $OUT,
1651         );
1652
1653         // Load template and return it
1654         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1655 }
1656
1657 // Prepares the header for HTML output
1658 function loadHtmlHeader () {
1659         // Run two filters:
1660         // 1.) pre_page_header (mainly loads the page_header template and includes
1661         //     meta description)
1662         runFilterChain('pre_page_header');
1663
1664         // Here can be something be added, but normally one of the two filters
1665         // around this line should do the job for you.
1666
1667         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1668         //     to close the head-tag)
1669         // Include more header data here
1670         runFilterChain('post_page_header');
1671 }
1672
1673 // Adds page header and footer to output array element
1674 function addPageHeaderFooter () {
1675         // Init output
1676         $OUT = '';
1677
1678         // Add them all together. This is maybe to simple
1679         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1680                 // Add page part if set
1681                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1682         } // END - foreach
1683
1684         // Transfer $OUT to 'output'
1685         $GLOBALS['output'] = $OUT;
1686 }
1687
1688 // Generates meta description for current module and 'what' value
1689 function generateMetaDescriptionCode () {
1690         // Only include from guest area and if sql_patches has correct version
1691         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1692                 // Construct dynamic description
1693                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1694
1695                 // Output it directly
1696                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1697         } // END - if
1698
1699         // Initialize referal system
1700         initReferalSystem();
1701 }
1702
1703 // Generates an FQFN for template cache from the given template name
1704 function generateCacheFqfn ($template, $mode = 'html') {
1705         // Is this cached?
1706         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1707                 // Generate the FQFN
1708                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1709                         "%s_compiled/%s/%s.tpl.cache",
1710                         getCachePath(),
1711                         $mode,
1712                         $template
1713                 );
1714         } // END - if
1715
1716         // Return it
1717         return $GLOBALS['template_cache_fqfn'][$template];
1718 }
1719
1720 // "Fixes" null or empty string to count of dashes
1721 function fixNullEmptyToDashes ($str, $num) {
1722         // Use str as default
1723         $return = $str;
1724
1725         // Is it empty?
1726         if ((is_null($str)) || (trim($str) == '')) {
1727                 // Set it
1728                 $return = str_repeat('-', $num);
1729         } // END - if
1730
1731         // Return final string
1732         return $return;
1733 }
1734
1735 // Translates the "pool type" into human-readable
1736 function translatePoolType ($type) {
1737         // Return "translation"
1738         return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1739 }
1740
1741 // Displays given message in admin_settings_saved template
1742 function displayMessage ($message, $return = false) {
1743         // Load the template
1744         return loadTemplate('admin_settings_saved', $return, $message);
1745 }
1746
1747 // Generates a selection box for (maybe) given gender
1748 function generateGenderSelectionBox ($selectedGender = '') {
1749         // Start the HTML code
1750         $out  = '<select name="gender" size="1" class="form_select">';
1751
1752         // Add the options
1753         $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1754
1755         // Finish HTML code
1756         $out .= '</select>';
1757
1758         // Return the code
1759         return $out;
1760 }
1761
1762 //-----------------------------------------------------------------------------
1763 //                      Template helper functions for EL
1764 //-----------------------------------------------------------------------------
1765
1766 // Color-switch helper function
1767 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1768         // Is it there?
1769         if (!isset($GLOBALS['color_switch'][$template])) {
1770                 // Initialize it
1771                 initTemplateColorSwitch($template);
1772         } elseif ($clear === false) {
1773                 // Switch color if called from loadTemplate()
1774                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1775                 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1776         }
1777
1778         // Return CSS class name
1779         if ($return === true) {
1780                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1781                 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1782         } // END - if
1783 }
1784
1785 // Helper function for extension registration link
1786 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1787         // Default is all non-productive
1788         $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>';
1789
1790         // Is the given extension non-productive?
1791         if (isExtensionProductive($ext_name)) {
1792                 // Productive code
1793                 $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>';
1794         } // END - if
1795
1796         // Return code
1797         return $OUT;
1798 }
1799
1800 // Helper function to create bonus mail admin links
1801 function doTemplateAdminBonusMailLinks ($template, $dummy, $bonusId) {
1802         // Call the inner function
1803         return generateAdminMailLinks('bid', $bonusId);
1804 }
1805
1806 // Helper function to create member mail admin links
1807 function doTemplateAdminMemberMailLinks ($template, $dummy, $mailId) {
1808         // Call the inner function
1809         return generateAdminMailLinks('mid', $mailId);
1810 }
1811
1812 // [EOF]
1813 ?>