Renamed all SQL-related functions to camel-case notation
[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 - 2013 by Mailer Developer Team                   *
20  * For more information visit: http://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, $full = TRUE) {
45         return compileCode($code, $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 whether 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         // Call inner function
74         $str = fixNullEmptyToDashes($str, 3);
75
76         // Return string
77         return $str;
78 }
79
80 // Init color switch
81 function initTemplateColorSwitch ($template) {
82         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
83         $GLOBALS['color_switch'][$template] = 2;
84 }
85
86 // "Getter" for color switch code
87 function getColorSwitchCode ($template) {
88         // Prepare the code
89         $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', FALSE, FALSE) . {DQUOTE}";
90
91         // And return it
92         return $code;
93 }
94
95 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
96 function outputHtml ($htmlCode = NULL, $newLine = TRUE) {
97         // Init output
98         if (!isset($GLOBALS['__output'])) {
99                 $GLOBALS['__output'] = '';
100         } // END - if
101
102         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getOutputMode()=' . getOutputMode() . ',htmlCode(length)=' . strlen($htmlCode) . ',output(length)=' . strlen($GLOBALS['__output']));
103         // Is there HTML-Code here?
104         if ((!is_null($htmlCode)) && (!empty($htmlCode))) {
105                 // Yes, so we handle it as you have configured
106                 switch (getOutputMode()) {
107                         case 'render':
108                                 // But if PHP is caching, then we don't need to do that
109                                 if (getPhpCaching() == 'on') {
110                                         // Output into PHP's internal buffer
111                                         outputRawCode($htmlCode);
112
113                                         // That's why you don't need any \n at the end of your HTML code... :-)
114                                         if ($newLine === TRUE) {
115                                                 outputRawCode(PHP_EOL);
116                                         } // END - if
117                                 } else {
118                                         // Render mode for old or lame servers...
119                                         $GLOBALS['__output'] .= $htmlCode;
120
121                                         // That's why you don't need any \n at the end of your HTML code... :-)
122                                         if ($newLine === TRUE) {
123                                                 $GLOBALS['__output'] .= PHP_EOL;
124                                         } // END - if
125                                 }
126                                 break;
127
128                         case 'direct':
129                                 // If we are switching from 'render' to 'direct' mode, all data in '__output' must be flushed and cleared
130                                 if ((!empty($GLOBALS['__output'])) && (getPhpCaching() != 'on')) {
131                                         outputRawCode($GLOBALS['__output']);
132                                         $GLOBALS['__output'] = '';
133                                 } // END - if
134
135                                 // The same as above... ^
136                                 outputRawCode($htmlCode);
137                                 if ($newLine === TRUE) {
138                                         outputRawCode(PHP_EOL);
139                                 } // END - if
140                                 break;
141
142                         default:
143                                 // Huh, something goes wrong or maybe you have edited config.php ???
144                                 reportBug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
145                                 break;
146                 } // END - switch
147         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['http_header'])) || (count($GLOBALS['http_header']) == 0)) && (!isRawOutputMode())) {
148                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getPhpCaching()=' . getPhpCaching() . ',isset(http_header)=' . intval(isset($GLOBALS['http_header'])) . ',getScriptOutputMode()=' . getScriptOutputMode() . '');
149                 // Output cached HTML code
150                 $GLOBALS['__output'] = ob_get_contents();
151
152                 // Clear output buffer for later output if output is found
153                 if (!empty($GLOBALS['__output'])) {
154                         clearOutputBuffer();
155                 } // END - if
156
157                 // Send all HTTP headers
158                 sendHttpHeaders();
159
160                 // Compile and run finished rendered HTML code
161                 compileFinalOutput();
162
163                 // Output code here, DO NOT REMOVE! ;-)
164                 outputRawCode($GLOBALS['__output']);
165         } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['__output'])) && (!isRawOutputMode())) {
166                 // Send all HTTP headers
167                 sendHttpHeaders();
168
169                 // Compile and run finished rendered HTML code
170                 compileFinalOutput();
171
172                 // Output code here, DO NOT REMOVE! ;-)
173                 outputRawCode($GLOBALS['__output']);
174         } else {
175                 // And flush all headers
176                 flushHttpHeaders();
177         }
178 }
179
180 // Compiles the final output
181 function compileFinalOutput () {
182         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ',getScriptOutputMode()=' . getScriptOutputMode() . ' - ENTERED!');
183         // Is this function called?
184         if (isset($GLOBALS[__FUNCTION__])) {
185                 // Abort here
186                 reportBug(__FUNCTION__, __LINE__, 'Double call of ' . __FUNCTION__ . ' causes problems with sent headers.');
187         } // END - if
188
189         // Mark this function as called
190         $GLOBALS[__FUNCTION__] = TRUE;
191
192         // Add page header and footer
193         addPageHeaderFooter();
194         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ' - After addPageHeaderFooter() call.');
195
196         // Do the final (general) compilation
197         $GLOBALS['__output'] = doFinalCompilation($GLOBALS['__output']);
198
199         // Compile any other things out
200         $GLOBALS['__output'] = compileUriCode($GLOBALS['__output']);
201
202         // Extension 'rewrite' installed?
203         if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
204                 $GLOBALS['__output'] = rewriteLinksInCode($GLOBALS['__output']);
205         } // END - if
206
207         // Compress it?
208         /**
209          * @TODO On some pages this is buggy
210         if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
211                 // Compress it for HTTP gzip
212                 $GLOBALS['__output'] = gzencode($GLOBALS['__output'], 9);
213
214                 // Add header
215                 addHttpHeader('Content-Encoding: gzip');
216         } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
217                 // Compress it for HTTP deflate
218                 $GLOBALS['__output'] = gzcompress($GLOBALS['__output'], 9);
219
220                 // Add header
221                 addHttpHeader('Content-Encoding: deflate');
222         }
223         */
224
225         // Add final length
226         addHttpHeader('Content-Length: ' . strlen($GLOBALS['__output']));
227
228         // Flush all headers
229         flushHttpHeaders();
230 }
231
232 // Main compilation loop
233 function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE) {
234         // Insert comments? (Only valid with HTML templates, of course)
235         enableTemplateHtml($insertComments);
236
237         // Init counter
238         $totalCompilations = 0;
239
240         // Compile all out
241         while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($totalCompilations < 7)) {
242                 // Init common variables
243                 $content = array();
244                 $newContent = '';
245
246                 // Compile it
247                 //* DEBUG: */ debugOutput('<pre>'.lineNumberCode($code).'</pre>');
248                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), $enableCodes)) . '";';
249                 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.lineNumberCode($eval).'</pre>');
250                 eval($eval);
251                 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.lineNumberCode($newContent).'</pre>');
252                 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
253
254                 // Was that eval okay?
255                 if (empty($newContent)) {
256                         // Something went wrong!
257                         reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . lineNumberCode($eval) . '</pre>', FALSE);
258                 } // END - if
259
260                 // Use it again
261                 $code = $newContent;
262
263                 // Compile the final code if insertComments is true
264                 if ($insertComments == TRUE) {
265                         // ... because SQL queries shall keep OPEN_CONFIG and such in
266                         $code = compileRawCode($code);
267                 } // END - if
268
269                 // Count round
270                 $totalCompilations++;
271         } // END - while
272
273         // Add debugging data in HTML code, if mode is enabled
274         if ((isDebugModeEnabled()) && ($insertComments === TRUE) && (isHtmlOutputMode())) {
275                 // Add loop count
276                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isDebugModeEnabled()=' . intval(isDebugModeEnabled()) . ',insertComments=' . intval($insertComments) . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()));
277                 $code .= '<!-- Total compilation loop=' . $totalCompilations . ' //-->';
278         } // END - if
279
280         // Return the compiled code
281         return $code;
282 }
283
284 // Output the raw HTML code
285 function outputRawCode ($htmlCode) {
286         // Output stripped HTML code to avoid broken JavaScript code, etc.
287         print(str_replace('{BACK}', chr(92), $htmlCode));
288
289         // Flush the output if only getPhpCaching() is not 'on'
290         if (getPhpCaching() != 'on') {
291                 // Flush it
292                 flush();
293         } // END - if
294 }
295
296 // Load a template file and return it's content (only it's name; do not use ' or ")
297 function loadTemplate ($template, $return = FALSE, $content = array(), $compileCode = TRUE) {
298         // @TODO Remove these sanity checks if all is fine
299         if (!is_bool($return)) {
300                 // $return has to be boolean
301                 reportBug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
302         } elseif (!is_string($template)) {
303                 // $template has to be string
304                 reportBug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
305         }
306
307         // Init returned content
308         $ret = '';
309
310         // Set current template
311         $GLOBALS['current_template'] = $template;
312
313         // Is there cache?
314         if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('html', $template))) {
315                 // Evaluate the cache
316                 $templateContent = readTemplateCache('html', $template, $content);
317
318                 // Better remove array element which is only needed in uncached mode
319                 unset($GLOBALS['template_eval']['html'][$template]);
320         } elseif (!isset($GLOBALS['template_eval']['html'][$template])) {
321                 // Make all template names lowercase
322                 $template = strtolower($template);
323
324                 // Base directory
325                 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
326                 $extraPath = detectExtraTemplatePath('html', $template);
327
328                 // Generate FQFN
329                 $FQFN = $basePath . $extraPath . $template . '.tpl';
330                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Template ' . $template . ' is solved to FQFN=' . $FQFN);
331
332                 // Does the special template exists?
333                 if (!isFileReadable($FQFN)) {
334                         // Reset to default template
335                         $FQFN = $basePath . $template . '.tpl';
336                 } // END - if
337
338                 // Now does the final template exists?
339                 if (isFileReadable($FQFN)) {
340                         // Count the template load
341                         incrementConfigEntry('num_templates');
342
343                         // The local file does exists so we load it. :)
344                         $GLOBALS['template_content']['html'][$template] = readFromFile($FQFN);
345
346                         // Is there to compile the code?
347                         if ((isInString('$', $GLOBALS['template_content']['html'][$template])) || (isInString('{--', $GLOBALS['template_content']['html'][$template])) || (isInString('{?', $GLOBALS['template_content']['html'][$template])) || (isInString('{%', $GLOBALS['template_content']['html'][$template]))) {
348                                 // Normal HTML output?
349                                 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
350                                         // Add surrounding HTML comments to help finding bugs faster
351                                         $code = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
352
353                                         // Prepare eval() command
354                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
355                                         $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($code), TRUE, $compileCode) . '";';
356                                 } elseif (substr($template, 0, 3) == 'js_') {
357                                         // JavaScripts don't like entities, dollar signs and timings
358                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
359                                         $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
360                                 } elseif (isAjaxOutputMode()) {
361                                         // AJAX (JSON content)
362                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
363                                         $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '";';
364                                 } else {
365                                         // Prepare eval() command, other output doesn't like entities, maybe
366                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
367                                         $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
368                                 }
369                         } elseif (isHtmlOutputMode()) {
370                                 // Add surrounding HTML comments to help finding bugs faster
371                                 $templateContent = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
372                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
373                                 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($templateContent), TRUE, $compileCode) . '";';
374                         } elseif (isAjaxOutputMode()) {
375                                 // AJAX (JSON content)
376                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
377                                 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '";';
378                         } else {
379                                 // JavaScript again
380                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
381                                 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
382                         } // END - if
383                 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
384                         // Only admins shall see this warning or when installation mode is active
385                         $templateContent = '<div class="para">
386         {--TEMPLATE_404--}
387 </div>
388 <div class="para">
389         (' . $template . ')
390 </div>
391 <div class="para">
392         {--TEMPLATE_CONTENT--}:
393         <pre>' . print_r($content, TRUE) . '</pre>
394 </div>';
395                 } else {
396                         // No file!
397                         $GLOBALS['template_eval']['html'][$template] = '404';
398                 }
399         }
400
401         // Code set?
402         if ((isset($GLOBALS['template_eval']['html'][$template])) && ($GLOBALS['template_eval']['html'][$template] != '404')) {
403                 // Eval the code
404                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
405                 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['html'][$template]).'</pre>');
406                 eval($GLOBALS['template_eval']['html'][$template]);
407                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
408         } // END - if
409
410         // Is there some content to output or return?
411         if ((empty($templateContent)) && (isDebugModeEnabled())) {
412                 // Warning, empty output!
413                 return 'E:' . $template . ',content=<pre>' . print_r($content, TRUE) . '</pre>';
414         } // END - if
415
416         // Not empty so let's put it out! ;)
417         if ($return === TRUE) {
418                 // Return the HTML code
419                 return $templateContent;
420         } else {
421                 // Output directly
422                 outputHtml($templateContent);
423         }
424 }
425
426 // Detects the extra template path from given template name
427 function detectExtraTemplatePath ($prefix, $template) {
428         // Default is empty
429         $extraPath = '';
430
431         // Is there cache?
432         if (!isset($GLOBALS['extra_path'][$prefix][$template])) {
433                 // Check for admin/guest/member/etc. templates
434                 if (substr($template, 0, 6) == 'admin_') {
435                         // Admin template found
436                         $extraPath = 'admin/';
437                 } elseif (substr($template, 0, 6) == 'guest_') {
438                         // Guest template found
439                         $extraPath = 'guest/';
440                 } elseif (substr($template, 0, 7) == 'member_') {
441                         // Member template found
442                         $extraPath = 'member/';
443                 } elseif (substr($template, 0, 7) == 'select_') {
444                         // Selection template found
445                         $extraPath = 'select/';
446                 } elseif (substr($template, 0, 8) == 'install_') {
447                         // Installation template found
448                         $extraPath = 'install/';
449                 } elseif (substr($template, 0, 4) == 'ext_') {
450                         // Extension template found
451                         $extraPath = 'ext/';
452                 } elseif (substr($template, 0, 3) == 'la_') {
453                         // 'Logical-area' template found
454                         $extraPath = 'la/';
455                 } elseif (substr($template, 0, 3) == 'js_') {
456                         // JavaScript template found
457                         $extraPath = 'js/';
458                 } elseif (substr($template, 0, 5) == 'menu_') {
459                         // Menu template found
460                         $extraPath = 'menu/';
461                 } else {
462                         // Test for extension
463                         $test = substr($template, 0, strpos($template, '_'));
464
465                         // Probe for valid extension name
466                         if (isExtensionNameValid($test)) {
467                                 // Set extra path to extension's name
468                                 $extraPath = $test . '/';
469                         } // END - if
470                 }
471
472                 // Store it in cache
473                 $GLOBALS['extra_path'][$prefix][$template] = $extraPath;
474         } // END - if
475
476         // Return result
477         return $GLOBALS['extra_path'][$prefix][$template];
478 }
479
480 // Loads an email template and compiles it
481 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = TRUE) {
482         // Make sure all template names are lowercase!
483         $template = strtolower($template);
484
485         // Set current template
486         $GLOBALS['current_template'] = $template;
487
488         // Is content an array?
489         if (is_array($content)) {
490                 // Add expiration to array
491                 if ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
492                         // Will never expire!
493                         $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
494                 } elseif ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge'))) {
495                         // Create nice date string
496                         $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
497                 } else {
498                         // Missing entry
499                         $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
500                 }
501         } // END - if
502
503         // Is there cache?
504         if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('email', $template))) {
505                 // Evaluate the cache
506                 $templateContent = readTemplateCache('email', $template, $content);
507
508                 // Better remove array element which is need only in uncached mode
509                 unset($GLOBALS['template_eval']['email'][$template]);
510         } elseif (!isset($GLOBALS['template_eval']['email'][$template])) {
511                 // Base directory
512                 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
513
514                 // Detect extra path
515                 $extraPath = detectExtraTemplatePath('email', $template);
516
517                 // Generate full FQFN
518                 $FQFN = $basePath . $extraPath . $template . '.tpl';
519
520                 // Does the special template exists?
521                 if (!isFileReadable($FQFN)) {
522                         // Reset to default template
523                         $FQFN = $basePath . $template . '.tpl';
524                 } // END - if
525
526                 // Now does the final template exists?
527                 $templateContent = '';
528                 if (isFileReadable($FQFN)) {
529                         // The local file does exists so we load it. :)
530                         $GLOBALS['template_content']['email'][$template] = readFromFile($FQFN);
531
532                         // Run code
533                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
534                         $GLOBALS['template_eval']['email'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['email'][$template])) . '");';
535                 } elseif (!empty($template)) {
536                         // Template file not found
537                         $templateContent = '<div class="para">
538         {--TEMPLATE_404--}: ' . $template . '
539 </div>
540 <div class="para">
541         {--TEMPLATE_CONTENT--}:
542         <pre>' . print_r($content, TRUE) . '</pre>
543 </div>';
544
545                         // Don't cache this, as there is no template to cache
546                         $GLOBALS['template_eval']['email'][$template] = '404';
547
548                         // Debug mode not active? Then remove the HTML tags
549                         if (!isDebugModeEnabled()) {
550                                 // Remove HTML tags
551                                 $templateContent = secureString($templateContent);
552                         } // END - if
553                 } else {
554                         // No template name supplied!
555                         $templateContent = '{--NO_TEMPLATE_SUPPLIED--}';
556                         $GLOBALS['template_eval']['email'][$template] = '404';
557                 }
558         }
559
560         // Is there something to eval?
561         if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
562                 // Eval the code
563                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
564                 //* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
565                 eval($GLOBALS['template_eval']['email'][$template]);
566                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
567         } // END - if
568
569         // Are there some content?
570         if (empty($templateContent)) {
571                 // Compiling failed
572                 $templateContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
573
574                 // Add last error if the required function exists
575                 if (function_exists('error_get_last')) {
576                         // Add last error and some lines for better overview
577                         $templateContent .= "\n--------------------------------------\nDebug:\n" . print_r(error_get_last(), TRUE) . "--------------------------------------\nPlease don't alter these informations!\nThanx.";
578                 } // END - if
579         } // END - if
580
581         // Remove content and data
582         unset($content);
583
584         // Return content
585         return $templateContent;
586 }
587
588 // "Getter" for menu CSS classes, mainly used in templates
589 function getMenuCssClasses ($data) {
590         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
591
592         // Is there cache?
593         if (!isset($GLOBALS[__FUNCTION__][$data])) {
594                 // $data needs to be converted into an array
595                 $content = explode('|', $data);
596
597                 // Non-existent index 2 will happen in menu blocks
598                 if (!isset($content[2])) {
599                         $content[2] = '';
600                 } // END - if
601
602                 // Re-construct the array: 0=visible,1=locked,2=prefix
603                 $content['visible'] = $content[0];
604                 $content['locked']  = $content[1];
605
606                 // Call our "translator" function
607                 $content = translateMenuVisibleLocked($content, $content[2]);
608
609                 // Set it in cache
610                 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
611         } // END - if
612
613         // Return cache
614         return $GLOBALS[__FUNCTION__][$data];
615 }
616
617 // Generate XHTML code for the CAPTCHA
618 function generateCaptchaCode ($code, $type, $urlId, $userid) {
619         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&amp;' . $type . '=' . $urlId . '&amp;do=img&amp;code=' . $code . '%}" />';
620 }
621
622 // Compiles the given HTML/mail code
623 function compileCode ($code, $full = TRUE, $compileCode = TRUE) {
624         // Is the code a string or should we not compile?
625         if ((!is_string($code)) || ($compileCode === FALSE)) {
626                 // Silently return it
627                 return $code;
628         } // END - if
629
630         // Start couting
631         $startCompile = microtime(TRUE);
632
633         // Comile the code
634         $code = compileRawCode($code, $full, $compileCode);
635
636         // Get timing
637         $compilationTime = $startCompile - microtime(TRUE);
638
639         // Add timing if enabled
640         if (isTemplateHtml()) {
641                 // Add timing, this should be disabled in
642                 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
643         } // END - if
644
645         // Return compiled code
646         return $code;
647 }
648
649 // Compiles the code
650 function compileRawCode ($code, $full = TRUE, $compileCode = TRUE) {
651         // Is the code a string or shall we not compile?
652         if ((!is_string($code)) || ($compileCode === FALSE)) {
653                 // Silently return it
654                 return $code;
655         } // END - if
656
657         // Init replacement-array with smaller set of security characters
658         $secChars = $GLOBALS['url_chars'];
659
660         // Select full set of chars to replace when we e.g. want to compile URLs
661         if ($full === TRUE) {
662                 $secChars = $GLOBALS['security_chars'];
663         } // END - if
664
665         // Compile more through a filter
666         $code = runFilterChain('compile_code', $code);
667
668         // First compile these chars
669         array_unshift($secChars['to']  , '{--'       , '--}');
670         array_unshift($secChars['from'], '{%message,', '%}' );
671
672         // Compile QUOT and other non-HTML codes
673         $code = str_replace($secChars['to'], $secChars['from'], $code);
674
675         // Find $content[bla][blub] entries
676         preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
677         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
678
679         // Are some matches found?
680         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
681                 // Replace all matches
682                 $matchesFound = array();
683                 foreach ($matches[0] as $key => $match) {
684                         // Fuzzy look has failed by default
685                         $fuzzyFound = FALSE;
686
687                         // Fuzzy look on match if already found
688                         foreach ($matchesFound as $found => $set) {
689                                 // Get test part
690                                 $test = substr($found, 0, strlen($match));
691
692                                 // Does this entry exist?
693                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
694                                 if ($test == $match) {
695                                         // Match found
696                                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
697                                         $fuzzyFound = TRUE;
698                                         break;
699                                 } // END - if
700                         } // END - foreach
701
702                         // Skip this entry?
703                         if ($fuzzyFound === TRUE) {
704                                 continue;
705                         } // END - if
706
707                         // Take all string elements
708                         if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
709                                 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
710                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
711                                 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
712                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
713                                 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
714                                 $matchesFound[$match] = TRUE;
715                         } elseif (!isset($matchesFound[$match])) {
716                                 // Not yet replaced!
717                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
718                                 $code = str_replace($match, '".' . $match . '."', $code);
719                                 $matchesFound[$match] = 1;
720                         } else {
721                                 // Everthing else should be a least logged
722                                 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
723                         }
724                 } // END - foreach
725         } // END - if
726
727         /*
728          * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
729          * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
730          * therefore the variable's value won't be inserted. This is why
731          * {COMPILE_DOLLAR} is being used in above loop and at the end of this
732          * function being replace with the original dollar sign again.
733          */
734         preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
735
736         // Are some matches found?
737         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
738                 // Scan all matches for not $content
739                 foreach ($matches[0] as $match) {
740                         // Trim match
741                         $match = trim($match);
742
743                         // Debug message
744                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
745
746                         // Is the first part not $content/$userid and not empty?
747                         // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
748                         if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
749                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
750                                 // Then replace $ with {DOLLAR}
751                                 $matchSecured = str_replace('$', '{DOLLAR}', $match);
752
753                                 // And in $code as well
754                                 $code = str_replace($match, $matchSecured, $code);
755                         } // END - if
756                 } // END - if
757         } // END - if
758
759         // Replace {COMPILE_DOLLAR} back to dollar sign
760         $code = str_replace('{COMPILE_DOLLAR}', '$', $code);
761
762         // Finally return it
763         return $code;
764 }
765
766 //
767 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select') {
768         $OUT = '';
769
770         if ($type == 'yn') {
771                 // This is a yes/no selection only!
772                 if (isValidId($id)) $prefix .= '[' . $id . ']';
773                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
774         } else {
775                 // Begin with regular selection box here
776                 if (!empty($prefix)) $prefix .= '_';
777                 $type2 = $type;
778                 if (isValidId($id)) $type2 .= '[' . $id . ']';
779                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
780         }
781
782         switch ($type) {
783                 case 'ye': // Years
784                         // Get current year
785                         $year = getYear();
786
787                         // Use configured min age or fixed?
788                         if (isExtensionInstalledAndNewer('other', '0.2.1')) {
789                                 // Configured
790                                 $startYear = $year - getMinAge();
791                         } else {
792                                 // Fixed 16 years
793                                 $startYear = $year - 16;
794                         }
795
796                         // Calculate earliest year (100 years old people can still enter Internet???)
797                         $minYear = $year - 100;
798
799                         // Check if the default value is larger than minimum and bigger than actual year
800                         if (($default > $minYear) && ($default >= $year)) {
801                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
802                                         $OUT .= '<option value="' . $idx . '"';
803                                         if ($default == $idx) $OUT .= ' selected="selected"';
804                                         $OUT .= '>' . $idx . '</option>';
805                                 } // END - for
806                         } elseif ($default == -1) {
807                                 // Current year minus 1
808                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
809                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
810                                 } // END - for
811                         } else {
812                                 // Get current year and subtract the configured minimum age
813                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
814
815                                 // Construct year selection list
816                                 for ($idx = $minYear; $idx <= $startYear; $idx++) {
817                                         $OUT .= '<option value="' . $idx . '"';
818                                         if ($default == $idx) $OUT .= ' selected="selected"';
819                                         $OUT .= '>' . $idx . '</option>';
820                                 } // END - for
821                         }
822                         break;
823
824                 case 'mo': // Months
825                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
826                                 $OUT .= '<option value="' . $idx . '"';
827                                 if ($default == $idx) $OUT .= ' selected="selected"';
828                                 $OUT .= '>' . $descr . '</option>';
829                         } // END - for
830                         break;
831
832                 case 'mn': // Months, numeric
833                         for ($idx = 0; $idx <= 12; $idx++) {
834                                 $OUT .= '<option value="' . $idx . '"';
835                                 if ($default == $idx) $OUT .= ' selected="selected"';
836                                 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
837                         } // END - for
838                         break;
839
840                 case 'we': // Weeks
841                         for ($idx = 0; $idx <= 4; $idx++) {
842                                 $OUT .= '  <option value="' . $idx . '"';
843                                 if ($default == $idx) $OUT .= ' selected="selected"';
844                                 $OUT .= '>' . $idx . '</option>';
845                         } // END - for
846                         break;
847
848                 case 'da': // Days
849                         for ($idx = 0; $idx <= 31; $idx++) {
850                                 $OUT .= '<option value="' . $idx . '"';
851                                 if ($default == $idx) $OUT .= ' selected="selected"';
852                                 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
853                         } // END - for
854                         break;
855
856                 case 'ho': // Hours
857                         for ($idx = 0; $idx <= 23; $idx++) {
858                                 if (strlen($idx) == 1) $idx = 0 . $idx;
859                                 $OUT .= '<option value="' . $idx . '"';
860                                 if ($default == $idx) $OUT .= ' selected="selected"';
861                                 $OUT .= '>' . $idx . '</option>';
862                         } // END - for
863                         break;
864
865                 case 'mi': // Minutes
866                 case 'se': // Seconds
867                         for ($idx = 0; $idx <= 59; $idx+=5) {
868                                 if (strlen($idx) == 1) $idx = 0 . $idx;
869                                 $OUT .= '<option value="' . $idx . '"';
870                                 if ($default == $idx) $OUT .= ' selected="selected"';
871                                 $OUT .= '>' . $idx . '</option>';
872                         } // END - for
873                         break;
874
875                 case 'yn': // Yes/No
876                         $OUT .= '<option value="Y"';
877                         if ($default == 'Y') $OUT .= ' selected="selected"';
878                         $OUT .= '>{--YES--}</option><option value="N"';
879                         if ($default != 'Y') $OUT .= ' selected="selected"';
880                         $OUT .= '>{--NO--}</option>';
881                         break;
882
883                 default: // Not detected
884                         reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' .  $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
885                         break;
886         }
887         $OUT .= '</select>';
888         return $OUT;
889 }
890
891 // Insert the code in $img_code into jpeg or PNG image
892 function generateImageOrCode ($img_code, $headerSent = TRUE) {
893         // Is the code size oversized or shouldn't we display it?
894         if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
895                 // Stop execution of function here because of over-sized code length
896                 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
897         } elseif ($headerSent === FALSE) {
898                 // Return an HTML code here
899                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
900         }
901
902         // Load image
903         $img = sprintf("%s/theme/%s/images/code_bg.%s",
904                 getPath(),
905                 getCurrentTheme(),
906                 getImgType()
907         );
908
909         // Is it readable?
910         if (isFileReadable($img)) {
911                 // Switch image type
912                 switch (getImgType()) {
913                         case 'jpg': // Okay, load image and hide all errors
914                                 $image = imagecreatefromjpeg($img);
915                                 break;
916
917                         case 'png': // Okay, load image and hide all errors
918                                 $image = imagecreatefrompng($img);
919                                 break;
920                 } // END - switch
921         } else {
922                 // Silently log the error
923                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
924                 return;
925         }
926
927         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
928         $text_color = imagecolorallocate($image, 0, 0, 0);
929
930         // Insert code into image
931         imagestring($image, 5, 14, 2, $img_code, $text_color);
932
933         // Return to browser
934         setContentType('image/' . getImgType());
935
936         // Output image with matching image factory
937         switch (getImgType()) {
938                 case 'jpg': imagejpeg($image); break;
939                 case 'png': imagepng($image);  break;
940         } // END - switch
941
942         // Remove image from memory
943         imagedestroy($image);
944 }
945
946 // Create selection box or array of splitted timestamp
947 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE) {
948         // Do not continue if ONE_DAY is absend
949         if (!isConfigEntrySet('ONE_DAY')) {
950                 // Abort here
951                 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
952         } // END - if
953
954         // Calculate 2-seconds timestamp
955         $stamp = round($timestamp);
956         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
957
958         // Is there a leap year?
959         $SWITCH = '0';
960         $TEST = getYear() / 4;
961         $M1 = getMonth();
962         $M2 = getMonth(time() + $timestamp);
963
964         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
965         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  {
966                 $SWITCH = getOneDay();
967         } // END - switch
968
969         // First of all years...
970         $year = abs(floor($timestamp / (31536000 + $SWITCH)));
971         //* DEBUG: */ debugOutput('year=' . $year);
972         // Next months...
973         $month = abs(floor($timestamp / 2628000 - $year * 12));
974         //* DEBUG: */ debugOutput('month=' . $month);
975         // Next weeks
976         $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
977         //* DEBUG: */ debugOutput('week=' . $week);
978         // Next days...
979         $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
980         //* DEBUG: */ debugOutput('day=' . $day);
981         // Next hours...
982         $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
983         //* DEBUG: */ debugOutput('hour=' . $hour);
984         // Next minutes..
985         $minute = abs(floor($timestamp / 60 - $year * (365 + $SWITCH / getOneDay()) * 24 * 60 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24 * 60) - $week * 7 * 24 * 60 - $day * 24 * 60 - $hour * 60));
986         //* DEBUG: */ debugOutput('minute=' . $minute);
987         // And at last seconds...
988         $second = abs(floor($timestamp - $year * (365 + $SWITCH / getOneDay()) * 24 * 3600 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24 * 3600) - $week * 7 * 24 * 3600 - $day * 24 * 3600 - $hour * 3600 - $minute * 60));
989         //* DEBUG: */ debugOutput('second=' . $second);
990
991         // Is seconds zero and time is < 60 seconds?
992         if (($second < 1) && ($timestamp < 60)) {
993                 // Fix seconds
994                 $second = round($timestamp);
995         } // END - if
996
997         // Put all calculated values in array
998         $data = array(
999                 'Y' => $year,
1000                 'M' => $month,
1001                 'W' => $week,
1002                 'D' => $day,
1003                 'h' => $hour,
1004                 'm' => $minute,
1005                 's' => $second
1006         );
1007
1008         //
1009         // Now we convert them in seconds...
1010         //
1011         if ($asArray === TRUE) {
1012                 // Just put data array out
1013                 $OUT = $data;
1014         } else {
1015                 // Init array
1016                 $units = array(
1017                         // Time unit -> field name
1018                         'unit_field' => array(
1019                                 'Y' => 'ye',
1020                                 'M' => 'mn',
1021                                 'W' => 'we',
1022                                 'D' => 'da',
1023                                 'h' => 'ho',
1024                                 'm' => 'mi',
1025                                 's' => 'se'
1026                         ),
1027                         // Time unit -> label
1028                         'unit_label' => array(
1029                                 'Y' => 'YEAR',
1030                                 'M' => 'MONTH',
1031                                 'W' => 'WEEK',
1032                                 'D' => 'DAY',
1033                                 'h' => 'HOUR',
1034                                 'm' => 'MINUTE',
1035                                 's' => 'SECOND'
1036                         )
1037                 );
1038
1039                 // Generate table
1040                 $OUT  = '<div align="' . $align . '">';
1041                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1042                 $OUT .= '<tr>';
1043
1044                 // "Walk" through all units
1045                 foreach ($units['unit_field'] as $unit => $field) {
1046                         // Is this displayed or zero?
1047                         if (isInString($unit, $display) || (empty($display))) {
1048                                 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1049                                 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1050                         } // END - if
1051                 } // END - foreach
1052
1053                 // Close table row and open new one
1054                 $OUT .= '</tr>';
1055                 $OUT .= '<tr>';
1056
1057                 // "Walk" through all units again
1058                 foreach ($units['unit_field'] as $unit => $field) {
1059                         // Is this used?
1060                         if (isInString($unit, $display) || (empty($display))) {
1061                                 // Generate year selection
1062                                 $OUT .= '<td align="center">';
1063                                 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select');
1064                                 $OUT .= '</td>';
1065                         } else {
1066                                 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1067                         }
1068                 } // END - foreach
1069
1070                 // Close all tags
1071                 $OUT .= '</tr>';
1072                 $OUT .= '</table>';
1073                 $OUT .= '</div>';
1074         }
1075
1076         // Return generated HTML code or data array
1077         return $OUT;
1078 }
1079
1080 // Generate a list of administrative links to a given userid
1081 function generateMemberAdminActionLinks ($userid) {
1082         // Make sure userid is a number
1083         if ($userid != bigintval($userid)) {
1084                 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1085         } // END - if
1086
1087         // Define all main targets
1088         $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1089
1090         // Get user status
1091         $status = getFetchedUserData('userid', $userid, 'status');
1092
1093         // Begin of navigation links
1094         $OUT = '[';
1095
1096         foreach ($targetArray as $target) {
1097                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $target . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1098                 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1099                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1100                         // Locked accounts shall be unlocked
1101                         $OUT .= 'UNLOCK_USER';
1102                 } elseif ($target == 'del_user') {
1103                         // @TODO Deprecate this thing
1104                         $OUT .= 'DELETE_USER';
1105                 } else {
1106                         // All other status is fine
1107                         $OUT .= strtoupper($target);
1108                 }
1109                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1110                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1111                         // Locked accounts shall be unlocked
1112                         $OUT .= 'UNLOCK_USER';
1113                 } elseif ($target == 'del_user') {
1114                         // @TODO Deprecate this thing
1115                         $OUT .= 'DELETE_USER';
1116                 } else {
1117                         // All other status is fine
1118                         $OUT .= strtoupper($target);
1119                 }
1120                 $OUT .= '--}</a></span>|';
1121         } // END - foreach
1122
1123         // Add special link, in case of the account is unconfirmed
1124         if ($status == 'UNCONFIRMED') {
1125                 // Add it
1126                 $OUT .= '<span class="admin_user_link"><a target="_blank" title="{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT_TITLE--}" href="{%url=confirm.php?hash=' . getFetchedUserData('userid', $userid, 'user_hash') . '%}">{--ADMIN_USER_ACTION_LINK_CONFIRM_ACCOUNT--}</a></span>|';
1127         } // END - if
1128
1129         // Finish navigation link
1130         $OUT = substr($OUT, 0, -1) . ']';
1131
1132         // Return string
1133         return $OUT;
1134 }
1135
1136 // Generate an email link
1137 function generateEmailLink ($email, $table = 'admins') {
1138         // Default email link (INSECURE! Spammer can read this by harvester programs)
1139         $EMAIL = 'mailto:' . $email;
1140
1141         // Check for several extensions
1142         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1143                 // Create email link for contacting admin in guest area
1144                 $EMAIL = generateAdminEmailLink($email);
1145         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1146                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1147                 $EMAIL = generateUserEmailLink($email);
1148         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1149                 // Create email link to contact sponsor within admin area (or like the link above?)
1150                 $EMAIL = generateSponsorEmailLink($email);
1151         }
1152
1153         // Return email link
1154         return $EMAIL;
1155 }
1156
1157 /**
1158  * Outputs an error message in a "fashioned way" to the user, by putting it into
1159  * a nice looking web page, if one of HTML or CSS output mode is active.
1160  *
1161  * Please use reportBug() instead of this function. reportBug() has more helpful
1162  * functionality like logging and admin notification (which you can configure
1163  * through your admin area).
1164  *
1165  * @param       $F                      Function or file basename where the error came from
1166  * @param       $L                      Line number where the error came from
1167  * @param       $message        Message which shall be output to web
1168  * @return      void
1169  */
1170 function app_exit ($F, $L, $message) {
1171         // Check if Script is already dieing and not let it kill itself another 1000 times
1172         if (isset($GLOBALS['app_died'])) {
1173                 // Script tried to kill itself twice
1174                 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1175         } // END - if
1176
1177         // Make sure, that the script realy realy diese here and now
1178         $GLOBALS['app_died'] = TRUE;
1179
1180         // Is this AJAX mode?
1181         if (isAjaxOutputMode()) {
1182                 // Set content type as application/json
1183                 setContentType('application/json');
1184         } else {
1185                 // Set content type as text/html
1186                 setContentType('text/html');
1187         }
1188
1189         // Load header
1190         loadIncludeOnce('inc/header.php');
1191
1192         // Rewrite message for output
1193         $message = sprintf(
1194                 getMessage('MAILER_HAS_DIED'),
1195                 basename($F),
1196                 $L,
1197                 $message
1198         );
1199
1200         // Is this AJAX mode again
1201         if (isAjaxOutputMode()) {
1202                 // Load the message template
1203                 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1204
1205                 // Output it as JSON encoded
1206                 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation($OUT)))));
1207         } else {
1208                 // Load the message template
1209                 loadTemplate('app_exit_message', FALSE, $message);
1210         }
1211
1212         // Load footer
1213         loadIncludeOnce('inc/footer.php');
1214 }
1215
1216 // Display parsing time and number of SQL queries in footer
1217 function displayParsingTime () {
1218         // Is the timer started?
1219         if (!isset($GLOBALS['__start_time'])) {
1220                 // Abort here
1221                 return FALSE;
1222         } // END - if
1223
1224         // Get end time
1225         $endTime = microtime(TRUE);
1226
1227         // "Explode" both times
1228         $start = explode(' ', $GLOBALS['__start_time']);
1229         $end = explode(' ', $endTime);
1230         $runTime = $end[0] - $start[0];
1231         if ($runTime < 0) {
1232                 $runTime = '0';
1233         } // END - if
1234
1235         // Prepare output
1236         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1237         $content = array(
1238                 'run_time' => $runTime,
1239                 'sql_time' => (getConfig('sql_time') * 1000),
1240         );
1241
1242         // Load the template
1243         $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1244
1245         // Is debug enabled?
1246         if (isDebugModeEnabled()) {
1247                 // Log loading of total includes
1248                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
1249         } // END - if
1250 }
1251
1252 /**
1253  * Outputs an error message and backtrace to the user, by default a mail with
1254  * all relevant data is being mailed to the configured administrators.
1255  *
1256  * This function shall be used "publicly" because of logging, admin notification
1257  * and double-call prevention (see first if() block) instead of app_exit().
1258  * app_exit() is more a "private" function and will only output a bug message to
1259  * the user, no email and no logging.
1260  *
1261  * @param       $F                      Function or file basename where the error came from
1262  * @param       $L                      Line number where the error came from
1263  * @param       $sendEmail      Wether to send an email to all configured administrators
1264  * @return      void
1265  */
1266 function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
1267         // Is this already called?
1268         if (isset($GLOBALS[__FUNCTION__])) {
1269                 // Other backtrace
1270                 print '[' . $F . ':' . $L . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
1271                 debug_print_backtrace();
1272                 die('</pre>');
1273         } // END - if
1274
1275         // Set HTTP status to 500 (e.g. for AJAX requests)
1276         setHttpStatus('500 Internal Server Error');
1277
1278         // Mark this function as called
1279         $GLOBALS[__FUNCTION__] = TRUE;
1280
1281         // Init message
1282         $debug = '';
1283
1284         // Is the optional message set?
1285         if (!empty($message)) {
1286                 // Use and log it
1287                 $debug = sprintf("Note: %s<br />\n",
1288                         $message
1289                 );
1290
1291                 // @TODO Add a little more infos here
1292                 logDebugMessage($F, $L, strip_tags($message));
1293         } // END - if
1294
1295         // Add output
1296         $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 this whole message + logfile from <strong>' . str_replace(getPath(), '', getCachePath()) . 'debug.log</strong> in your report (you can now attach files).<br />Backtrace:<pre>';
1297         $debug .= debug_get_printable_backtrace();
1298         $debug .= '</pre>';
1299         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1300         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1301
1302         // Send an email? (e.g. not wanted for evaluation errors)
1303         if (($sendEmail === TRUE) && (!isInstallationPhase())) {
1304                 // Prepare content
1305                 $content = array(
1306                         'message'   => trim($message),
1307                         'backtrace' => trim(debug_get_mailable_backtrace())
1308                 );
1309
1310                 // Send email to webmaster
1311                 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1312         } // END - if
1313
1314         // Is there HTML/CSS/AJAX mode?
1315         if (((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode())) && (isDebugModeEnabled())) {
1316                 // And abort here
1317                 app_exit($F, $L, $debug);
1318         } else {
1319                 // Raw/image output mode and all other modes doesn't work well with text ...
1320                 die();
1321         }
1322 }
1323
1324 // Compile characters which are allowed in URLs
1325 function compileUriCode ($code, $simple = TRUE) {
1326         // Trim code
1327         $test = trim($code);
1328
1329         // Is it empty?
1330         if (empty($test)) {
1331                 // Then abort here and return the original code
1332                 return $code;
1333         } // END - if
1334
1335         // Compile these by default
1336         $charsCompile = array(
1337                 'from' => array(
1338                         '{DOT}',
1339                         '{SLASH}',
1340                         '{QUOT}',
1341                         '{DOLLAR}',
1342                         '{OPEN_ANCHOR}',
1343                         '{CLOSE_ANCHOR}',
1344                         '{OPEN_SQR}',
1345                         '{CLOSE_SQR}',
1346                         '{PER}'
1347                 ),
1348                 'to' => array(
1349                         '.',
1350                         '/',
1351                         chr(39),
1352                         '$',
1353                         '(',
1354                         ')',
1355                         '[',
1356                         ']',
1357                         '%'
1358                 )
1359         );
1360
1361         // Compile constants
1362         if ($simple === FALSE) {
1363                 // Add more 'from'
1364                 array_unshift($charsCompile['from'], '{--', '--}');
1365
1366                 // Add more 'to'
1367                 array_unshift($charsCompile['to'], '".', '."');
1368         } // END - if
1369
1370         // Compile QUOT and other non-HTML codes
1371         $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1372         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1373
1374         // Return compiled code
1375         return $code;
1376 }
1377
1378 // Handle message codes from URL
1379 function handleCodeMessage () {
1380         // Is 'code' set?
1381         if (isGetRequestElementSet('code')) {
1382                 // Default extension is 'unknown'
1383                 $ext = 'unknown';
1384
1385                 // Is extension given?
1386                 if (isGetRequestElementSet('ext')) {
1387                         $ext = getRequestElement('ext');
1388                 } // END - if
1389
1390                 // Convert the 'code' parameter from URL to a human-readable message
1391                 $message = getMessageFromErrorCode(getRequestElement('code'));
1392
1393                 // Load message template
1394                 loadTemplate('message', FALSE, $message);
1395         } // END - if
1396 }
1397
1398 // Generates a 'extension foo out-dated' message
1399 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1400         // Is the extension empty?
1401         if (empty($ext_name)) {
1402                 // This should not happen
1403                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1404         } // END - if
1405
1406         // Default message
1407         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1408
1409         // Is an admin logged in?
1410         if (isAdmin()) {
1411                 // Then output admin message
1412                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1413         } // END - if
1414
1415         // Return prepared message
1416         return $message;
1417 }
1418
1419 // Generates a 'extension foo inactive' message
1420 function generateExtensionInactiveMessage ($ext_name) {
1421         // Is the extension empty?
1422         if (empty($ext_name)) {
1423                 // This should not happen
1424                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1425         } // END - if
1426
1427         // Default message
1428         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1429
1430         // Is an admin logged in?
1431         if (isAdmin()) {
1432                 // Then output admin message
1433                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1434         } // END - if
1435
1436         // Return prepared message
1437         return $message;
1438 }
1439
1440 // Generates a 'extension foo not installed' message
1441 function generateExtensionNotInstalledMessage ($ext_name) {
1442         // Is the extension empty?
1443         if (empty($ext_name)) {
1444                 // This should not happen
1445                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1446         } // END - if
1447
1448         // Default message
1449         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1450
1451         // Is an admin logged in?
1452         if (isAdmin()) {
1453                 // Then output admin message
1454                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1455         } // END - if
1456
1457         // Return prepared message
1458         return $message;
1459 }
1460
1461 // Generates a message depending on if the extension is not installed or not
1462 // just activated
1463 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1464         // Init message
1465         $message = '';
1466
1467         // Is the extension not installed or just deactivated?
1468         switch (isExtensionInstalled($ext_name)) {
1469                 case TRUE; // Deactivated!
1470                         $message = generateExtensionInactiveMessage($ext_name);
1471                         break;
1472
1473                 case FALSE; // Not installed!
1474                         $message = generateExtensionNotInstalledMessage($ext_name);
1475                         break;
1476
1477                 default: // Should not happen!
1478                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1479                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1480                         break;
1481         } // END - switch
1482
1483         // Return the message
1484         return $message;
1485 }
1486
1487 // Print code with line numbers
1488 function lineNumberCode ($code)    {
1489         // By default copy the code
1490         $codeE = $code;
1491
1492         if (!is_array($code)) {
1493                 // We need an array, so try it with the new-line character
1494                 $codeE = explode(PHP_EOL, $code);
1495         } // END - if
1496
1497         $count_lines = count($codeE);
1498
1499         $r = 'Line | Code:<br />';
1500         foreach ($codeE as $line => $c) {
1501                 $r .= '<div class="line"><span class="linenum">';
1502                 if ($count_lines == 1) {
1503                         $r .= 1;
1504                 } else {
1505                         $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1506                 }
1507                 $r .= '</span>|';
1508
1509                 // Add code
1510                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1511         } // END - foreach
1512
1513         return '<div class="code">' . $r . '</div>';
1514 }
1515
1516 // Determines the right page title
1517 function determinePageTitle () {
1518         // Init page title
1519         $pageTitle = '';
1520
1521         // Config and database connection valid?
1522         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1523                 // Title decoration enabled?
1524                 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1525                         $pageTitle .= '{%config,trim=title_left%} ';
1526                 } // END - if
1527
1528                 // Is there an extra title?
1529                 if (isExtraTitleSet()) {
1530                         // Then prepend it
1531                         $pageTitle .= '{%pipe,getExtraTitle%} by ';
1532                 } // END - if
1533
1534                 // Add main title
1535                 $pageTitle .= '{?MAIN_TITLE?}';
1536
1537                 // Add title of module? (middle decoration will also be added!)
1538                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1539                         $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1540                 } // END - if
1541
1542                 // Get menu mode from module
1543                 $menuMode = getMenuModeFromModule();
1544
1545                 // Add middle part (always in admin area!)
1546                 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1547                         $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1548                 } // END - if
1549
1550                 // Add title decorations? (right)
1551                 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1552                         $pageTitle .= ' {%config,trim=title_right%}';
1553                 } // END - if
1554         } elseif ((isInstalled()) && (isAdminRegistered())) {
1555                 // Installed, admin registered but no ext-sql_patches
1556                 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1557         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1558                 // Installed but no admin registered
1559                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1560         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1561                 // Installation mode
1562                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1563         } else {
1564                 // Configuration not found
1565                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1566
1567                 // Do not add the fatal message in installation mode
1568                 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1569                         // Please report this
1570                         reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1571                 } // END - if
1572         }
1573
1574         // Return title
1575         return decodeEntities($pageTitle);
1576 }
1577
1578 // Checks whethere there is a cache file there. This function is cached.
1579 function isTemplateCached ($prefix, $template) {
1580         // Is there cached this result?
1581         if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1582                 // Generate FQFN
1583                 $FQFN = generateCacheFqfn($prefix, $template);
1584
1585                 // Is it there?
1586                 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1587         } // END - if
1588
1589         // Return it
1590         return $GLOBALS['template_cache'][$prefix][$template];
1591 }
1592
1593 // Flushes non-flushed template cache to disk
1594 function flushTemplateCache ($prefix, $template, $eval) {
1595         // Is this cache flushed?
1596         if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1597                 // Generate FQFN
1598                 $FQFN = generateCacheFqfn($prefix, $template);
1599
1600                 // Compile code another round for better performance and preserve $ signs
1601                 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1602
1603                 // Is this a XML template?
1604                 if ($prefix == 'xml') {
1605                         // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1606                         $eval = compactContent($eval);
1607                 } // END - if
1608
1609                 // And flush it
1610                 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1611         } // END - if
1612 }
1613
1614 // Reads a template cache
1615 function readTemplateCache ($prefix, $template, $content) {
1616         // Check it again
1617         if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1618                 // This should not happen
1619                 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1620         } // END - if
1621
1622         // Is it cached?
1623         if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1624                 // Generate FQFN
1625                 $FQFN = generateCacheFqfn($prefix, $template);
1626
1627                 /*
1628                  * And read from it.
1629                  *
1630                  * WARNING: Do not replace this include() call with loadInclude() as it
1631                  * would hide local variables away which is here required to make this
1632                  * work.
1633                  */
1634                 include($FQFN);
1635
1636                 // Is the template cache valid?
1637                 if (!isset($templateContent)) {
1638                         // Please clear your cache!
1639                         reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1640                 } // END - if
1641         } // END - if
1642
1643         // And return it
1644         return $templateContent;
1645 }
1646
1647 // Escapes quotes (default is only double-quotes)
1648 function escapeQuotes ($str, $single = FALSE) {
1649         // Should we escape all?
1650         if ($single === TRUE) {
1651                 // Escape all (including null)
1652                 $str = addslashes($str);
1653         } else {
1654                 // Replace all chars at once
1655                 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1656         }
1657
1658         // Return the escape'd string
1659         return $str;
1660 }
1661
1662 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1663 function escapeJavaScriptQuotes ($str) {
1664         // Replace all double-quotes and secure back-ticks
1665         $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1666
1667         // Return it
1668         return $str;
1669 }
1670
1671 // Send out mails depending on the 'mod/modes' combination
1672 // @TODO Lame description for this function
1673 function sendModeMails ($mod, $modes) {
1674         // Init user data
1675         $content = array ();
1676
1677         // Load hash
1678         if (fetchUserData(getMemberId())) {
1679                 // Extract salt from cookie
1680                 $salt = substr(getSession('u_hash'), 0, -40);
1681
1682                 // Now let's compare passwords
1683                 $hash = encodeHashForCookie(getUserData('password'));
1684
1685                 // Does the hash match or should we change it?
1686                 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1687                         // Load the data
1688                         $content = getUserDataArray();
1689
1690                         // Clear/init the content variable
1691                         $content['message'] = '';
1692
1693                         // Which mail?
1694                         // @TODO Move this in a filter
1695                         switch ($mod) {
1696                                 case 'mydata':
1697                                         foreach ($modes as $mode) {
1698                                                 switch ($mode) {
1699                                                         case 'normal': break; // Do not add any special lines
1700                                                         case 'email': // Email was changed!
1701                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1702                                                                 break;
1703
1704                                                         case 'password': // Password was changed
1705                                                                 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . PHP_EOL;
1706                                                                 break;
1707
1708                                                         default:
1709                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1710                                                                 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . PHP_EOL . PHP_EOL;
1711                                                                 break;
1712                                                 } // END - switch
1713                                         } // END - foreach
1714
1715                                         if (isExtensionActive('country')) {
1716                                                 // Replace code with description
1717                                                 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1718                                         } // END - if
1719
1720                                         // Merge content with data from POST
1721                                         $content = merge_array($content, postRequestArray());
1722
1723                                         // Load template
1724                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1725
1726                                         if (isAdminNotificationEnabled()) {
1727                                                 // The admin needs to be notified about a profile change
1728                                                 $message_admin = 'admin_mydata_notify';
1729                                                 $sub_adm   = '{--ADMIN_CHANGED_DATA--}';
1730                                         } else {
1731                                                 // No mail to admin
1732                                                 $message_admin = '';
1733                                                 $sub_adm   = '';
1734                                         }
1735
1736                                         // Set subject lines
1737                                         $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1738
1739                                         // Output success message
1740                                         $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1741                                         break;
1742
1743                                 default: // Unsupported module!
1744                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1745                                         $content['message'] = '<span class="bad">{--UNKNOWN_MODULE--}</span>';
1746                                         break;
1747                         } // END - switch
1748                 } else {
1749                         // Passwords mismatch
1750                         $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1751                 }
1752         } else {
1753                 // Could not load profile
1754                 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1755         }
1756
1757         // Send email to user if required
1758         if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1759                 // Send member mail
1760                 sendEmail($content['userid'], $sub_mem, $message);
1761         } // END - if
1762
1763         // Send only if no other error has occured
1764         if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1765                 // Send admin mail
1766                 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1767         } elseif (isAdminNotificationEnabled()) {
1768                 // Cannot send mails to admin!
1769                 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1770         } else {
1771                 // No mail to admin
1772                 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1773         }
1774
1775         // Load template
1776         displayMessage($content['message']);
1777 }
1778
1779 // Generates a 'selection box' from given array
1780 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1781         // Default is empty
1782         $addKey = '';
1783
1784         // Use default value as array key?
1785         if ($useDefaultAsArray === TRUE) {
1786                 // Then set it
1787                 $addKey = '[' . convertNullToZero($default) . ']';
1788         } // END - if
1789
1790         // Start the output
1791         $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1792 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1793
1794         // Allow none?
1795         if ($allowNone === TRUE) {
1796                 // Then add it
1797                 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1798         } // END - if
1799
1800         // Walk through all options
1801         foreach ($options as $option) {
1802                 // Default 'default' is not set
1803                 $option['default'] = '';
1804
1805                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1806                 // Is default value same as given value?
1807                 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1808                         // Then set default
1809                         $option['default'] = ' selected="selected"';
1810                 } // END - if
1811
1812                 // Is 'nameElement' set?
1813                 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1814                         // Then set this as extraName, but lower-case
1815                         $extraName = '_' . strtolower($option[$nameElement]);
1816                 } // END - if
1817
1818                 // Add the <option> entry from ...
1819                 if (empty($optionContent)) {
1820                         // Is a template name given?
1821                         if (empty($templateName)) {
1822                                 // ... $name template
1823                                 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1824                         } else {
1825                                 // ... $templateName template
1826                                 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1827                         }
1828                 } else {
1829                         // ... direct HTML code
1830                         $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1831                 }
1832         } // END - foreach
1833
1834         // Finish selection box
1835         $OUT .= '</select>';
1836
1837         // Prepare output
1838         $content = array(
1839                 'selection_box' => $OUT,
1840         );
1841
1842         // Load template and return it
1843         if (empty($templateName)) {
1844                 // Use name from $name + $extraName
1845                 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1846         } else {
1847                 // Use name from $templateName + $extraName
1848                 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1849         }
1850 }
1851
1852 // Prepares the header for HTML output
1853 function loadHtmlHeader () {
1854         /*
1855          * Run two filters:
1856          * 1.) pre_page_header (mainly loads the page_header template and includes
1857          *     meta description)
1858          */
1859         runFilterChain('pre_page_header');
1860
1861         /*
1862          * Here can be something be added, but normally one of the two filters
1863          * around this line should do the job for you.
1864          */
1865
1866         /*
1867          * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1868          *     to close the head-tag)
1869          * Include more header data here
1870          */
1871         runFilterChain('post_page_header');
1872 }
1873
1874 // Adds page header and footer to output array element
1875 function addPageHeaderFooter () {
1876         // Init output
1877         $OUT = '';
1878
1879         // Add them all together. This is maybe to simple
1880         foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1881                 // Add page part if set
1882                 if (isset($GLOBALS[$pagePart])) {
1883                         $OUT .= $GLOBALS[$pagePart];
1884                 } // END - if
1885         } // END - foreach
1886
1887         // Transfer $OUT to '__output'
1888         $GLOBALS['__output'] = $OUT;
1889 }
1890
1891 // Generates meta description for current module and 'what' value
1892 function generateMetaDescriptionCode () {
1893         // Only include from guest area and if ext-sql_patches has correct version
1894         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1895                 // Output it directly
1896                 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1897         } // END - if
1898
1899         // Initialize referral system
1900         initReferralSystem();
1901 }
1902
1903 // Generates an FQFN for template cache from the given template name
1904 function generateCacheFqfn ($prefix, $template) {
1905         // Is this cached?
1906         if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1907                 // Generate the FQFN
1908                 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1909                         '%s_compiled/%s/%s.tpl.cache',
1910                         getCachePath(),
1911                         $prefix,
1912                         $template
1913                 );
1914         } // END - if
1915
1916         // Return it
1917         return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1918 }
1919
1920 // "Fixes" null or empty string to count of dashes
1921 function fixNullEmptyToDashes ($str, $num) {
1922         // Use str as default
1923         $return = $str;
1924
1925         // Is it empty?
1926         if ((is_null($str)) || (trim($str) == '')) {
1927                 // Set it
1928                 $return = str_repeat('-', $num);
1929         } // END - if
1930
1931         // Return final string
1932         return $return;
1933 }
1934
1935 // Translates the "pool type" into human-readable
1936 function translatePoolType ($type) {
1937         // Return "translation"
1938         return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1939 }
1940
1941 // "Translates" given time unit
1942 function translateTimeUnit ($unit) {
1943         // Default is unknown
1944         $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1945
1946         // "Detect" it
1947         if (!isset($GLOBALS['time_units'][$unit])) {
1948                 // Not found
1949                 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1950         } else {
1951                 // Translate it with generic function
1952                 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1953         }
1954
1955         // Return message
1956         return $message;
1957 }
1958
1959 // Displays given message in admin_settings_saved template
1960 function displayMessage ($message, $return = FALSE) {
1961         // Load the template
1962         return loadTemplate('admin_settings_saved', $return, $message);
1963 }
1964
1965 // Displays given error message in admin_settings_saved template
1966 function displayErrorMessage ($message, $return = FALSE) {
1967         // Load the template
1968         return loadTemplate('admin_settings_unsaved', $return, $message);
1969 }
1970
1971 // Generates a selection box for (maybe) given gender
1972 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
1973         // Start the HTML code
1974         $out  = '<select name="' . $fieldName . '" size="1" class="form_select">';
1975
1976         // Add options
1977         $out .= generateOptions(
1978                 '/ARRAY/',
1979                 array(
1980                         'M',
1981                         'F',
1982                         'C'
1983                 ), array(
1984                         '{--GENDER_M--}',
1985                         '{--GENDER_F--}',
1986                         '{--GENDER_C--}'
1987                 ),
1988                 $selectedGender
1989         );
1990
1991         // Finish HTML code
1992         $out .= '</select>';
1993
1994         // Return the code
1995         return $out;
1996 }
1997
1998 // Generates a selection box for given default value
1999 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2000         // Init variables
2001         $messageIds = array();
2002
2003         // Generate message id array
2004         foreach ($unitArray as $unit) {
2005                 // "Translate" it
2006                 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2007         } // END - foreach
2008
2009         // Start the HTML code
2010         $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2011
2012         // Add options
2013         $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2014
2015         // Finish HTML code
2016         $out .= '</select>';
2017
2018         // Return the code
2019         return $out;
2020 }
2021
2022 // Function to add style tag (whether display:none/block)
2023 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2024         // Is there foo_menu_javascript enabled?
2025         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2026                 // Silently abort here, not enabled
2027                 return '';
2028         } // END - if
2029
2030         // Is action=mainAction?
2031         if ($action == $mainAction) {
2032                 // Add "menu open" style
2033                 return ' style="display:block"';
2034         } else {
2035                 return ' style="display:none"';
2036         }
2037 }
2038
2039 // Function to add onclick attribute
2040 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2041         // Is there foo_menu_javascript enabled?
2042         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2043                 // Silently abort here, not enabled
2044                 return '';
2045         } // END - if
2046
2047         // Prepare output
2048         $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2049
2050         // Return output
2051         return $OUT;
2052 }
2053
2054 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2055 function anonymizeSensitiveData ($data) {
2056         // Trim it
2057         $data = trim($data);
2058
2059         // Is it empty?
2060         if (empty($data)) {
2061                 // Then add three dashes
2062                 $data = '---';
2063         } elseif (isUrlValid($data)) {
2064                 // Is a referrer, so is it black-listed?
2065                 if (isAdmin()) {
2066                         // Is admin, has always priority
2067                         $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2068                 } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
2069                         // Yes, so replace it with text
2070                         $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2071                 } else {
2072                         // A  member is viewing this referral URL
2073                         $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2074                 }
2075         } elseif (isIp4AddressValid($data)) {
2076                 // Is an IPv4 address
2077                 $ipArray = explode('.', $data);
2078
2079                 // Only display first 2 octets
2080                 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2081         } else {
2082                 // Generic data
2083                 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2084         }
2085
2086         // Return it (hopefully) anonymized
2087         return $data;
2088 }
2089
2090 /**
2091  * Removes all comments, tabs and new-line characters to compact the content
2092  *
2093  * @param       $uncompactedContent             The uncompacted content
2094  * @return      $compactedContent               The compacted content
2095  */
2096 function compactContent ($uncompactedContent) {
2097         // First, remove all tab/new-line/revert characters
2098         $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2099
2100         // Make a space after >
2101         $compactedContent = str_replace(array('>', '  '), array('> ', ' '), $compactedContent);
2102
2103         // Then regex all comments like <!-- //--> away
2104         preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2105
2106         // Do we have entries?
2107         if (isset($matches[0][0])) {
2108                 // Remove all
2109                 foreach ($matches[0] as $match) {
2110                         // Remove the match
2111                         $compactedContent = str_replace($match, '', $compactedContent);
2112                 } // END - foreach
2113         } // END - if
2114
2115         // Return compacted content
2116         return $compactedContent;
2117 }
2118
2119 //-----------------------------------------------------------------------------
2120 //                     Template helper functions for EL code
2121 //-----------------------------------------------------------------------------
2122
2123 // Color-switch helper function
2124 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2125         // Is it there?
2126         if (!isset($GLOBALS['color_switch'][$templateName])) {
2127                 // Initialize it
2128                 initTemplateColorSwitch($templateName);
2129         } elseif ($clear === FALSE) {
2130                 // Switch color if called from loadTemplate()
2131                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2132                 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2133         }
2134
2135         // Return CSS class name
2136         if ($return === TRUE) {
2137                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2138                 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2139         } // END - if
2140 }
2141
2142 // Helper function for extension registration link
2143 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2144         // Default is all non-productive
2145         $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2146
2147         // Is the given extension non-productive?
2148         if (isExtensionDeprecated($ext_name)) {
2149                 // Is deprecated
2150                 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2151         } elseif (isExtensionProductive($ext_name)) {
2152                 // Productive code
2153                 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&amp;what=extensions&amp;register_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
2154         }
2155
2156         // Return code
2157         return $OUT;
2158 }
2159
2160 // Helper function to create bonus mail admin links
2161 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2162         // Call the inner function
2163         return generateAdminMailLinks('bonus', $bonusId);
2164 }
2165
2166 // Helper function to create member mail admin links
2167 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2168         // Call the inner function
2169         return generateAdminMailLinks('normal', $mailId);
2170 }
2171
2172 // Helper function to create a selection box for YES/NO configuration entries
2173 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2174         // Default is a "missing entry" warning
2175         $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2176
2177         // Generate the HTML code
2178         if (isConfigEntrySet($configEntry)) {
2179                 // Configuration entry is found
2180                 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2181 {%config,generateYesNoOptions=' . $configEntry . '%}
2182 </select>';
2183         } // END - if
2184
2185         // Return it
2186         return $OUT;
2187 }
2188
2189 // Helper function to create a selection box for YES/NO form fields
2190 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2191         // Generate the HTML code
2192         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2193 {%pipe,generateYesNoOptions%}
2194 </select>';
2195
2196         // Return it
2197         return $OUT;
2198 }
2199
2200 // Helper function to create a selection box for YES/NO form fields, by NO is default
2201 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2202         // Generate the HTML code
2203         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2204 {%pipe,generateYesNoOptions=N%}
2205 </select>';
2206
2207         // Return it
2208         return $OUT;
2209 }
2210
2211 // Helper function to add extra content for guest area (module=index and others)
2212 function doTemplateGuestFooterExtras ($templateName, $clear) {
2213         // Init filter data
2214         $filterData = array(
2215                 // Name of used template
2216                 'template' => $templateName,
2217                 // Target array for gathered data
2218                 '__data'   => array(),
2219                 // Where the HTML output will go
2220                 '__output' => '',
2221         );
2222
2223         // Run the filter chain
2224         $filterData = runFilterChain('guest_footer_extras', $filterData);
2225
2226         // Return output
2227         return $filterData['__output'];
2228 }
2229
2230 // Helper function to add extra content for member area (module=login)
2231 function doTemplateMemberFooterExtras ($templateName, $clear) {
2232         // Is a member logged in?
2233         if (!isMember()) {
2234                 // This shall not happen
2235                 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2236         } // END - if
2237
2238         // Init filter data
2239         $filterData = array(
2240                 // Current user's id number
2241                 'userid'   => getMemberId(),
2242                 // Name of used template
2243                 'template' => $templateName,
2244                 // Target array for gathered data
2245                 '__data'   => array(),
2246                 // Where the HTML output will go
2247                 '__output' => '',
2248         );
2249
2250         // Run the filter chain
2251         $filterData = runFilterChain('member_footer_extras', $filterData);
2252
2253         // Return output
2254         return $filterData['__output'];
2255 }
2256
2257 /**
2258  * Helper function to determine whether current userid is set, if none is set,
2259  * return a zero, else an EL code is being returned as of this function is used
2260  * only in templates.
2261  *
2262  * @param       $templateName   Name of template (unused)
2263  * @param       $clear                  Wether to clear something (unused)
2264  * @return      $userId                 Wether zero or EL code snippet
2265  */
2266 function doTemplateUserId ($templateName, $clear) {
2267         // By default no userid is set
2268         $userId = '0';
2269
2270         // Is there a user id currently set?
2271         if (isCurrentUserIdSet()) {
2272                 // Then get the current user id
2273                 $userId = getCurrentUserId();
2274         } // END - if
2275
2276         // Return it
2277         return $userId;
2278 }
2279
2280 // Template helper function to generate "Terms&Conditions" link (EL code again)
2281 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2282         /*
2283          * Use default link by default ;-) This link, however, will become
2284          * deprecated once ext-terms is rolled out.
2285          */
2286         $linkCode = '{%url=modules.php?module=index&amp;what=agb%}';
2287
2288         // Is ext-terms installed?
2289         if (isExtensionInstalled('terms')) {
2290                 // Then use that link (only 'what' has changed)
2291                 $linkCode = '{%url=modules.php?module=index&amp;what=terms%}';
2292         } // END - if
2293
2294         // Return link (EL) code
2295         return $linkCode;
2296 }
2297
2298 // Template helper function to create selection box for "locked points mode"
2299 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2300         // Init array
2301         $lockedModes = array(
2302                 0 => array('mode' => 'LOCKED'),
2303                 1 => array('mode' => 'UNLOCKED'),
2304         );
2305
2306         // Handle it over to generateSelectionBoxFromArray()
2307         $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2308
2309         // Return prepared content
2310         return $content;
2311 }
2312
2313 // Template helper function to create selection box for payment method
2314 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2315         // Init array
2316         $paymentMethods = array(
2317                 0 => array('method' => 'DIRECT'),
2318                 1 => array('method' => 'REFERRAL'),
2319         );
2320
2321         // Handle it over to generateSelectionBoxFromArray()
2322         $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2323
2324         // Return prepared content
2325         return $content;
2326 }
2327
2328 // Template helper function to create a deferrer code if URL is not empty
2329 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2330         // Is the URL not NULL and not empty?
2331         if ((!is_null($url)) && (!empty($url))) {
2332                 // Set HTML with EL code
2333                 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2334         } // END - if
2335
2336         // Return URL (or content) or dashes if empty
2337         return fixEmptyContentToDashes($url);
2338 }
2339
2340 // Load another template and return its content
2341 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = array()) {
2342         // Load "the" template
2343         return loadTemplate($theTemplate, TRUE, $content);
2344 }
2345
2346 // Output HTML code for favicon.ico, if found
2347 function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
2348         // Default is not found
2349         $out = '';
2350
2351         // Check all common extensions
2352         foreach (array('ico', 'gif', 'png') as $extension) {
2353                 // Is the file there?
2354                 if (isFileReadable(getPath() . 'favicon.' . $extension)) {
2355                         // Then use this and abort
2356                         $out = '<link rel="shortcut icon" href="{%url=favicon.ico%}" type="image/' . $extension . '" />';
2357                         break;
2358                 } // END - if
2359         } // END - while
2360
2361         // Return code
2362         return $out;
2363 }
2364
2365 // [EOF]
2366 ?>