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