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