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