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