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