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