7d5e670a2c2eb9b2c4bb0ed47aa5c6da240476c8
[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                         // It is valid
459                         $content = merge_array($content, getUserDataArray());
460
461                         // But we don't like hashed passwords be mailed
462                         unset($content['password']);
463                 } // END - if
464
465                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
466         } // END - if
467
468         // Base directory
469         $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
470
471         // Detect extra path
472         $extraPath = detectExtraTemplatePath($template);
473
474         // Generate full FQFN
475         $FQFN = $basePath . $extraPath . $template . '.tpl';
476
477         // Does the special template exists?
478         if (!isFileReadable($FQFN)) {
479                 // Reset to default template
480                 $FQFN = $basePath . $template . '.tpl';
481         } // END - if
482
483         // Now does the final template exists?
484         $newContent = '';
485         if (isFileReadable($FQFN)) {
486                 // The local file does exists so we load it. :)
487                 $GLOBALS['tpl_content'][$template] = readFromFile($FQFN);
488
489                 // Run code
490                 $GLOBALS['tpl_content'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'][$template])) . '");';
491                 eval($GLOBALS['tpl_content'][$template]);
492         } elseif (!empty($template)) {
493                 // Template file not found
494                 $newContent = '<div class="para">
495         {--TEMPLATE_404--}: ' . $template . '
496 </div>
497 <div class="para">
498         {--TEMPLATE_CONTENT--}:
499         <pre>' . print_r($content, true) . '</pre>
500         {--TEMPLATE_DATA--}:
501         <pre>' . print_r($DATA, true) . '</pre>
502 </div>';
503
504                 // Debug mode not active? Then remove the HTML tags
505                 if (!isDebugModeEnabled()) {
506                         // Remove HTML tags
507                         $newContent = secureString($newContent);
508                 } // END - if
509         } else {
510                 // No template name supplied!
511                 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
512         }
513
514         // Is there some content?
515         if (empty($newContent)) {
516                 // Compiling failed
517                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'][$template];
518
519                 // Add last error if the required function exists
520                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
521         } // END - if
522
523         // Remove content and data
524         unset($content);
525         unset($DATA);
526
527         // Return content
528         return $newContent;
529 }
530
531 // "Getter" for menu CSS classes, mainly used in templates
532 function getMenuCssClasses ($data) {
533         // $data needs to be converted into an array
534         $content = explode('|', $data);
535
536         // Non-existent index 2 will happen in menu blocks
537         if (!isset($content[2])) $content[2] = '';
538
539         // Re-construct the array: 0=visible,1=locked,2=prefix
540         $content['visible'] = $content[0];
541         $content['locked']  = $content[1];
542
543         // Call our "translator" function
544         $content = translateMenuVisibleLocked($content, $content[2]);
545
546         // Return CSS classes
547         return ($content['visible_css'] . ' ' . $content['locked_css']);
548 }
549
550 // Generate XHTML code for the CAPTCHA
551 function generateCaptchaCode ($code, $type, $type, $userid) {
552         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $type . '&amp;mode=img&amp;code=' . $code . '%}" />';
553 }
554
555 // Compiles the given HTML/mail code
556 function compileCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
557         // Is the code a string or should we not compile?
558         if ((!is_string($code)) || ($compileCode === false)) {
559                 // Silently return it
560                 return $code;
561         } // END - if
562
563         // Start couting
564         $startCompile = microtime(true);
565
566         // Comile the code
567         $code = compileRawCode($code, $simple, $constants, $full);
568
569         // Get timing
570         $compiled = microtime(true);
571
572         // Add timing if enabled
573         if (isTemplateHtml()) {
574                 // Add timing, this should be disabled in
575                 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
576         } // END - if
577
578         // Return compiled code
579         return $code;
580 }
581
582 // Compiles the code (use compileCode() only for HTML because of the comments)
583 // @TODO $simple/$constants are deprecated
584 function compileRawCode ($code, $simple = false, $constants = true, $full = true, $compileCode = true) {
585         // Is the code a string or shall we not compile?
586         if ((!is_string($code)) || ($compileCode === false)) {
587                 // Silently return it
588                 return $code;
589         } // END - if
590
591         // Init replacement-array with smaller set of security characters
592         $secChars = $GLOBALS['url_chars'];
593
594         // Select full set of chars to replace when we e.g. want to compile URLs
595         if ($full === true) {
596                 $secChars = $GLOBALS['security_chars'];
597         } // END - if
598
599         // Compile more through a filter
600         $code = runFilterChain('compile_code', $code);
601
602         // Compile message strings
603         $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
604
605         // Compile QUOT and other non-HTML codes
606         $code = str_replace($secChars['to'], $secChars['from'], $code);
607
608         // Find $content[bla][blub] entries
609         // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
610         preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
611
612         // Are some matches found?
613         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
614                 // Replace all matches
615                 $matchesFound = array();
616                 foreach ($matches[0] as $key => $match) {
617                         // Fuzzy look has failed by default
618                         $fuzzyFound = false;
619
620                         // Fuzzy look on match if already found
621                         foreach ($matchesFound as $found => $set) {
622                                 // Get test part
623                                 $test = substr($found, 0, strlen($match));
624
625                                 // Does this entry exist?
626                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
627                                 if ($test == $match) {
628                                         // Match found
629                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
630                                         $fuzzyFound = true;
631                                         break;
632                                 } // END - if
633                         } // END - foreach
634
635                         // Skip this entry?
636                         if ($fuzzyFound === true) continue;
637
638                         // Take all string elements
639                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
640                                 // Replace it in the code
641                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
642                                 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
643                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
644                                 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
645                                 $matchesFound[$match] = 1;
646                         } elseif (!isset($matchesFound[$match])) {
647                                 // Not yet replaced!
648                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
649                                 $code = str_replace($match, '".' . $match . '."', $code);
650                                 $matchesFound[$match] = 1;
651                         }
652                 } // END - foreach
653         } // END - if
654
655         // Return it
656         return $code;
657 }
658
659 //
660 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
661         $OUT = '';
662
663         if ($type == 'yn') {
664                 // This is a yes/no selection only!
665                 if ($id > 0) $prefix .= '[' . $id . ']';
666                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
667         } else {
668                 // Begin with regular selection box here
669                 if (!empty($prefix)) $prefix .= '_';
670                 $type2 = $type;
671                 if ($id > 0) $type2 .= '[' . $id . ']';
672                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
673         }
674
675         switch ($type) {
676                 case 'day': // Day
677                         for ($idx = 1; $idx < 32; $idx++) {
678                                 $OUT .= '<option value="' . $idx . '"';
679                                 if ($default == $idx) $OUT .= ' selected="selected"';
680                                 $OUT .= '>' . $idx . '</option>';
681                         } // END - for
682                         break;
683
684                 case 'month': // Month
685                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
686                                 $OUT .= '<option value="' . $idx . '"';
687                                 if ($default == $idx) $OUT .= ' selected="selected"';
688                                 $OUT .= '>' . $descr . '</option>';
689                         } // END - for
690                         break;
691
692                 case 'year': // Year
693                         // Get current year
694                         $year = getYear();
695
696                         // Use configured min age or fixed?
697                         if (isExtensionInstalledAndNewer('order', '0.2.1')) {
698                                 // Configured
699                                 $startYear = $year - getConfig('min_age');
700                         } else {
701                                 // Fixed 16 years
702                                 $startYear = $year - 16;
703                         }
704
705                         // Calculate earliest year (100 years old people can still enter Internet???)
706                         $minYear = $year - 100;
707
708                         // Check if the default value is larger than minimum and bigger than actual year
709                         if (($default > $minYear) && ($default >= $year)) {
710                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
711                                         $OUT .= '<option value="' . $idx . '"';
712                                         if ($default == $idx) $OUT .= ' selected="selected"';
713                                         $OUT .= '>' . $idx . '</option>';
714                                 } // END - for
715                         } elseif ($default == -1) {
716                                 // Current year minus 1
717                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
718                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
719                                 } // END - for
720                         } else {
721                                 // Get current year and subtract the configured minimum age
722                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
723                                 // Calculate earliest year depending on extension version
724                                 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
725                                         // Use configured minimum age
726                                         $year = getYear() - getConfig('min_age');
727                                 } else {
728                                         // Use fixed 16 years age
729                                         $year = getYear() - 16;
730                                 }
731
732                                 // Construct year selection list
733                                 for ($idx = $minYear; $idx <= $year; $idx++) {
734                                         $OUT .= '<option value="' . $idx . '"';
735                                         if ($default == $idx) $OUT .= ' selected="selected"';
736                                         $OUT .= '>' . $idx . '</option>';
737                                 } // END - for
738                         }
739                         break;
740
741                 case 'sec':
742                 case 'min':
743                         for ($idx = 0; $idx < 60; $idx+=5) {
744                                 if (strlen($idx) == 1) $idx = '0' . $idx;
745                                 $OUT .= '<option value="' . $idx . '"';
746                                 if ($default == $idx) $OUT .= ' selected="selected"';
747                                 $OUT .= '>' . $idx . '</option>';
748                         } // END - for
749                         break;
750
751                 case 'hour':
752                         for ($idx = 0; $idx < 24; $idx++) {
753                                 if (strlen($idx) == 1) $idx = '0' . $idx;
754                                 $OUT .= '<option value="' . $idx . '"';
755                                 if ($default == $idx) $OUT .= ' selected="selected"';
756                                 $OUT .= '>' . $idx . '</option>';
757                         } // END - for
758                         break;
759
760                 case 'yn':
761                         $OUT .= '<option value="Y"';
762                         if ($default == 'Y') $OUT .= ' selected="selected"';
763                         $OUT .= '>{--YES--}</option><option value="N"';
764                         if ($default != 'Y') $OUT .= ' selected="selected"';
765                         $OUT .= '>{--NO--}</option>';
766                         break;
767         }
768         $OUT .= '</select>';
769         return $OUT;
770 }
771
772 // Insert the code in $img_code into jpeg or PNG image
773 function generateImageOrCode ($img_code, $headerSent = true) {
774         // Is the code size oversized or shouldn't we display it?
775         if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
776                 // Stop execution of function here because of over-sized code length
777                 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getCodeLength());
778         } elseif ($headerSent === false) {
779                 // Return an HTML code here
780                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
781         }
782
783         // Load image
784         $img = sprintf("%s/theme/%s/images/code_bg.%s",
785                 getPath(),
786                 getCurrentTheme(),
787                 getImgType()
788         );
789
790         // Is it readable?
791         if (isFileReadable($img)) {
792                 // Switch image type
793                 switch (getImgType()) {
794                         case 'jpg': // Okay, load image and hide all errors
795                                 $image = imagecreatefromjpeg($img);
796                                 break;
797
798                         case 'png': // Okay, load image and hide all errors
799                                 $image = imagecreatefrompng($img);
800                                 break;
801                 } // END - switch
802         } else {
803                 // Silently log the error
804                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
805                 return;
806         }
807
808         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
809         $text_color = imagecolorallocate($image, 0, 0, 0);
810
811         // Insert code into image
812         imagestring($image, 5, 14, 2, $img_code, $text_color);
813
814         // Return to browser
815         setContentType('image/' . getImgType());
816
817         // Output image with matching image factory
818         switch (getImgType()) {
819                 case 'jpg': imagejpeg($image); break;
820                 case 'png': imagepng($image);  break;
821         } // END - switch
822
823         // Remove image from memory
824         imagedestroy($image);
825 }
826
827 // Create selection box or array of splitted timestamp
828 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
829         // Do not continue if ONE_DAY is absend
830         if (!isConfigEntrySet('ONE_DAY')) {
831                 // And return the timestamp itself or empty array
832                 if ($return_array === true) {
833                         return array();
834                 } else {
835                         return $timestamp;
836                 }
837         } // END - if
838
839         // Calculate 2-seconds timestamp
840         $stamp = round($timestamp);
841         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
842
843         // Do we have a leap year?
844         $SWITCH = '0';
845         $TEST = getYear() / 4;
846         $M1 = getMonth();
847         $M2 = getMonth(time() + $timestamp);
848
849         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
850         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  {
851                 $SWITCH = getOneDay();
852         } // END - switch
853
854         // First of all years...
855         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
856         //* DEBUG: */ debugOutput('Y=' . $Y);
857         // Next months...
858         $M = abs(floor($timestamp / 2628000 - $Y * 12));
859         //* DEBUG: */ debugOutput('M=' . $M);
860         // Next weeks
861         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
862         //* DEBUG: */ debugOutput('W=' . $W);
863         // Next days...
864         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
865         //* DEBUG: */ debugOutput('D=' . $D);
866         // Next hours...
867         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
868         //* DEBUG: */ debugOutput('h=' . $h);
869         // Next minutes..
870         $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));
871         //* DEBUG: */ debugOutput('m=' . $m);
872         // And at last seconds...
873         $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));
874         //* DEBUG: */ debugOutput('s=' . $s);
875
876         // Is seconds zero and time is < 60 seconds?
877         if (($s == '0') && ($timestamp < 60)) {
878                 // Fix seconds
879                 $s = round($timestamp);
880         } // END - if
881
882         //
883         // Now we convert them in seconds...
884         //
885         if ($return_array) {
886                 // Just put all data in an array for later use
887                 $OUT = array(
888                         'YEARS'   => $Y,
889                         'MONTHS'  => $M,
890                         'WEEKS'   => $W,
891                         'DAYS'    => $D,
892                         'HOURS'   => $h,
893                         'MINUTES' => $m,
894                         'SECONDS' => $s
895                 );
896         } else {
897                 // Generate table
898                 $OUT  = '<div align="' . $align . '">';
899                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
900                 $OUT .= '<tr>';
901
902                 if (isInString('Y', $display) || (empty($display))) {
903                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
904                 } // END - if
905
906                 if (isInString('M', $display) || (empty($display))) {
907                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
908                 } // END - if
909
910                 if (isInString('W', $display) || (empty($display))) {
911                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
912                 } // END - if
913
914                 if (isInString('D', $display) || (empty($display))) {
915                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
916                 } // END - if
917
918                 if (isInString('h', $display) || (empty($display))) {
919                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
920                 } // END - if
921
922                 if (isInString('m', $display) || (empty($display))) {
923                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
924                 } // END - if
925
926                 if (isInString('s', $display) || (empty($display))) {
927                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
928                 } // END - if
929
930                 $OUT .= '</tr>';
931                 $OUT .= '<tr>';
932
933                 if (isInString('Y', $display) || (empty($display))) {
934                         // Generate year selection
935                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
936                         for ($idx = 0; $idx <= 10; $idx++) {
937                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
938                                 if ($idx == $Y) $OUT .= ' selected="selected"';
939                                 $OUT .= '>' . $idx . '</option>';
940                         } // END - for
941                         $OUT .= '</select></td>';
942                 } else {
943                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
944                 }
945
946                 if (isInString('M', $display) || (empty($display))) {
947                         // Generate month selection
948                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
949                         for ($idx = 0; $idx <= 11; $idx++) {
950                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
951                                 if ($idx == $M) $OUT .= ' selected="selected"';
952                                 $OUT .= '>' . $idx . '</option>';
953                         } // END - for
954                         $OUT .= '</select></td>';
955                 } else {
956                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
957                 }
958
959                 if (isInString('W', $display) || (empty($display))) {
960                         // Generate week selection
961                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
962                         for ($idx = 0; $idx <= 4; $idx++) {
963                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
964                                 if ($idx == $W) $OUT .= ' selected="selected"';
965                                 $OUT .= '>' . $idx . '</option>';
966                         } // END - for
967                         $OUT .= '</select></td>';
968                 } else {
969                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
970                 }
971
972                 if (isInString('D', $display) || (empty($display))) {
973                         // Generate day selection
974                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
975                         for ($idx = 0; $idx <= 31; $idx++) {
976                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
977                                 if ($idx == $D) $OUT .= ' selected="selected"';
978                                 $OUT .= '>' . $idx . '</option>';
979                         } // END - for
980                         $OUT .= '</select></td>';
981                 } else {
982                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
983                 }
984
985                 if (isInString('h', $display) || (empty($display))) {
986                         // Generate hour selection
987                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
988                         for ($idx = 0; $idx <= 23; $idx++) {
989                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
990                                 if ($idx == $h) $OUT .= ' selected="selected"';
991                                 $OUT .= '>' . $idx . '</option>';
992                         } // END - for
993                         $OUT .= '</select></td>';
994                 } else {
995                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
996                 }
997
998                 if (isInString('m', $display) || (empty($display))) {
999                         // Generate minute selection
1000                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1001                         for ($idx = 0; $idx <= 59; $idx++) {
1002                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1003                                 if ($idx == $m) $OUT .= ' selected="selected"';
1004                                 $OUT .= '>' . $idx . '</option>';
1005                         } // END - for
1006                         $OUT .= '</select></td>';
1007                 } else {
1008                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1009                 }
1010
1011                 if (isInString('s', $display) || (empty($display))) {
1012                         // Generate second selection
1013                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1014                         for ($idx = 0; $idx <= 59; $idx++) {
1015                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1016                                 if ($idx == $s) $OUT .= ' selected="selected"';
1017                                 $OUT .= '>' . $idx . '</option>';
1018                         } // END - for
1019                         $OUT .= '</select></td>';
1020                 } else {
1021                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1022                 }
1023                 $OUT .= '</tr>';
1024                 $OUT .= '</table>';
1025                 $OUT .= '</div>';
1026         }
1027
1028         // Return generated HTML code
1029         return $OUT;
1030 }
1031
1032 // Generate a list of administrative links to a given userid
1033 function generateMemberAdminActionLinks ($userid) {
1034         // Make sure userid is a number
1035         if ($userid != bigintval($userid)) {
1036                 debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
1037         } // END - if
1038
1039         // Define all main targets
1040         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1041
1042         // Get user status
1043         $status = getFetchedUserData('userid', $userid, 'status');
1044
1045         // Begin of navigation links
1046         $OUT = '[';
1047
1048         foreach ($targetArray as $tar) {
1049                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1050                 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
1051                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1052                         // Locked accounts shall be unlocked
1053                         $OUT .= 'UNLOCK_USER';
1054                 } elseif ($tar == 'del_user') {
1055                         // @TODO Deprecate this thing
1056                         $OUT .= 'DELETE_USER';
1057                 } else {
1058                         // All other status is fine
1059                         $OUT .= strtoupper($tar);
1060                 }
1061                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1062                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1063                         // Locked accounts shall be unlocked
1064                         $OUT .= 'UNLOCK_USER';
1065                 } elseif ($tar == 'del_user') {
1066                         // @TODO Deprecate this thing
1067                         $OUT .= 'DELETE_USER';
1068                 } else {
1069                         // All other status is fine
1070                         $OUT .= strtoupper($tar);
1071                 }
1072                 $OUT .= '--}</a></span>|';
1073         } // END - foreach
1074
1075         // Finish navigation link
1076         $OUT = substr($OUT, 0, -1) . ']';
1077
1078         // Return string
1079         return $OUT;
1080 }
1081
1082 // Generate an email link
1083 function generateEmailLink ($email, $table = 'admins') {
1084         // Default email link (INSECURE! Spammer can read this by harvester programs)
1085         $EMAIL = 'mailto:' . $email;
1086
1087         // Check for several extensions
1088         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1089                 // Create email link for contacting admin in guest area
1090                 $EMAIL = generateAdminEmailLink($email);
1091         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1092                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1093                 $EMAIL = generateUserEmailLink($email);
1094         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1095                 // Create email link to contact sponsor within admin area (or like the link above?)
1096                 $EMAIL = generateSponsorEmailLink($email);
1097         }
1098
1099         // Shall I close the link when there is no admin?
1100         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1101
1102         // Return email link
1103         return $EMAIL;
1104 }
1105
1106 // Output error messages in a fasioned way and die...
1107 function app_die ($F, $L, $message) {
1108         // Check if Script is already dieing and not let it kill itself another 1000 times
1109         if (isset($GLOBALS['app_died'])) {
1110                 // Script tried to kill itself twice
1111                 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1112         } // END - if
1113
1114         // Make sure, that the script realy realy diese here and now
1115         $GLOBALS['app_died'] = true;
1116
1117         // Set content type as text/html
1118         setContentType('text/html');
1119
1120         // Load header
1121         loadIncludeOnce('inc/header.php');
1122
1123         // Rewrite message for output
1124         $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
1125
1126         // Load the message template
1127         loadTemplate('app_die_message', false, $message);
1128
1129         // Load footer
1130         loadIncludeOnce('inc/footer.php');
1131 }
1132
1133 // Display parsing time and number of SQL queries in footer
1134 function displayParsingTime () {
1135         // Is the timer started?
1136         if (!isset($GLOBALS['startTime'])) {
1137                 // Abort here
1138                 return false;
1139         } // END - if
1140
1141         // Get end time
1142         $endTime = microtime(true);
1143
1144         // "Explode" both times
1145         $start = explode(' ', $GLOBALS['startTime']);
1146         $end = explode(' ', $endTime);
1147         $runTime = $end[0] - $start[0];
1148         if ($runTime < 0) {
1149                 $runTime = '0';
1150         } // END - if
1151
1152         // Prepare output
1153         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1154         $content = array(
1155                 'run_time' => $runTime,
1156                 'sql_time' => (getConfig('sql_time') * 1000),
1157         );
1158
1159         // Load the template
1160         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
1161 }
1162
1163 // Output a debug backtrace to the user
1164 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
1165         // Is this already called?
1166         if (isset($GLOBALS[__FUNCTION__])) {
1167                 // Other backtrace
1168                 print 'Message:' . $message . '<br />Backtrace:<pre>';
1169                 debug_print_backtrace();
1170                 die('</pre>');
1171         } // END - if
1172
1173         // Set this function as called
1174         $GLOBALS[__FUNCTION__] = true;
1175
1176         // Init message
1177         $debug = '';
1178
1179         // Is the optional message set?
1180         if (!empty($message)) {
1181                 // Use and log it
1182                 $debug = sprintf("Note: %s<br />\n",
1183                         $message
1184                 );
1185
1186                 // @TODO Add a little more infos here
1187                 logDebugMessage($F, $L, strip_tags($message));
1188         } // END - if
1189
1190         // Add output
1191         $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>';
1192         $debug .= debug_get_printable_backtrace();
1193         $debug .= '</pre>';
1194         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1195         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1196
1197         // Send an email? (e.g. not wanted for evaluation errors)
1198         if (($sendEmail === true) && (!isInstallationPhase())) {
1199                 // Prepare content
1200                 $content = array(
1201                         'message'   => trim($message),
1202                         'backtrace' => trim(debug_get_mailable_backtrace())
1203                 );
1204
1205                 // Send email to webmaster
1206                 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1207         } // END - if
1208
1209         // And abort here
1210         app_die($F, $L, $debug);
1211 }
1212
1213 // Compile characters which are allowed in URLs
1214 function compileUriCode ($code, $simple = true) {
1215         // Compile constants
1216         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
1217
1218         // Compile QUOT and other non-HTML codes
1219         $code = str_replace('{DOT}', '.',
1220                 str_replace('{SLASH}', '/',
1221                 str_replace('{QUOT}', "'",
1222                 str_replace('{DOLLAR}', '$',
1223                 str_replace('{OPEN_ANCHOR}', '(',
1224                 str_replace('{CLOSE_ANCHOR}', ')',
1225                 str_replace('{OPEN_SQR}', '[',
1226                 str_replace('{CLOSE_SQR}', ']',
1227                 str_replace('{PER}', '%',
1228                 $code
1229         )))))))));
1230
1231         // Return compiled code
1232         return $code;
1233 }
1234
1235 // Handle message codes from URL
1236 function handleCodeMessage () {
1237         if (isGetRequestParameterSet('code')) {
1238                 // Default extension is 'unknown'
1239                 $ext = 'unknown';
1240
1241                 // Is extension given?
1242                 if (isGetRequestParameterSet('ext')) {
1243                         $ext = getRequestParameter('ext');
1244                 } // END - if
1245
1246                 // Convert the 'code' parameter from URL to a human-readable message
1247                 $message = getMessageFromErrorCode(getRequestParameter('code'));
1248
1249                 // Load message template
1250                 loadTemplate('message', false, $message);
1251         } // END - if
1252 }
1253
1254 // Generates a 'extension foo out-dated' message
1255 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1256         // Is the extension empty?
1257         if (empty($ext_name)) {
1258                 // This should not happen
1259                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1260         } // END - if
1261
1262         // Default message
1263         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_OUTDATED', $ext_name);
1264
1265         // Is an admin logged in?
1266         if (isAdmin()) {
1267                 // Then output admin message
1268                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1269         } // END - if
1270
1271         // Return prepared message
1272         return $message;
1273 }
1274
1275 // Generates a 'extension foo inactive' message
1276 function generateExtensionInactiveMessage ($ext_name) {
1277         // Is the extension empty?
1278         if (empty($ext_name)) {
1279                 // This should not happen
1280                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1281         } // END - if
1282
1283         // Default message
1284         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1285
1286         // Is an admin logged in?
1287         if (isAdmin()) {
1288                 // Then output admin message
1289                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE', $ext_name);
1290         } // END - if
1291
1292         // Return prepared message
1293         return $message;
1294 }
1295
1296 // Generates a 'extension foo not installed' message
1297 function generateExtensionNotInstalledMessage ($ext_name) {
1298         // Is the extension empty?
1299         if (empty($ext_name)) {
1300                 // This should not happen
1301                 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1302         } // END - if
1303
1304         // Default message
1305         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1306
1307         // Is an admin logged in?
1308         if (isAdmin()) {
1309                 // Then output admin message
1310                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
1311         } // END - if
1312
1313         // Return prepared message
1314         return $message;
1315 }
1316
1317 // Generates a message depending on if the extension is not installed or not
1318 // just activated
1319 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1320         // Init message
1321         $message = '';
1322
1323         // Is the extension not installed or just deactivated?
1324         switch (isExtensionInstalled($ext_name)) {
1325                 case true; // Deactivated!
1326                         $message = generateExtensionInactiveMessage($ext_name);
1327                         break;
1328
1329                 case false; // Not installed!
1330                         $message = generateExtensionNotInstalledMessage($ext_name);
1331                         break;
1332
1333                 default: // Should not happen!
1334                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1335                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1336                         break;
1337         } // END - switch
1338
1339         // Return the message
1340         return $message;
1341 }
1342
1343 // Print code with line numbers
1344 function linenumberCode ($code)    {
1345         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
1346         $count_lines = count($codeE);
1347
1348         $r = 'Line | Code:<br />';
1349         foreach ($codeE as $line => $c) {
1350                 $r .= '<div class="line"><span class="linenum">';
1351                 if ($count_lines == 1) {
1352                         $r .= 1;
1353                 } else {
1354                         $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1355                 }
1356                 $r .= '</span>|';
1357
1358                 // Add code
1359                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1360         } // END - foreach
1361
1362         return '<div class="code">' . $r . '</div>';
1363 }
1364
1365 // Determines the right page title
1366 function determinePageTitle () {
1367         // Config and database connection valid?
1368         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1369                 // Init title
1370                 $TITLE = '';
1371
1372                 // Title decoration enabled?
1373                 if ((isTitleDecorationEnabled()) && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
1374
1375                 // Do we have some extra title?
1376                 if (isExtraTitleSet()) {
1377                         // Then prepent it
1378                         $TITLE .= getExtraTitle() . ' by ';
1379                 } // END - if
1380
1381                 // Add main title
1382                 $TITLE .= getMainTitle();
1383
1384                 // Add title of module? (middle decoration will also be added!)
1385                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1386                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1387                 } // END - if
1388
1389                 // Add title from what file
1390                 $mode = '';
1391                 if (getModule() == 'login') $mode = 'member';
1392                 elseif (getModule() == 'index') $mode = 'guest';
1393                 if ((!empty($mode)) && (isWhatTitleEnabled())) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
1394
1395                 // Add title decorations? (right)
1396                 if ((isTitleDecorationEnabled()) && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
1397
1398                 // Remember title in constant for the template
1399                 $pageTitle = $TITLE;
1400         } elseif ((isInstalled()) && (isAdminRegistered())) {
1401                 // Installed, admin registered but no ext-sql_patches
1402                 $pageTitle = '[-- ' . getMainTitle() . ' - ' . getModuleTitle(getModule()) . ' --]';
1403         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1404                 // Installed but no admin registered
1405                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1406         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1407                 // Installation mode
1408                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1409         } else {
1410                 // Configuration not found
1411                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1412
1413                 // Do not add the fatal message in installation mode
1414                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
1415         }
1416
1417         // Return title
1418         return decodeEntities($pageTitle);
1419 }
1420
1421 // Checks wethere there is a cache file there. This function is cached.
1422 function isTemplateCached ($template) {
1423         // Do we have cached this result?
1424         if (!isset($GLOBALS['template_cache'][$template])) {
1425                 // Generate FQFN
1426                 $FQFN = generateCacheFqfn($template);
1427
1428                 // Is it there?
1429                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
1430         } // END - if
1431
1432         // Return it
1433         return $GLOBALS['template_cache'][$template];
1434 }
1435
1436 // Flushes non-flushed template cache to disk
1437 function flushTemplateCache ($template, $eval) {
1438         // Is this cache flushed?
1439         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
1440                 // Generate FQFN
1441                 $FQFN = generateCacheFqfn($template);
1442
1443                 // And flush it
1444                 writeToFile($FQFN, $eval, true);
1445         } // END - if
1446 }
1447
1448 // Reads a template cache
1449 function readTemplateCache ($template) {
1450         // Check it again
1451         if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
1452                 // This should not happen
1453                 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1454         } // END - if
1455
1456         // Is it cached?
1457         if (!isset($GLOBALS['template_eval'][$template])) {
1458                 // Generate FQFN
1459                 $FQFN = generateCacheFqfn($template);
1460
1461                 // And read from it
1462                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
1463         } // END - if
1464
1465         // And return it
1466         return $GLOBALS['template_eval'][$template];
1467 }
1468
1469 // Escapes quotes (default is only double-quotes)
1470 function escapeQuotes ($str, $single = false) {
1471         // Should we escape all?
1472         if ($single === true) {
1473                 // Escape all (including null)
1474                 $str = addslashes($str);
1475         } else {
1476                 // Remove escaping of single quotes
1477                 $str = str_replace("\\'", "'", $str);
1478
1479                 // Escape only double-quotes but prevent double-quoting
1480                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
1481         }
1482
1483         // Return the escaped string
1484         return $str;
1485 }
1486
1487 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1488 function escapeJavaScriptQuotes ($str) {
1489         // Replace all double-quotes and secure back-ticks
1490         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
1491
1492         // Return it
1493         return $str;
1494 }
1495
1496 // Send out mails depending on the 'mod/modes' combination
1497 // @TODO Lame description for this function
1498 function sendModeMails ($mod, $modes) {
1499         // Init user data
1500         $content = array ();
1501
1502         // Load hash
1503         if (fetchUserData(getMemberId())) {
1504                 // Extract salt from cookie
1505                 $salt = substr(getSession('u_hash'), 0, -40);
1506
1507                 // Now let's compare passwords
1508                 $hash = encodeHashForCookie(getUserData('password'));
1509
1510                 // Does the hash match or should we change it?
1511                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
1512                         // Load the data
1513                         $content = getUserDataArray();
1514
1515                         // Clear/init the content variable
1516                         $content['message'] = '';
1517
1518                         // Which mail?
1519                         // @TODO Move this in a filter
1520                         switch ($mod) {
1521                                 case 'mydata':
1522                                         foreach ($modes as $mode) {
1523                                                 switch ($mode) {
1524                                                         case 'normal': break; // Do not add any special lines
1525                                                         case 'email': // Email was changed!
1526                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
1527                                                                 break;
1528
1529                                                         case 'password': // Password was changed
1530                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
1531                                                                 break;
1532
1533                                                         default:
1534                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1535                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1536                                                                 break;
1537                                                 } // END - switch
1538                                         } // END - foreach
1539
1540                                         if (isExtensionActive('country')) {
1541                                                 // Replace code with description
1542                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
1543                                         } // END - if
1544
1545                                         // Merge content with data from POST
1546                                         $content = merge_array($content, postRequestArray());
1547
1548                                         // Load template
1549                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1550
1551                                         if (isAdminNotificationEnabled()) {
1552                                                 // The admin needs to be notified about a profile change
1553                                                 $message_admin = 'admin_mydata_notify';
1554                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1555                                         } else {
1556                                                 // No mail to admin
1557                                                 $message_admin = '';
1558                                                 $sub_adm   = '';
1559                                         }
1560
1561                                         // Set subject lines
1562                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1563
1564                                         // Output success message
1565                                         $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1566                                         break;
1567
1568                                 default: // Unsupported module!
1569                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1570                                         $content['message'] = '<span class="notice">{--UNKNOWN_MODULE--}</span>';
1571                                         break;
1572                         } // END - switch
1573                 } else {
1574                         // Passwords mismatch
1575                         $content['message'] = '<span class="notice">{--MEMBER_PASSWORD_ERROR--}</span>';
1576                 }
1577         } else {
1578                 // Could not load profile
1579                 $content['message'] = '<span class="notice">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1580         }
1581
1582         // Send email to user if required
1583         if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['email']))) {
1584                 // Send member mail
1585                 sendEmail($content['email'], $sub_mem, $message);
1586         } // END - if
1587
1588         // Send only if no other error has occured
1589         if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1590                 // Send admin mail
1591                 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1592         } elseif (isAdminNotificationEnabled()) {
1593                 // Cannot send mails to admin!
1594                 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1595         } else {
1596                 // No mail to admin
1597                 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1598         }
1599
1600         // Load template
1601         displayMessage($content['message']);
1602 }
1603
1604 // Generates a 'selection box' from given array
1605 function generateSelectionBoxFromArray (array $options, $name, $optionValue, $optionContent = '', $extraName = '') {
1606         // Start the output
1607         $OUT = '<select name="' . $name . '" size="1" class="form_select">
1608 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1609
1610         // Walk through all options
1611         foreach ($options as $option) {
1612                 // Add the <option> entry from ...
1613                 if (empty($optionContent)) {
1614                         // ... template
1615                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
1616                 } else {
1617                         // ... direct HTML code
1618                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
1619                 }
1620         } // END - foreach
1621
1622         // Finish selection box
1623         $OUT .= '</select>';
1624
1625         // Prepare output
1626         $content = array(
1627                 'selection_box' => $OUT,
1628         );
1629
1630         // Load template and return it
1631         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
1632 }
1633
1634 // Prepares the header for HTML output
1635 function loadHtmlHeader () {
1636         // Run two filters:
1637         // 1.) pre_page_header (mainly loads the page_header template and includes
1638         //     meta description)
1639         runFilterChain('pre_page_header');
1640
1641         // Here can be something be added, but normally one of the two filters
1642         // around this line should do the job for you.
1643
1644         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1645         //     to close the head-tag)
1646         // Include more header data here
1647         runFilterChain('post_page_header');
1648 }
1649
1650 // Adds page header and footer to output array element
1651 function addPageHeaderFooter () {
1652         // Init output
1653         $OUT = '';
1654
1655         // Add them all together. This is maybe to simple
1656         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
1657                 // Add page part if set
1658                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
1659         } // END - foreach
1660
1661         // Transfer $OUT to 'output'
1662         $GLOBALS['output'] = $OUT;
1663 }
1664
1665 // Generates meta description for current module and 'what' value
1666 function generateMetaDescriptionCode () {
1667         // Only include from guest area and if sql_patches has correct version
1668         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1669                 // Construct dynamic description
1670                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
1671
1672                 // Output it directly
1673                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
1674         } // END - if
1675
1676         // Remove depth
1677         unset($GLOBALS['ref_level']);
1678 }
1679
1680 // Generates an FQFN for template cache from the given template name
1681 function generateCacheFqfn ($template, $mode = 'html') {
1682         // Is this cached?
1683         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
1684                 // Generate the FQFN
1685                 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
1686                         "%s_compiled/%s/%s.tpl.cache",
1687                         getCachePath(),
1688                         $mode,
1689                         $template
1690                 );
1691         } // END - if
1692
1693         // Return it
1694         return $GLOBALS['template_cache_fqfn'][$template];
1695 }
1696
1697 // "Fixes" null or empty string to count of dashes
1698 function fixNullEmptyToDashes ($str, $num) {
1699         // Use str as default
1700         $return = $str;
1701
1702         // Is it empty?
1703         if ((is_null($str)) || (trim($str) == '')) {
1704                 // Set it
1705                 $return = str_repeat('-', $num);
1706         } // END - if
1707
1708         // Return final string
1709         return $return;
1710 }
1711
1712 // Translates the "pool type" into human-readable
1713 function translatePoolType ($type) {
1714         // Return "translation"
1715         return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1716 }
1717
1718 // Displays given message in admin_settings_saved template
1719 function displayMessage ($message, $return = false) {
1720         // Load the template
1721         return loadTemplate('admin_settings_saved', $return, $message);
1722 }
1723
1724 // Generates a selection box for (maybe) given gender
1725 function generateGenderSelectionBox ($selectedGender = '') {
1726         // Start the HTML code
1727         $out  = '<select name="gender" size="1" class="form_select">';
1728
1729         // Add the options
1730         $out .= generateOptionList('/ARRAY/', array('M', 'F', 'C'), array('{--GENDER_M--}', '{--GENDER_F--}', '{--GENDER_C--}'), $selectedGender);
1731
1732         // Finish HTML code
1733         $out .= '</select>';
1734
1735         // Return the code
1736         return $out;
1737 }
1738
1739 //-----------------------------------------------------------------------------
1740 //                      Template helper functions for EL
1741 //-----------------------------------------------------------------------------
1742
1743 // Color-switch helper function
1744 function doTemplateColorSwitch ($template, $clear = false, $return = true) {
1745         // Is it there?
1746         if (!isset($GLOBALS['color_switch'][$template])) {
1747                 // Initialize it
1748                 initTemplateColorSwitch($template);
1749         } elseif ($clear === false) {
1750                 // Switch color if called from loadTemplate()
1751                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $template);
1752                 $GLOBALS['color_switch'][$template] = 3 - $GLOBALS['color_switch'][$template];
1753         }
1754
1755         // Return CSS class name
1756         if ($return === true) {
1757                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $template . '=' . $GLOBALS['color_switch'][$template]);
1758                 return 'switch_sw' . $GLOBALS['color_switch'][$template];
1759         } // END - if
1760 }
1761
1762 // Helper function for extension registration link
1763 function doTemplateExtensionRegistrationLink ($template, $dummy, $ext_name) {
1764         // Default is all non-productive
1765         $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>';
1766
1767         // Is the given extension non-productive?
1768         if (isExtensionProductive($ext_name)) {
1769                 // Productive code
1770                 $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>';
1771         } // END - if
1772
1773         // Return code
1774         return $OUT;
1775 }
1776
1777 // Helper function to create bonus mail admin links
1778 function doTemplateAdminBonusMailLinks ($template, $bonusId) {
1779         // Call the inner function
1780         return generateAdminMailLinks('bid', $bonusId);
1781 }
1782
1783 // Helper function to create member mail admin links
1784 function doTemplateAdminMemberMailLinks ($template, $mailId) {
1785         // Call the inner function
1786         return generateAdminMailLinks('mid', $mailId);
1787 }
1788
1789 // [EOF]
1790 ?>