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