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