Code cleanup, more usage of API functions
[mailer.git] / inc / template-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 04/04/2009 *
4  * ===================                          Last change: 04/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : template-functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : Template functions                               *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Template-Funktionen                              *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Wrapper until we merged to the EL branch
44 function preCompileCode ($code, $template = '', $compiled = false, $full = true, $overwrite = false) {
45         return compileCode($code, false, true, $full);
46 }
47
48 // Setter for 'is_template_html'
49 function enableTemplateHtml ($enable = true) {
50         $GLOBALS['is_template_html'] = (bool) $enable;
51 }
52
53 // Checks wether the template is HTML or not by previously set flag
54 // Default: true
55 function isTemplateHtml () {
56         // Is the output_mode other than 0 (HTML), then no comments are enabled
57         if (!isHtmlOutputMode()) {
58                 // No HTML
59                 return false;
60         } else {
61                 // Maybe HTML?
62                 return $GLOBALS['is_template_html'];
63         }
64 }
65
66 // Wrapper for writing debug informations to the browser
67 function debugOutput ($message) {
68         outputHtml('<div class="debug_message">' . $message . '</div>');
69 }
70
71 // "Fixes" an empty string into three dashes (use for templates)
72 function fixEmptyContentToDashes ($str) {
73         // Trim the string
74         $str = trim($str);
75
76         // Is the string empty?
77         if (empty($str)) $str = '---';
78
79         // Return string
80         return $str;
81 }
82
83 // Init color switch
84 function initTemplateColorSwitch ($template) {
85         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
86         $GLOBALS['color_switch'][$template] = 2;
87 }
88
89 // "Getter" for color switch code
90 function getColorSwitchCode ($template) {
91         // Prepare the code
92         $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', false, false) . {DQUOTE}";
93
94         // And return it
95         return $code;
96 }
97
98 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
99 function outputHtml ($htmlCode, $newLine = true) {
100         // Init output
101         if (!isset($GLOBALS['output'])) {
102                 $GLOBALS['output'] = '';
103         } // END - if
104
105         // Do we have HTML-Code here?
106         if (!empty($htmlCode)) {
107                 // Yes, so we handle it as you have configured
108                 switch (getOutputMode()) {
109                         case 'render':
110                                 // That's why you don't need any \n at the end of your HTML code... :-)
111                                 if (getPhpCaching() == 'on') {
112                                         // Output into PHP's internal buffer
113                                         outputRawCode($htmlCode);
114
115                                         // That's why you don't need any \n at the end of your HTML code... :-)
116                                         if ($newLine === true) print("\n");
117                                 } else {
118                                         // Render mode for old or lame servers...
119                                         $GLOBALS['output'] .= $htmlCode;
120
121                                         // That's why you don't need any \n at the end of your HTML code... :-)
122                                         if ($newLine === true) $GLOBALS['output'] .= "\n";
123                                 }
124                                 break;
125
126                         case 'direct':
127                                 // If we are switching from render to direct output rendered code
128                                 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
129
130                                 // The same as above... ^
131                                 outputRawCode($htmlCode);
132                                 if ($newLine === true) print("\n");
133                                 break;
134
135                         default:
136                                 // Huh, something goes wrong or maybe you have edited config.php ???
137                                 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
138                                 break;
139                 } // END - switch
140         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
141                 // Output cached HTML code
142                 $GLOBALS['output'] = ob_get_contents();
143
144                 // Clear output buffer for later output if output is found
145                 if (!empty($GLOBALS['output'])) {
146                         clearOutputBuffer();
147                 } // END - if
148
149                 // Send all HTTP headers
150                 sendHttpHeaders();
151
152                 // Compile and run finished rendered HTML code
153                 compileFinalOutput();
154
155                 // Output code here, DO NOT REMOVE! ;-)
156                 outputRawCode($GLOBALS['output']);
157         } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['output']))) {
158                 // Send all HTTP headers
159                 sendHttpHeaders();
160
161                 // Compile and run finished rendered HTML code
162                 compileFinalOutput();
163
164                 // Output code here, DO NOT REMOVE! ;-)
165                 outputRawCode($GLOBALS['output']);
166         } else {
167                 // And flush all headers
168                 flushHeaders();
169         }
170 }
171
172 // Compiles the final output
173 function compileFinalOutput () {
174         // Add page header and footer
175         addPageHeaderFooter();
176
177         // Do the final compilation
178         $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
179
180         // Extension 'rewrite' installed?
181         if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
182                 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
183         } // END - if
184
185         // Compress it?
186         /**
187          * @TODO On some pages this is buggy
188         if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
189                 // Compress it for HTTP gzip
190                 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9);
191
192                 // Add header
193                 sendHeader('Content-Encoding: gzip');
194         } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
195                 // Compress it for HTTP deflate
196                 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
197
198                 // Add header
199                 sendHeader('Content-Encoding: deflate');
200         }
201         */
202
203         // Add final length
204         sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
205
206         // Flush all headers
207         flushHeaders();
208 }
209
210 // Main compilation loop
211 function doFinalCompilation ($code, $insertComments = true, $enableCodes = true) {
212         // Insert comments? (Only valid with HTML templates, of course)
213         enableTemplateHtml($insertComments);
214
215         // Init counter
216         $cnt = 0;
217
218         // Compile all out
219         while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 5)) {
220                 // Init common variables
221                 $content = array();
222                 $newContent = '';
223
224                 // Compile it
225                 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
226                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), false, true, $enableCodes)) . '";';
227                 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
228                 eval($eval);
229                 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
230                 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
231
232                 // Was that eval okay?
233                 if (empty($newContent)) {
234                         // Something went wrong!
235                         debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
236                 } // END - if
237
238                 // Use it again
239                 $code = $newContent;
240
241                 // Count round
242                 $cnt++;
243         } // END - while
244
245         // Return the compiled code
246         return $code;
247 }
248
249 // Output the raw HTML code
250 function outputRawCode ($htmlCode) {
251         // Output stripped HTML code to avoid broken JavaScript code, etc.
252         print(str_replace('{BACK}', "\\", $htmlCode));
253
254         // Flush the output if only getPhpCaching() is not 'on'
255         if (getPhpCaching() != 'on') {
256                 // Flush it
257                 flush();
258         } // END - if
259 }
260
261 // Load a template file and return it's content (only it's name; do not use ' or ")
262 function loadTemplate ($template, $return = false, $content = array()) {
263         // @TODO Remove this sanity-check if all is fine
264         if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
265
266         // Set current template
267         $GLOBALS['current_template'] = $template;
268
269         // Do we have cache?
270         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
271                 // Evaluate the cache
272                 eval(readTemplateCache($template));
273         } elseif (!isset($GLOBALS['template_eval'][$template])) {
274                 // Make all template names lowercase
275                 $template = strtolower($template);
276
277                 // Init some data
278                 $ret = '';
279
280                 // Base directory
281                 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
282                 $extraPath = detectExtraTemplatePath($template);;
283
284                 // Generate FQFN
285                 $FQFN = $basePath . $extraPath . $template . '.tpl';
286
287                 // Does the special template exists?
288                 if (!isFileReadable($FQFN)) {
289                         // Reset to default template
290                         $FQFN = $basePath . $template . '.tpl';
291                 } // END - if
292
293                 // Now does the final template exists?
294                 if (isFileReadable($FQFN)) {
295                         // Count the template load
296                         incrementConfigEntry('num_templates');
297
298                         // The local file does exists so we load it. :)
299                         $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
300
301                         // Do we have to compile the code?
302                         $ret = '';
303                         if ((strpos($GLOBALS['tpl_content'][$template], '$') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{--') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{?') !== false) || (strpos($GLOBALS['tpl_content'][$template], '{%') !== false)) {
304                                 // Normal HTML output?
305                                 if (isHtmlOutputMode()) {
306                                         // Add surrounding HTML comments to help finding bugs faster
307                                         $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
308
309                                         // Prepare eval() command
310                                         $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($ret)) . '";';
311                                 } elseif (substr($template, 0, 3) == 'js_') {
312                                         // JavaScripts don't like entities and timings
313                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'][$template])) . '");';
314                                 } else {
315                                         // Prepare eval() command, other output doesn't like entities, maybe
316                                         $GLOBALS['template_eval'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
317                                 }
318                         } else {
319                                 // Add surrounding HTML comments to help finding bugs faster
320                                 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['tpl_content'][$template] . '<!-- Template ' . $template . ' - End //-->';
321                                 $GLOBALS['template_eval'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret)) . '";';
322                         } // END - if
323                 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
324                         // Only admins shall see this warning or when installation mode is active
325                         $ret = '<div class="para">
326         <span class="notice">{--TEMPLATE_404--}</span>
327 </div>
328 <div class="para">
329         (' . $template . ')
330 </div>
331 <div class="para">
332         {--TEMPLATE_CONTENT--}
333         <pre>' . print_r($content, true) . '</pre>
334 </div>';
335                 } else {
336                         // No file!
337                         $GLOBALS['template_eval'][$template] = '404';
338                 }
339         }
340
341         // Code set?
342         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
343                 // Eval the code
344                 eval($GLOBALS['template_eval'][$template]);
345         } // END - if
346
347         // Do we have some content to output or return?
348         if (!empty($ret)) {
349                 // Not empty so let's put it out! ;)
350                 if ($return === true) {
351                         // Return the HTML code
352                         return $ret;
353                 } else {
354                         // Output directly
355                         outputHtml($ret);
356                 }
357         } elseif (isDebugModeEnabled()) {
358                 // Warning, empty output!
359                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
360         }
361 }
362
363 // Detects the extra template path from given template name
364 function detectExtraTemplatePath ($template) {
365         // Default is empty
366         $extraPath = '';
367
368         // Do we have cache?
369         if (!isset($GLOBALS['extra_path'][$template])) {
370                 // Check for admin/guest/member/etc. templates
371                 if (substr($template, 0, 6) == 'admin_') {
372                         // Admin template found
373                         $extraPath = 'admin/';
374                 } elseif (substr($template, 0, 6) == 'guest_') {
375                         // Guest template found
376                         $extraPath = 'guest/';
377                 } elseif (substr($template, 0, 7) == 'member_') {
378                         // Member template found
379                         $extraPath = 'member/';
380                 } elseif (substr($template, 0, 7) == 'select_') {
381                         // Selection template found
382                         $extraPath = 'select/';
383                 } elseif (substr($template, 0, 8) == 'install_') {
384                         // Installation template found
385                         $extraPath = 'install/';
386                 } elseif (substr($template, 0, 4) == 'ext_') {
387                         // Extension template found
388                         $extraPath = 'ext/';
389                 } elseif (substr($template, 0, 3) == 'la_') {
390                         // 'Logical-area' template found
391                         $extraPath = 'la/';
392                 } elseif (substr($template, 0, 3) == 'js_') {
393                         // JavaScript template found
394                         $extraPath = 'js/';
395                 } elseif (substr($template, 0, 5) == 'menu_') {
396                         // Menu template found
397                         $extraPath = 'menu/';
398                 } else {
399                         // Test for extension
400                         $test = substr($template, 0, strpos($template, '_'));
401
402                         // Probe for valid extension name
403                         if (isExtensionNameValid($test)) {
404                                 // Set extra path to extension's name
405                                 $extraPath = $test . '/';
406                         } // END - if
407                 }
408
409                 // Store it in cache
410                 $GLOBALS['extra_path'][$template] = $extraPath;
411         } // END - if
412
413         // Return result
414         return $GLOBALS['extra_path'][$template];
415 }
416
417 // Loads an email template and compiles it
418 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
419         global $DATA;
420
421         // Make sure all template names are lowercase!
422         $template = strtolower($template);
423
424         // Is content an array?
425         if (is_array($content)) {
426                 // Add expiration to array
427                 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
428                         // Will never expire!
429                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
430                 } elseif (isConfigEntrySet('auto_purge')) {
431                         // Create nice date string
432                         $content['expiration'] = '{%pipe,getAutoPurge,createFancyTime%}';
433                 } else {
434                         // Missing entry
435                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
436                 }
437         } // END - if
438
439         // Load user's data
440         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
441         if ((isValidUserId($userid)) && (is_array($content))) {
442                 // If nickname extension is installed, fetch nickname as well
443                 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
444                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
445                         // Load by nickname
446                         fetchUserData($userid, 'nickname');
447                 } else {
448                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
449                         /// Load by userid
450                         fetchUserData($userid);
451                 }
452
453                 // Merge data if valid
454                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
455                 if (isUserDataValid()) {
456                         $content = merge_array($content, getUserDataArray());
457                 } // END - if
458                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
459         } // END - if
460
461         // Base directory
462         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
463
464         // Detect extra path
465         $extraPath = detectExtraTemplatePath($template);
466
467         // Generate full FQFN
468         $FQFN = $basePath . $extraPath . $template . '.tpl';
469
470         // Does the special template exists?
471         if (!isFileReadable($FQFN)) {
472                 // Reset to default template
473                 $FQFN = $basePath . $template . '.tpl';
474         } // END - if
475
476         // Now does the final template exists?
477         $newContent = '';
478         if (isFileReadable($FQFN)) {
479                 // The local file does exists so we load it. :)
480                 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
481
482                 // Run code
483                 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
484                 eval($GLOBALS['tpl_content'][$template]);
485         } elseif (!empty($template)) {
486                 // Template file not found!
487                 $newContent = '<div class="para">
488         {--TEMPLATE_404--}: ' . $template . '
489 </div>
490 <div class="para">
491         {--TEMPLATE_CONTENT--}
492         <pre>' . print_r($content, true) . '</pre>
493         {--TEMPLATE_DATA--}
494         <pre>' . print_r($DATA, true) . '</pre>
495 </div>';
496
497                 // Debug mode not active? Then remove the HTML tags
498                 if (!isDebugModeEnabled()) {
499                         // Remove HTML tags
500                         $newContent = secureString($newContent);
501                 } // END - if
502         } else {
503                 // No template name supplied!
504                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
505         }
506
507         // Is there some content?
508         if (empty($newContent)) {
509                 // Compiling failed
510                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
511
512                 // Add last error if the required function exists
513                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
514         } // END - if
515
516         // Remove content and data
517         unset($content);
518         unset($DATA);
519
520         // Return content
521         return $newContent;
522 }
523
524 // "Getter" for menu CSS classes, mainly used in templates
525 function getMenuCssClasses ($data) {
526         // $data needs to be converted into an array
527         $content = explode('|', $data);
528
529         // Non-existent index 2 will happen in menu blocks
530         if (!isset($content[2])) $content[2] = '';
531
532         // Re-construct the array: 0=visible,1=locked,2=prefix
533         $content['visible'] = $content[0];
534         $content['locked']  = $content[1];
535
536         // Call our "translator" function
537         $content = translateMenuVisibleLocked($content, $content[2]);
538
539         // Return CSS classes
540         return ($content['visible_css'] . ' ' . $content['locked_css']);
541 }
542
543 // Generate XHTML code for the CAPTCHA
544 function generateCaptchaCode ($code, $type, $DATA, $userid) {
545         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '%}" />';
546 }
547
548 // Compiles the given HTML/mail code
549 function compileCode ($code, $simple = false, $constants = true, $full = true) {
550         // Is the code a string?
551         if (!is_string($code)) {
552                 // Silently return it
553                 return $code;
554         } // END - if
555
556         // Start couting
557         $startCompile = microtime(true);
558
559         // Comile the code
560         $code = compileRawCode($code, $simple, $constants, $full);
561
562         // Get timing
563         $compiled = microtime(true);
564
565         // Add timing if enabled
566         if (isTemplateHtml()) {
567                 // Add timing, this should be disabled in
568                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
569         } // END - if
570
571         // Return compiled code
572         return $code;
573 }
574
575 // Compiles the code (use compileCode() only for HTML because of the comments)
576 // @TODO $simple/$constants are deprecated
577 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
578         // Is the code a string?
579         if (!is_string($code)) {
580                 // Silently return it
581                 return $code;
582         } // END - if
583
584         // Init replacement-array with smaller set of security characters
585         $secChars = $GLOBALS['url_chars'];
586
587         // Select full set of chars to replace when we e.g. want to compile URLs
588         if ($full === true) $secChars = $GLOBALS['security_chars'];
589
590         // Compile more through a filter
591         $code = runFilterChain('compile_code', $code);
592
593         // Compile message strings
594         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
595
596         // Compile QUOT and other non-HTML codes
597         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 = 'form_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_USER_ACTION_LINK_';
1041                 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1042                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1043                         // Locked accounts shall be unlocked
1044                         $OUT .= 'UNLOCK_USER';
1045                 } elseif ($tar == 'del_user') {
1046                         // @TODO Deprecate this thing
1047                         $OUT .= 'DELETE_USER';
1048                 } else {
1049                         // All other status is fine
1050                         $OUT .= strtoupper($tar);
1051                 }
1052                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1053                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1054                         // Locked accounts shall be unlocked
1055                         $OUT .= 'UNLOCK_USER';
1056                 } elseif ($tar == 'del_user') {
1057                         // @TODO Deprecate this thing
1058                         $OUT .= 'DELETE_USER';
1059                 } else {
1060                         // All other status is fine
1061                         $OUT .= strtoupper($tar);
1062                 }
1063                 $OUT .= '--}</a></span>|';
1064         } // END - foreach
1065
1066         // Finish navigation link
1067         $OUT = substr($OUT, 0, -1) . ']';
1068
1069         // Return string
1070         return $OUT;
1071 }
1072
1073 // Generate an email link
1074 function generateEmailLink ($email, $table = 'admins') {
1075         // Default email link (INSECURE! Spammer can read this by harvester programs)
1076         $EMAIL = 'mailto:' . $email;
1077
1078         // Check for several extensions
1079         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1080                 // Create email link for contacting admin in guest area
1081                 $EMAIL = generateAdminEmailLink($email);
1082         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1083                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1084                 $EMAIL = generateUserEmailLink($email);
1085         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1086                 // Create email link to contact sponsor within admin area (or like the link above?)
1087                 $EMAIL = generateSponsorEmailLink($email);
1088         }
1089
1090         // Shall I close the link when there is no admin?
1091         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1092
1093         // Return email link
1094         return $EMAIL;
1095 }
1096
1097 // Output error messages in a fasioned way and die...
1098 function app_die ($F, $L, $message) {
1099         // Check if Script is already dieing and not let it kill itself another 1000 times
1100         if (!isset($GLOBALS['app_died'])) {
1101                 // Make sure, that the script realy realy diese here and now
1102                 $GLOBALS['app_died'] = true;
1103
1104                 // Set content type as text/html
1105                 setContentType('text/html');
1106
1107                 // Load header
1108                 loadIncludeOnce('inc/header.php');
1109
1110                 // Rewrite message for output
1111                 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1112
1113                 // Load the message template
1114                 loadTemplate('app_die_message', false, $message);
1115
1116                 // Load footer
1117                 loadIncludeOnce('inc/footer.php');
1118         } else {
1119                 // Script tried to kill itself twice
1120                 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1121         }
1122 }
1123
1124 // Display parsing time and number of SQL queries in footer
1125 function displayParsingTime () {
1126         // Is the timer started?
1127         if (!isset($GLOBALS['startTime'])) {
1128                 // Abort here
1129                 return false;
1130         } // END - if
1131
1132         // Get end time
1133         $endTime = microtime(true);
1134
1135         // "Explode" both times
1136         $start = explode(' ', $GLOBALS['startTime']);
1137         $end = explode(' ', $endTime);
1138         $runTime = $end[0] - $start[0];
1139         if ($runTime < 0) {
1140                 $runTime = '0';
1141         } // END - if
1142
1143         // Prepare output
1144         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1145         $content = array(
1146                 'run_time' => $runTime,
1147                 'sql_time' => (getConfig('sql_time') * 1000),
1148         );
1149
1150         // Load the template
1151         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1152 }
1153
1154 // Output a debug backtrace to the user
1155 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1156         // Is this already called?
1157         if (isset($GLOBALS[__FUNCTION__])) {
1158                 // Other backtrace
1159                 print 'Message:' . $message . '<br />Backtrace:<pre>';
1160                 debug_print_backtrace();
1161                 die('</pre>');
1162         } // END - if
1163
1164         // Set this function as called
1165         $GLOBALS[__FUNCTION__] = true;
1166
1167         // Init message
1168         $debug = '';
1169
1170         // Is the optional message set?
1171         if (!empty($message)) {
1172                 // Use and log it
1173                 $debug = sprintf("Note: %s<br />\n",
1174                         $message
1175                 );
1176
1177                 // @TODO Add a little more infos here
1178                 logDebugMessage($F, $L, strip_tags($message));
1179         } // END - if
1180
1181         // Add output
1182         $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>';
1183         $debug .= debug_get_printable_backtrace();
1184         $debug .= '</pre>';
1185         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1186         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1187
1188         // Send an email? (e.g. not wanted for evaluation errors)
1189         if (($sendEmail === true) && (!isInstallationPhase())) {
1190                 // Prepare content
1191                 $content = array(
1192                         'message'   => trim($message),
1193                         'backtrace' => trim(debug_get_mailable_backtrace())
1194                 );
1195
1196                 // Send email to webmaster
1197                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1198         } // END - if
1199
1200         // And abort here
1201         app_die($F, $L, $debug);
1202 }
1203
1204 // Compile characters which are allowed in URLs
1205 function compileUriCode ($code, $simple = true) {
1206         // Compile constants
1207         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1208
1209         // Compile QUOT and other non-HTML codes
1210         $code = str_replace('{DOT}', '.',
1211                 str_replace('{SLASH}', '/',
1212                 str_replace('{QUOT}', "'",
1213                 str_replace('{DOLLAR}', '$',
1214                 str_replace('{OPEN_ANCHOR}', '(',
1215                 str_replace('{CLOSE_ANCHOR}', ')',
1216                 str_replace('{OPEN_SQR}', '[',
1217                 str_replace('{CLOSE_SQR}', ']',
1218                 str_replace('{PER}', '%',
1219                 $code
1220         )))))))));
1221
1222         // Return compiled code
1223         return $code;
1224 }
1225
1226 // Handle message codes from URL
1227 function handleCodeMessage () {
1228         if (isGetRequestParameterSet('code')) {
1229                 // Default extension is 'unknown'
1230                 $ext = 'unknown';
1231
1232                 // Is extension given?
1233                 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
1234
1235                 // Convert the 'code' parameter from URL to a human-readable message
1236                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1237
1238                 // Load message template
1239                 loadTemplate('message', false, $message);
1240         } // END - if
1241 }
1242
1243 // Generates a 'extension foo inactive' message
1244 function generateExtensionInactiveMessage ($ext_name) {
1245         // Is the extension empty?
1246         if (empty($ext_name)) {
1247                 // This should not happen
1248                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1249         } // END - if
1250
1251         // Default message
1252         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1253
1254         // Is an admin logged in?
1255         if (isAdmin()) {
1256                 // Then output admin message
1257                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1258         } // END - if
1259
1260         // Return prepared message
1261         return $message;
1262 }
1263
1264 // Generates a 'extension foo not installed' message
1265 function generateExtensionNotInstalledMessage ($ext_name) {
1266         // Is the extension empty?
1267         if (empty($ext_name)) {
1268                 // This should not happen
1269                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1270         } // END - if
1271
1272         // Default message
1273         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1274
1275         // Is an admin logged in?
1276         if (isAdmin()) {
1277                 // Then output admin message
1278                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1279         } // END - if
1280
1281         // Return prepared message
1282         return $message;
1283 }
1284
1285 // Generates a message depending on if the extension is not installed or not
1286 // just activated
1287 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1288         // Init message
1289         $message = '';
1290
1291         // Is the extension not installed or just deactivated?
1292         switch (isExtensionInstalled($ext_name)) {
1293                 case true; // Deactivated!
1294                         $message = generateExtensionInactiveMessage($ext_name);
1295                         break;
1296
1297                 case false; // Not installed!
1298                         $message = generateExtensionNotInstalledMessage($ext_name);
1299                         break;
1300
1301                 default: // Should not happen!
1302                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1303                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1304                         break;
1305         } // END - switch
1306
1307         // Return the message
1308         return $message;
1309 }
1310
1311 // Print code with line numbers
1312 function linenumberCode ($code)    {
1313         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1314         $count_lines = count($codeE);
1315
1316         $r = 'Line | Code:<br />';
1317         foreach($codeE as $line => $c) {
1318                 $r .= '<div class="line"><span class="linenum">';
1319                 if ($count_lines == 1) {
1320                         $r .= 1;
1321                 } else {
1322                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
1323                 }
1324                 $r .= '</span>|';
1325
1326                 // Add code
1327                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1328         }
1329
1330         return '<div class="code">' . $r . '</div>';
1331 }
1332
1333 // Determines the right page title
1334 function determinePageTitle () {
1335         // Config and database connection valid?
1336         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1337                 // Init title
1338                 $TITLE = '';
1339
1340                 // Title decoration enabled?
1341                 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1342
1343                 // Do we have some extra title?
1344                 if (isExtraTitleSet()) {
1345                         // Then prepent it
1346                         $TITLE .= getExtraTitle() . ' by ';
1347                 } // END - if
1348
1349                 // Add main title
1350                 $TITLE .= getMainTitle();
1351
1352                 // Add title of module? (middle decoration will also be added!)
1353                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1354                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1355                 } // END - if
1356
1357                 // Add title from what file
1358                 $mode = '';
1359                 if (getModule() == 'login') $mode = 'member';
1360                 elseif (getModule() == 'index') $mode = 'guest';
1361                 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1362
1363                 // Add title decorations? (right)
1364                 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1365
1366                 // Remember title in constant for the template
1367                 $pageTitle = $TITLE;
1368         } elseif ((isInstalled()) && (isAdminRegistered())) {
1369                 // Installed, admin registered but no ext-sql_patches
1370                 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1371         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1372                 // Installed but no admin registered
1373                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1374         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1375                 // Installation mode
1376                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1377         } else {
1378                 // Configuration not found!
1379                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1380
1381                 // Do not add the fatal message in installation mode
1382                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1383         }
1384
1385         // Return title
1386         return decodeEntities($pageTitle);
1387 }
1388
1389 // Checks wethere there is a cache file there. This function is cached.
1390 function isTemplateCached ($template) {
1391         // Do we have cached this result?
1392         if (!isset($GLOBALS['template_cache'][$template])) {
1393                 // Generate FQFN
1394                 $FQFN = generateCacheFqfn($template);
1395
1396                 // Is it there?
1397                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1398         } // END - if
1399
1400         // Return it
1401         return $GLOBALS['template_cache'][$template];
1402 }
1403
1404 // Flushes non-flushed template cache to disk
1405 function flushTemplateCache ($template, $eval) {
1406         // Is this cache flushed?
1407         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1408                 // Generate FQFN
1409                 $FQFN = generateCacheFqfn($template);
1410
1411                 // And flush it
1412                 writeToFile($FQFN, $eval, true);
1413         } // END - if
1414 }
1415
1416 // Reads a template cache
1417 function readTemplateCache ($template) {
1418         // Check it again
1419         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1420                 // This should not happen
1421                 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1422         } // END - if
1423
1424         // Is it cached?
1425         if (!isset($GLOBALS['template_eval'][$template])) {
1426                 // Generate FQFN
1427                 $FQFN = generateCacheFqfn($template);
1428
1429                 // And read from it
1430                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1431         } // END - if
1432
1433         // And return it
1434         return $GLOBALS['template_eval'][$template];
1435 }
1436
1437 // Escapes quotes (default is only double-quotes)
1438 function escapeQuotes ($str, $single = false) {
1439         // Should we escape all?
1440         if ($single === true) {
1441                 // Escape all (including null)
1442                 $str = addslashes($str);
1443         } else {
1444                 // Remove escaping of single quotes
1445                 $str = str_replace("\'", "'", $str);
1446
1447                 // Escape only double-quotes but prevent double-quoting
1448                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1449         }
1450
1451         // Return the escaped string
1452         return $str;
1453 }
1454
1455 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1456 function escapeJavaScriptQuotes ($str) {
1457         // Replace all double-quotes and secure back-ticks
1458         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1459
1460         // Return it
1461         return $str;
1462 }
1463
1464 // Send out mails depending on the 'mod/modes' combination
1465 // @TODO Lame description for this function
1466 function sendModeMails ($mod, $modes) {
1467         // Load hash
1468         if (fetchUserData(getMemberId())) {
1469                 // Extract salt from cookie
1470                 $salt = substr(getSession('u_hash'), 0, -40);
1471
1472                 // Now let's compare passwords
1473                 $hash = encodeHashForCookie(getUserData('password'));
1474
1475                 // Does the hash match or should we change it?
1476                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1477                         // Load the data
1478                         $content = getUserDataArray();
1479
1480                         // Clear/init the content variable
1481                         $content['message'] = '';
1482
1483                         // Which mail?
1484                         // @TODO Move this in a filter
1485                         switch ($mod) {
1486                                 case 'mydata':
1487                                         foreach ($modes as $mode) {
1488                                                 switch ($mode) {
1489                                                         case 'normal': break; // Do not add any special lines
1490                                                         case 'email': // Email was changed!
1491                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1492                                                                 break;
1493
1494                                                         case 'password': // Password was changed
1495                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1496                                                                 break;
1497
1498                                                         default:
1499                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1500                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1501                                                                 break;
1502                                                 } // END - switch
1503                                         } // END - foreach
1504
1505                                         if (isExtensionActive('country')) {
1506                                                 // Replace code with description
1507                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1508                                         } // END - if
1509
1510                                         // Merge content with data from POST
1511                                         $content = merge_array($content, postRequestArray());
1512
1513                                         // Load template
1514                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1515
1516                                         if (isAdminNotificationEnabled()) {
1517                                                 // The admin needs to be notified about a profile change
1518                                                 $message_admin = 'admin_mydata_notify';
1519                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1520                                         } else {
1521                                                 // No mail to admin
1522                                                 $message_admin = '';
1523                                                 $sub_adm   = '';
1524                                         }
1525
1526                                         // Set subject lines
1527                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1528
1529                                         // Output success message
1530                                         $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1531                                         break;
1532
1533                                 default: // Unsupported module!
1534                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1535                                         $content = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1536                                         break;
1537                         } // END - switch
1538                 } else {
1539                         // Passwords mismatch
1540                         $content = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1541                 }
1542         } else {
1543                 // Could not load profile
1544                 $content = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1545         }
1546
1547         // Send email to user if required
1548         if ((!empty($sub_mem)) && (!empty($message))) {
1549                 // Send member mail
1550                 sendEmail($content['email'], $sub_mem, $message);
1551         } // END - if
1552
1553         // Send only if no other error has occured
1554         if (empty($content)) {
1555                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
1556                         // Send admin mail
1557                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1558                 } elseif (isAdminNotificationEnabled()) {
1559                         // Cannot send mails to admin!
1560                         $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
1561                 } else {
1562                         // No mail to admin
1563                         $content = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1564                 }
1565         } // END - if
1566
1567         // Load template
1568         loadTemplate('admin_settings_saved', false, $content);
1569 }
1570
1571 // Generates a 'selection box' from given array
1572 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
1573         // Start the output
1574         $OUT = '<select name="' . $name . '" size="1" class="form_select">
1575 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1576
1577         // Walk through all options
1578         foreach ($options as $option) {
1579                 // Add the <option> entry
1580                 if (empty($optionContent)) {
1581                         // ... from template
1582                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1583                 } else {
1584                         // Direct HTML code
1585                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1586                 }
1587         } // END - foreach
1588
1589         // Finish selection box
1590         $OUT .= '</select>';
1591
1592         // Prepare output
1593         $content = array(
1594                 'selection_box' => $OUT,
1595         );
1596
1597         // Load template and return it
1598         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1599 }
1600
1601 // Prepares the header for HTML output
1602 function loadHtmlHeader () {
1603         // Run two filters:
1604         // 1.) pre_page_header (mainly loads the page_header template and includes
1605         //     meta description)
1606         runFilterChain('pre_page_header');
1607
1608         // Here can be something be added, but normally one of the two filters
1609         // around this line should do the job for you.
1610
1611         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1612         //     to close the head-tag)
1613         // Include more header data here
1614         runFilterChain('post_page_header');
1615 }
1616
1617 // Adds page header and footer to output array element
1618 function addPageHeaderFooter () {
1619         // Init output
1620         $OUT = '';
1621
1622         // Add them all together. This is maybe to simple
1623         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1624                 // Add page part if set
1625                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1626         } // END - foreach
1627
1628         // Transfer $OUT to 'output'
1629         $GLOBALS['output'] = $OUT;
1630 }
1631
1632 // Generates meta description for current module and 'what' value
1633 function generateMetaDescriptionCode () {
1634         // Only include from guest area and if sql_patches has correct version
1635         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1636                 // Construct dynamic description
1637                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1638
1639                 // Output it directly
1640                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1641         } // END - if
1642
1643         // Remove depth
1644         unset($GLOBALS['ref_level']);
1645 }
1646
1647 // Generates an FQFN for template cache from the given template name
1648 function generateCacheFqfn ($template, $mode = 'html') {
1649         // Is this cached?
1650         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1651                 // Generate the FQFN
1652                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1653                         "%s_compiled/%s/%s.tpl.cache",
1654                         getCachePath(),
1655                         $mode,
1656                         $template
1657                 );
1658         } // END - if
1659
1660         // Return it
1661         return $GLOBALS['template_cache_fqfn'][$template];
1662 }
1663
1664 // "Fixes" null or empty string to count of dashes
1665 function fixNullEmptyToDashes ($str, $num) {
1666         // Use str as default
1667         $return = $str;
1668
1669         // Is it empty?
1670         if ((is_null($str)) || (trim($str) == '')) {
1671                 // Set it
1672                 $return = str_repeat('-', $num);
1673         } // END - if
1674
1675         // Return final string
1676         return $return;
1677 }
1678
1679 //-----------------------------------------------------------------------------
1680 //                       Template Helper Functions
1681 //-----------------------------------------------------------------------------
1682
1683 // Color-switch helper function
1684 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1685         // Is it there?
1686         if (!isset($GLOBALS['color_switch'][$template])) {
1687                 // Initialize it
1688                 initTemplateColorSwitch($template);
1689         } elseif ($clear === false) {
1690                 // Switch color if called from loadTemplate()
1691                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1692                 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1693         } // END - if
1694
1695         // Return CSS class name
1696         if ($return === true) {
1697                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1698                 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1699         } // END - if
1700 }
1701
1702 // Helper function for extension registration link
1703 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1704         // Default is all productive
1705         $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>';
1706
1707         // Is the given extension non-productive?
1708         if (!isExtensionProductive($ext_name)) {
1709                 // Non-productive code
1710                 $OUT = '<em style="cursor:help" class="notice" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</em>';
1711         } // END - if
1712
1713         // Return code
1714         return $OUT;
1715 }
1716
1717 // [EOF]
1718 ?>