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