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