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