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