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