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