cc04cdeb79295e04e23299d09355ec1017ca5c49
[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') && (!isFilledArray($GLOBALS['http_header'])) && (!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         $templateContent = '';
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 = getTemplateBasePath('html');
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 = getTemplateBasePath('emails');
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                 //* DEBUG: */ die('<pre>'.print_r($content, TRUE).'</pre><pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
566                 eval($GLOBALS['template_eval']['email'][$template]);
567                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
568         } // END - if
569
570         // Are there some content?
571         if (empty($templateContent)) {
572                 // Compiling failed
573                 $templateContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
574
575                 // Add last error if the required function exists
576                 if (function_exists('error_get_last')) {
577                         // Add last error and some lines for better overview
578                         $templateContent .= "\n--------------------------------------\nDebug:\n" . print_r(error_get_last(), TRUE) . "--------------------------------------\nPlease don't alter these informations!\nThanx.";
579                 } // END - if
580         } // END - if
581
582         // Remove content and data
583         unset($content);
584
585         // Return content
586         return $templateContent;
587 }
588
589 // "Getter" for menu CSS classes, mainly used in templates
590 function getMenuCssClasses ($data) {
591         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
592
593         // Is there cache?
594         if (!isset($GLOBALS[__FUNCTION__][$data])) {
595                 // $data needs to be converted into an array
596                 $content = explode('|', $data);
597
598                 // Non-existent index 2 will happen in menu blocks
599                 if (!isset($content[2])) {
600                         $content[2] = '';
601                 } // END - if
602
603                 // Re-construct the array: 0=visible,1=locked,2=prefix
604                 $content['visible'] = $content[0];
605                 $content['locked']  = $content[1];
606
607                 // Call our "translator" function
608                 $content = translateMenuVisibleLocked($content, $content[2]);
609
610                 // Set it in cache
611                 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
612         } // END - if
613
614         // Return cache
615         return $GLOBALS[__FUNCTION__][$data];
616 }
617
618 // Generate XHTML code for the CAPTCHA
619 function generateCaptchaCode ($code, $type, $urlId, $userid) {
620         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&amp;' . $type . '=' . $urlId . '&amp;do=img&amp;code=' . $code . '%}" />';
621 }
622
623 // Compiles the given HTML/mail code
624 function compileCode ($code, $full = TRUE, $compileCode = TRUE) {
625         // Is the code a string or should we not compile?
626         if ((!is_string($code)) || ($compileCode === FALSE)) {
627                 // Silently return it
628                 return $code;
629         } // END - if
630
631         // Start couting
632         $startCompile = microtime(TRUE);
633
634         // Comile the code
635         $code = compileRawCode($code, $full, $compileCode);
636
637         // Get timing
638         $compilationTime = $startCompile - microtime(TRUE);
639
640         // Add timing if enabled
641         if (isTemplateHtml()) {
642                 // Add timing, this should be disabled in
643                 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
644         } // END - if
645
646         // Return compiled code
647         return $code;
648 }
649
650 // Compiles the code
651 function compileRawCode ($code, $full = TRUE, $compileCode = TRUE) {
652         // Is the code a string or shall we not compile?
653         if ((!is_string($code)) || ($compileCode === FALSE)) {
654                 // Silently return it
655                 return $code;
656         } // END - if
657
658         // Init replacement-array with smaller set of security characters
659         $secChars = $GLOBALS['url_chars'];
660
661         // Select full set of chars to replace when we e.g. want to compile URLs
662         if ($full === TRUE) {
663                 $secChars = $GLOBALS['security_chars'];
664         } // END - if
665
666         // Compile more through a filter
667         $code = runFilterChain('compile_code', $code);
668
669         // First compile these chars
670         array_unshift($secChars['to']  , '{--'       , '--}');
671         array_unshift($secChars['from'], '{%message,', '%}' );
672
673         // Compile QUOT and other non-HTML codes
674         $code = str_replace($secChars['to'], $secChars['from'], $code);
675
676         // Find $content[bla][blub] entries
677         preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
678         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
679
680         // Are some matches found?
681         if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
682                 // Replace all matches
683                 $matchesFound = array();
684                 foreach ($matches[0] as $key => $match) {
685                         // Fuzzy look has failed by default
686                         $fuzzyFound = FALSE;
687
688                         // "Cache" match length
689                         $matchLength = strlen($match);
690
691                         // Fuzzy look on match if already found
692                         foreach ($matchesFound as $found => $set) {
693                                 // Get test part
694                                 $test = substr($found, 0, $matchLength);
695
696                                 // Does this entry exist?
697                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
698                                 if ($test == $match) {
699                                         // Match found
700                                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
701                                         $fuzzyFound = TRUE;
702                                         break;
703                                 } // END - if
704                         } // END - foreach
705
706                         // Skip this entry?
707                         if ($fuzzyFound === TRUE) {
708                                 continue;
709                         } // END - if
710
711                         // Take all string elements
712                         if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
713                                 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
714                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
715                                 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
716                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
717                                 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
718                                 $matchesFound[$match] = TRUE;
719                         } elseif (!isset($matchesFound[$match])) {
720                                 // Not yet replaced!
721                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
722                                 $code = str_replace($match, '".' . $match . '."', $code);
723                                 $matchesFound[$match] = 1;
724                         } else {
725                                 // Everthing else should be a least logged
726                                 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
727                         }
728                 } // END - foreach
729         } // END - if
730
731         /*
732          * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
733          * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
734          * therefore the variable's value won't be inserted. This is why
735          * {COMPILE_DOLLAR} is being used in above loop and at the end of this
736          * function being replace with the original dollar sign again.
737          */
738         preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
739
740         // Are some matches found?
741         if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
742                 // Scan all matches for not $content
743                 foreach ($matches[0] as $match) {
744                         // Trim match
745                         $match = trim($match);
746
747                         // Debug message
748                         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
749
750                         // Is the first part not $content/$userid and not empty?
751                         // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
752                         if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
753                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
754                                 // Then replace $ with {DOLLAR}
755                                 $matchSecured = str_replace('$', '{DOLLAR}', $match);
756
757                                 // And in $code as well
758                                 $code = str_replace($match, $matchSecured, $code);
759                         } // END - if
760                 } // END - if
761         } // END - if
762
763         // Replace {COMPILE_DOLLAR} back to dollar sign
764         $code = str_replace('{COMPILE_DOLLAR}', '$', $code);
765
766         // Finally return it
767         return $code;
768 }
769
770 //
771 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select') {
772         $OUT = '';
773
774         if ($type == 'yn') {
775                 // This is a yes/no selection only!
776                 if (isValidId($id)) $prefix .= '[' . $id . ']';
777                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
778         } else {
779                 // Begin with regular selection box here
780                 if (!empty($prefix)) $prefix .= '_';
781                 $type2 = $type;
782                 if (isValidId($id)) $type2 .= '[' . $id . ']';
783                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
784         }
785
786         switch ($type) {
787                 case 'ye': // Years
788                         // Get current year
789                         $year = getYear();
790
791                         // Use configured min age or fixed?
792                         if (isExtensionInstalledAndNewer('other', '0.2.1')) {
793                                 // Configured
794                                 $startYear = $year - getMinAge();
795                         } else {
796                                 // Fixed 16 years
797                                 $startYear = $year - 16;
798                         }
799
800                         // Calculate earliest year (100 years old people can still enter Internet???)
801                         $minYear = $year - 100;
802
803                         // Check if the default value is larger than minimum and bigger than actual year
804                         if (($default > $minYear) && ($default >= $year)) {
805                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
806                                         $OUT .= '<option value="' . $idx . '"';
807                                         if ($default == $idx) $OUT .= ' selected="selected"';
808                                         $OUT .= '>' . $idx . '</option>';
809                                 } // END - for
810                         } elseif ($default == -1) {
811                                 // Current year minus 1
812                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
813                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
814                                 } // END - for
815                         } else {
816                                 // Get current year and subtract the configured minimum age
817                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
818
819                                 // Construct year selection list
820                                 for ($idx = $minYear; $idx <= $startYear; $idx++) {
821                                         $OUT .= '<option value="' . $idx . '"';
822                                         if ($default == $idx) $OUT .= ' selected="selected"';
823                                         $OUT .= '>' . $idx . '</option>';
824                                 } // END - for
825                         }
826                         break;
827
828                 case 'mo': // Months
829                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
830                                 $OUT .= '<option value="' . $idx . '"';
831                                 if ($default == $idx) $OUT .= ' selected="selected"';
832                                 $OUT .= '>' . $descr . '</option>';
833                         } // END - for
834                         break;
835
836                 case 'mn': // Months, numeric
837                         for ($idx = 0; $idx <= 12; $idx++) {
838                                 $OUT .= '<option value="' . $idx . '"';
839                                 if ($default == $idx) $OUT .= ' selected="selected"';
840                                 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
841                         } // END - for
842                         break;
843
844                 case 'we': // Weeks
845                         for ($idx = 0; $idx <= 4; $idx++) {
846                                 $OUT .= '  <option value="' . $idx . '"';
847                                 if ($default == $idx) $OUT .= ' selected="selected"';
848                                 $OUT .= '>' . $idx . '</option>';
849                         } // END - for
850                         break;
851
852                 case 'da': // Days
853                         for ($idx = 0; $idx <= 31; $idx++) {
854                                 $OUT .= '<option value="' . $idx . '"';
855                                 if ($default == $idx) $OUT .= ' selected="selected"';
856                                 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
857                         } // END - for
858                         break;
859
860                 case 'ho': // Hours
861                         for ($idx = 0; $idx <= 23; $idx++) {
862                                 $padded = padLeftZero($idx, 2);
863                                 $OUT .= '<option value="' . $padded . '"';
864                                 if ($default == $padded) $OUT .= ' selected="selected"';
865                                 $OUT .= '>' . $padded . '</option>';
866                         } // END - for
867                         break;
868
869                 case 'mi': // Minutes
870                 case 'se': // Seconds
871                         for ($idx = 0; $idx <= 59; $idx+=5) {
872                                 $padded = padLeftZero($idx, 2);
873                                 $OUT .= '<option value="' . $padded . '"';
874                                 if ($default == $padded) $OUT .= ' selected="selected"';
875                                 $OUT .= '>' . $padded . '</option>';
876                         } // END - for
877                         break;
878
879                 case 'yn': // Yes/No
880                         $OUT .= '<option value="Y"';
881                         if ($default == 'Y') $OUT .= ' selected="selected"';
882                         $OUT .= '>{--YES--}</option><option value="N"';
883                         if ($default != 'Y') $OUT .= ' selected="selected"';
884                         $OUT .= '>{--NO--}</option>';
885                         break;
886
887                 default: // Not detected
888                         reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' .  $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
889                         break;
890         }
891         $OUT .= '</select>';
892         return $OUT;
893 }
894
895 // Insert the code in $img_code into jpeg or PNG image
896 function generateImageOrCode ($img_code, $headerSent = TRUE) {
897         // Is the code size oversized or shouldn't we display it?
898         if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
899                 // Stop execution of function here because of over-sized code length
900                 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
901         } elseif ($headerSent === FALSE) {
902                 // Return an HTML code here
903                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
904         }
905
906         // Load image
907         $img = sprintf('%s/theme/%s/images/code_bg.%s',
908                 getPath(),
909                 getCurrentTheme(),
910                 getImgType()
911         );
912
913         // Is it readable?
914         if (isFileReadable($img)) {
915                 // Switch image type
916                 switch (getImgType()) {
917                         case 'jpg': // Okay, load image and hide all errors
918                                 $image = imagecreatefromjpeg($img);
919                                 break;
920
921                         case 'png': // Okay, load image and hide all errors
922                                 $image = imagecreatefrompng($img);
923                                 break;
924                 } // END - switch
925         } else {
926                 // Silently log the error
927                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('File for image-type %s in theme %s not found.', getImgType(), getCurrentTheme()));
928                 return;
929         }
930
931         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
932         $text_color = imagecolorallocate($image, 0, 0, 0);
933
934         // Insert code into image
935         imagestring($image, 5, 14, 2, $img_code, $text_color);
936
937         // Return to browser
938         setContentType('image/' . getImgType());
939
940         // Output image with matching image factory
941         switch (getImgType()) {
942                 case 'jpg': imagejpeg($image); break;
943                 case 'png': imagepng($image);  break;
944         } // END - switch
945
946         // Remove image from memory
947         imagedestroy($image);
948 }
949
950 // Create selection box or array of splitted timestamp
951 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE) {
952         // Do not continue if ONE_DAY is absend
953         if (!isConfigEntrySet('ONE_DAY')) {
954                 // Abort here
955                 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
956         } // END - if
957
958         // Calculate 2-seconds timestamp
959         $stamp = round($timestamp);
960         //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
961
962         // Is there a leap year?
963         $SWITCH = '0';
964         $TEST = getYear() / 4;
965         $M1 = getMonth();
966         $M2 = getMonth(time() + $timestamp);
967
968         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
969         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02'))  {
970                 $SWITCH = getOneDay();
971         } // END - switch
972
973         // First of all years...
974         $year = abs(floor($timestamp / (31536000 + $SWITCH)));
975         //* DEBUG: */ debugOutput('year=' . $year);
976         // Next months...
977         $month = abs(floor($timestamp / 2628000 - $year * 12));
978         //* DEBUG: */ debugOutput('month=' . $month);
979         // Next weeks
980         $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
981         //* DEBUG: */ debugOutput('week=' . $week);
982         // Next days...
983         $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
984         //* DEBUG: */ debugOutput('day=' . $day);
985         // Next hours...
986         $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
987         //* DEBUG: */ debugOutput('hour=' . $hour);
988         // Next minutes..
989         $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));
990         //* DEBUG: */ debugOutput('minute=' . $minute);
991         // And at last seconds...
992         $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));
993         //* DEBUG: */ debugOutput('second=' . $second);
994
995         // Is seconds zero and time is < 60 seconds?
996         if (($second < 1) && ($timestamp < 60)) {
997                 // Fix seconds
998                 $second = round($timestamp);
999         } // END - if
1000
1001         // Put all calculated values in array
1002         $data = array(
1003                 'Y' => $year,
1004                 'M' => $month,
1005                 'W' => $week,
1006                 'D' => $day,
1007                 'h' => $hour,
1008                 'm' => $minute,
1009                 's' => $second
1010         );
1011
1012         //
1013         // Now we convert them in seconds...
1014         //
1015         if ($asArray === TRUE) {
1016                 // Just put data array out
1017                 $OUT = $data;
1018         } else {
1019                 // Init array
1020                 $units = array(
1021                         // Time unit -> field name
1022                         'unit_field' => array(
1023                                 'Y' => 'ye',
1024                                 'M' => 'mn',
1025                                 'W' => 'we',
1026                                 'D' => 'da',
1027                                 'h' => 'ho',
1028                                 'm' => 'mi',
1029                                 's' => 'se'
1030                         ),
1031                         // Time unit -> label
1032                         'unit_label' => array(
1033                                 'Y' => 'YEAR',
1034                                 'M' => 'MONTH',
1035                                 'W' => 'WEEK',
1036                                 'D' => 'DAY',
1037                                 'h' => 'HOUR',
1038                                 'm' => 'MINUTE',
1039                                 's' => 'SECOND'
1040                         )
1041                 );
1042
1043                 // Generate table
1044                 $OUT  = '<div align="' . $align . '">';
1045                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1046                 $OUT .= '<tr>';
1047
1048                 // "Walk" through all units
1049                 foreach ($units['unit_field'] as $unit => $field) {
1050                         // Is this displayed or zero?
1051                         if (isInString($unit, $display) || (empty($display))) {
1052                                 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1053                                 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1054                         } // END - if
1055                 } // END - foreach
1056
1057                 // Close table row and open new one
1058                 $OUT .= '</tr>';
1059                 $OUT .= '<tr>';
1060
1061                 // "Walk" through all units again
1062                 foreach ($units['unit_field'] as $unit => $field) {
1063                         // Is this used?
1064                         if (isInString($unit, $display) || (empty($display))) {
1065                                 // Generate year selection
1066                                 $OUT .= '<td align="center">';
1067                                 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select');
1068                                 $OUT .= '</td>';
1069                         } else {
1070                                 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1071                         }
1072                 } // END - foreach
1073
1074                 // Close all tags
1075                 $OUT .= '</tr>';
1076                 $OUT .= '</table>';
1077                 $OUT .= '</div>';
1078         }
1079
1080         // Return generated HTML code or data array
1081         return $OUT;
1082 }
1083
1084 // Generate a list of administrative links to a given userid
1085 function generateMemberAdminActionLinks ($userid) {
1086         // Make sure userid is a number
1087         if ($userid != bigintval($userid)) {
1088                 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1089         } // END - if
1090
1091         // Define all main targets
1092         $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1093
1094         // Get user status
1095         $status = getFetchedUserData('userid', $userid, 'status');
1096
1097         // Begin of navigation links
1098         $OUT = '[';
1099
1100         foreach ($targetArray as $target) {
1101                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $target . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1102                 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1103                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1104                         // Locked accounts shall be unlocked
1105                         $OUT .= 'UNLOCK_USER';
1106                 } elseif ($target == 'del_user') {
1107                         // @TODO Deprecate this thing
1108                         $OUT .= 'DELETE_USER';
1109                 } else {
1110                         // All other status is fine
1111                         $OUT .= strtoupper($target);
1112                 }
1113                 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1114                 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1115                         // Locked accounts shall be unlocked
1116                         $OUT .= 'UNLOCK_USER';
1117                 } elseif ($target == 'del_user') {
1118                         // @TODO Deprecate this thing
1119                         $OUT .= 'DELETE_USER';
1120                 } else {
1121                         // All other status is fine
1122                         $OUT .= strtoupper($target);
1123                 }
1124                 $OUT .= '--}</a></span>|';
1125         } // END - foreach
1126
1127         // Add special link, in case of the account is unconfirmed
1128         if ($status == 'UNCONFIRMED') {
1129                 // Add it
1130                 $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>|';
1131         } // END - if
1132
1133         // Finish navigation link
1134         $OUT = substr($OUT, 0, -1) . ']';
1135
1136         // Return string
1137         return $OUT;
1138 }
1139
1140 // Generate an email link
1141 function generateEmailLink ($email, $table = 'admins') {
1142         // Default email link (INSECURE! Spammer can read this by harvester programs)
1143         $EMAIL = 'mailto:' . $email;
1144
1145         // Check for several extensions
1146         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1147                 // Create email link for contacting admin in guest area
1148                 $EMAIL = generateAdminEmailLink($email);
1149         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1150                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1151                 $EMAIL = generateUserEmailLink($email);
1152         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1153                 // Create email link to contact sponsor within admin area (or like the link above?)
1154                 $EMAIL = generateSponsorEmailLink($email);
1155         }
1156
1157         // Return email link
1158         return $EMAIL;
1159 }
1160
1161 /**
1162  * Outputs an error message in a "fashioned way" to the user, by putting it into
1163  * a nice looking web page, if one of HTML or CSS output mode is active.
1164  *
1165  * Please use reportBug() instead of this function. reportBug() has more helpful
1166  * functionality like logging and admin notification (which you can configure
1167  * through your admin area).
1168  *
1169  * @param       $file           Function or file basename where the error came from
1170  * @param       $line           Line number where the error came from
1171  * @param       $message        Message which shall be output to web
1172  * @return      void
1173  */
1174 function app_exit ($file, $line, $message) {
1175         // Check if Script is already dieing and not let it kill itself another 1000 times
1176         if (isset($GLOBALS['app_died'])) {
1177                 // Script tried to kill itself twice
1178                 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $file . ', line=' . $line);
1179         } // END - if
1180
1181         // Make sure, that the script realy realy diese here and now
1182         $GLOBALS['app_died'] = TRUE;
1183
1184         // Is this AJAX mode?
1185         if (isAjaxOutputMode()) {
1186                 // Set content type as application/json
1187                 setContentType('application/json');
1188         } else {
1189                 // Set content type as text/html
1190                 setContentType('text/html');
1191         }
1192
1193         // Load header
1194         loadIncludeOnce('inc/header.php');
1195
1196         // Rewrite message for output
1197         $message = sprintf(
1198                 getMessage('MAILER_HAS_DIED'),
1199                 basename($file),
1200                 $line,
1201                 $message
1202         );
1203
1204         // Is this AJAX mode again
1205         if (isAjaxOutputMode()) {
1206                 // Load the message template
1207                 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1208
1209                 // Output it as JSON encoded
1210                 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation($OUT)))));
1211         } else {
1212                 // Load the message template
1213                 loadTemplate('app_exit_message', FALSE, $message);
1214         }
1215
1216         // Load footer
1217         loadIncludeOnce('inc/footer.php');
1218 }
1219
1220 // Display parsing time and number of SQL queries in footer
1221 function displayParsingTime () {
1222         // Is the timer started?
1223         if (!isset($GLOBALS['__start_time'])) {
1224                 // Abort here
1225                 return FALSE;
1226         } // END - if
1227
1228         // Get end time
1229         $endTime = microtime(TRUE);
1230
1231         // "Explode" both times
1232         $start = explode(' ', $GLOBALS['__start_time']);
1233         $end = explode(' ', $endTime);
1234         $runTime = $end[0] - $start[0];
1235         if ($runTime < 0) {
1236                 $runTime = '0';
1237         } // END - if
1238
1239         // Prepare output
1240         // @TODO This can be easily moved out after the merge from EL branch to this is complete
1241         $content = array(
1242                 'run_time' => $runTime,
1243                 'sql_time' => (getConfig('sql_time') * 1000),
1244         );
1245
1246         // Load the template
1247         $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1248
1249         // Is debug enabled?
1250         if (isDebugModeEnabled()) {
1251                 // Log loading of total includes
1252                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
1253         } // END - if
1254 }
1255
1256 /**
1257  * Outputs an error message and backtrace to the user, by default a mail with
1258  * all relevant data is being mailed to the configured administrators.
1259  *
1260  * This function shall be used "publicly" because of logging, admin notification
1261  * and double-call prevention (see first if() block) instead of app_exit().
1262  * app_exit() is more a "private" function and will only output a bug message to
1263  * the user, no email and no logging.
1264  *
1265  * @param       $file           Function or file basename where the error came from
1266  * @param       $line           Line number where the error came from
1267  * @param       $sendEmail      Wether to send an email to all configured administrators
1268  * @return      void
1269  */
1270 function reportBug ($file, $line, $message = '', $sendEmail = TRUE) {
1271         // Is this already called?
1272         if (isset($GLOBALS[__FUNCTION__])) {
1273                 // Other backtrace
1274                 print '[' . $file . ':' . $line . ':] ' . __FUNCTION__ . '() has already died! Message:' . $message . '<br />Backtrace:<pre>';
1275                 debug_print_backtrace();
1276                 die('</pre>');
1277         } // END - if
1278
1279         // Set HTTP status to 500 (e.g. for AJAX requests)
1280         setHttpStatus('500 Internal Server Error');
1281
1282         // Mark this function as called
1283         $GLOBALS[__FUNCTION__] = TRUE;
1284
1285         // Init message
1286         $debug = '';
1287
1288         // Is the optional message set?
1289         if (!empty($message)) {
1290                 // Use and log it
1291                 $debug = sprintf("Note: %s<br />\n",
1292                         $message
1293                 );
1294
1295                 // @TODO Add a little more infos here
1296                 logDebugMessage($file, $line, strip_tags($message));
1297         } // END - if
1298
1299         // Add output
1300         $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>';
1301         $debug .= debug_get_printable_backtrace();
1302         $debug .= '</pre>';
1303         $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1304         $debug .= '<div class="para">Thank you for finding bugs.</div>';
1305
1306         // Send an email? (e.g. not wanted for evaluation errors)
1307         if (($sendEmail === TRUE) && (!isInstaller()) && (isAdminRegistered())) {
1308                 // Prepare content
1309                 $content = array(
1310                         'message'   => trim($message),
1311                         'backtrace' => trim(debug_get_mailable_backtrace())
1312                 );
1313
1314                 // Send email to webmaster
1315                 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1316         } // END - if
1317
1318         // Is there HTML/CSS/AJAX mode while debug-mode is enabled?
1319         if ((isDebugModeEnabled()) && ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode()))) {
1320                 // And abort here
1321                 app_exit($file, $line, $debug);
1322         } elseif (isAjaxOutputMode()) {
1323                 // Load include (again?)
1324                 loadIncludeOnce('inc/ajax-functions.php');
1325
1326                 // Init AJAX
1327                 initAjax();
1328
1329                 // Set HTTP status to 500 again
1330                 setHttpStatus('500 Internal Server Error');
1331
1332                 // Is AJAX output mode, then output message as JSON
1333                 setAjaxReplyContent($debug);
1334
1335                 // Send it out to browser
1336                 sendAjaxContent(TRUE);
1337
1338                 // Include footer
1339                 loadIncludeOnce('inc/footer.php');
1340         } else {
1341                 // Raw/image output mode and all other modes doesn't work well with text ...
1342                 die();
1343         }
1344 }
1345
1346 // Compile characters which are allowed in URLs
1347 function compileUriCode ($code, $simple = TRUE) {
1348         // Trim code
1349         $test = trim($code);
1350
1351         // Is it empty?
1352         if (empty($test)) {
1353                 // Then abort here and return the original code
1354                 return $code;
1355         } // END - if
1356
1357         // Compile these by default
1358         $charsCompile = array(
1359                 'from' => array(
1360                         '{DOT}',
1361                         '{SLASH}',
1362                         '{QUOT}',
1363                         '{DOLLAR}',
1364                         '{OPEN_ANCHOR}',
1365                         '{CLOSE_ANCHOR}',
1366                         '{OPEN_SQR}',
1367                         '{CLOSE_SQR}',
1368                         '{PER}'
1369                 ),
1370                 'to' => array(
1371                         '.',
1372                         '/',
1373                         chr(39),
1374                         '$',
1375                         '(',
1376                         ')',
1377                         '[',
1378                         ']',
1379                         '%'
1380                 )
1381         );
1382
1383         // Compile constants
1384         if ($simple === FALSE) {
1385                 // Add more 'from'
1386                 array_unshift($charsCompile['from'], '{--', '--}');
1387
1388                 // Add more 'to'
1389                 array_unshift($charsCompile['to'], '".', '."');
1390         } // END - if
1391
1392         // Compile QUOT and other non-HTML codes
1393         $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1394         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1395
1396         // Return compiled code
1397         return $code;
1398 }
1399
1400 // Handle message codes from URL
1401 function handleCodeMessage () {
1402         // Is 'code' set?
1403         if (isGetRequestElementSet('code')) {
1404                 // Default extension is 'unknown'
1405                 $ext = 'unknown';
1406
1407                 // Is extension given?
1408                 if (isGetRequestElementSet('ext')) {
1409                         $ext = getRequestElement('ext');
1410                 } // END - if
1411
1412                 // Convert the 'code' parameter from URL to a human-readable message
1413                 $message = getMessageFromErrorCode(getRequestElement('code'));
1414
1415                 // Load message template
1416                 loadTemplate('message', FALSE, $message);
1417         } // END - if
1418 }
1419
1420 // Generates a 'extension foo out-dated' message
1421 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1422         // Is the extension empty?
1423         if (empty($ext_name)) {
1424                 // This should not happen
1425                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1426         } // END - if
1427
1428         // Default message
1429         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1430
1431         // Is an admin logged in?
1432         if (isAdmin()) {
1433                 // Then output admin message
1434                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1435         } // END - if
1436
1437         // Return prepared message
1438         return $message;
1439 }
1440
1441 // Generates a 'extension foo inactive' message
1442 function generateExtensionInactiveMessage ($ext_name) {
1443         // Is the extension empty?
1444         if (empty($ext_name)) {
1445                 // This should not happen
1446                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1447         } // END - if
1448
1449         // Default message
1450         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1451
1452         // Is an admin logged in?
1453         if (isAdmin()) {
1454                 // Then output admin message
1455                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1456         } // END - if
1457
1458         // Return prepared message
1459         return $message;
1460 }
1461
1462 // Generates a 'extension foo not installed' message
1463 function generateExtensionNotInstalledMessage ($ext_name) {
1464         // Is the extension empty?
1465         if (empty($ext_name)) {
1466                 // This should not happen
1467                 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1468         } // END - if
1469
1470         // Default message
1471         $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1472
1473         // Is an admin logged in?
1474         if (isAdmin()) {
1475                 // Then output admin message
1476                 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1477         } // END - if
1478
1479         // Return prepared message
1480         return $message;
1481 }
1482
1483 // Generates a message depending on if the extension is not installed or not
1484 // just activated
1485 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1486         // Init message
1487         $message = '';
1488
1489         // Is the extension not installed or just deactivated?
1490         switch (isExtensionInstalled($ext_name)) {
1491                 case TRUE; // Deactivated!
1492                         $message = generateExtensionInactiveMessage($ext_name);
1493                         break;
1494
1495                 case FALSE; // Not installed!
1496                         $message = generateExtensionNotInstalledMessage($ext_name);
1497                         break;
1498
1499                 default: // Should not happen!
1500                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid state of extension %s detected.', $ext_name));
1501                         $message = sprintf('Invalid state of extension %s detected.', $ext_name);
1502                         break;
1503         } // END - switch
1504
1505         // Return the message
1506         return $message;
1507 }
1508
1509 // Print code with line numbers
1510 function lineNumberCode ($code)    {
1511         // By default copy the code
1512         $codeE = $code;
1513
1514         if (!is_array($code)) {
1515                 // We need an array, so try it with the new-line character
1516                 $codeE = explode(PHP_EOL, $code);
1517         } // END - if
1518
1519         $count_lines = count($codeE);
1520
1521         $r = 'Line | Code:<br />';
1522         foreach ($codeE as $line => $c) {
1523                 $r .= '<div class="line"><span class="linenum">';
1524                 if ($count_lines == 1) {
1525                         $r .= 1;
1526                 } else {
1527                         $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1528                 }
1529                 $r .= '</span>|';
1530
1531                 // Add code
1532                 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1533         } // END - foreach
1534
1535         return '<div class="code">' . $r . '</div>';
1536 }
1537
1538 // Determines the right page title
1539 function determinePageTitle () {
1540         // Init page title
1541         $pageTitle = '';
1542
1543         // Config and database connection valid?
1544         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1545                 // Title decoration enabled?
1546                 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1547                         $pageTitle .= '{%config,trim=title_left%} ';
1548                 } // END - if
1549
1550                 // Is there an extra title?
1551                 if (isExtraTitleSet()) {
1552                         // Then prepend it
1553                         $pageTitle .= '{%pipe,getExtraTitle%} by ';
1554                 } // END - if
1555
1556                 // Add main title
1557                 $pageTitle .= '{?MAIN_TITLE?}';
1558
1559                 // Add title of module? (middle decoration will also be added!)
1560                 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1561                         $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1562                 } // END - if
1563
1564                 // Get menu mode from module
1565                 $menuMode = getMenuModeFromModule();
1566
1567                 // Add middle part (always in admin area!)
1568                 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1569                         $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1570                 } // END - if
1571
1572                 // Add title decorations? (right)
1573                 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1574                         $pageTitle .= ' {%config,trim=title_right%}';
1575                 } // END - if
1576         } elseif ((isInstalled()) && (isAdminRegistered())) {
1577                 // Installed, admin registered but no ext-sql_patches
1578                 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1579         } elseif ((isInstalled()) && (!isAdminRegistered())) {
1580                 // Installed but no admin registered
1581                 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1582         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1583                 // Installation mode
1584                 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1585         } else {
1586                 // Configuration not found
1587                 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1588
1589                 // Do not add the fatal message in installation mode
1590                 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1591                         // Please report this
1592                         reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1593                 } // END - if
1594         }
1595
1596         // Return title
1597         return decodeEntities($pageTitle);
1598 }
1599
1600 // Checks whethere there is a cache file there. This function is cached.
1601 function isTemplateCached ($prefix, $template) {
1602         // Is there cached this result?
1603         if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1604                 // Generate FQFN
1605                 $FQFN = generateCacheFqfn($prefix, $template);
1606
1607                 // Is it there?
1608                 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1609         } // END - if
1610
1611         // Return it
1612         return $GLOBALS['template_cache'][$prefix][$template];
1613 }
1614
1615 // Flushes non-flushed template cache to disk
1616 function flushTemplateCache ($prefix, $template, $eval) {
1617         // Is this cache flushed?
1618         if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1619                 // Generate FQFN
1620                 $FQFN = generateCacheFqfn($prefix, $template);
1621
1622                 // Compile code another round for better performance and preserve $ signs
1623                 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1624
1625                 // Is this a XML template?
1626                 if ($prefix == 'xml') {
1627                         // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1628                         $eval = compactContent($eval);
1629                 } // END - if
1630
1631                 // And flush it
1632                 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1633         } // END - if
1634 }
1635
1636 // Reads a template cache
1637 function readTemplateCache ($prefix, $template, $content) {
1638         // Check it again
1639         if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1640                 // This should not happen
1641                 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1642         } // END - if
1643
1644         // Is it cached?
1645         if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1646                 // Generate FQFN
1647                 $FQFN = generateCacheFqfn($prefix, $template);
1648
1649                 /*
1650                  * And read from it.
1651                  *
1652                  * WARNING: Do not replace this include() call with loadInclude() as it
1653                  * would hide local variables away which is here required to make this
1654                  * work.
1655                  */
1656                 include($FQFN);
1657
1658                 // Is the template cache valid?
1659                 if (!isset($templateContent)) {
1660                         // Please clear your cache!
1661                         reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1662                 } // END - if
1663         } // END - if
1664
1665         // And return it
1666         return $templateContent;
1667 }
1668
1669 // Escapes quotes (default is only double-quotes)
1670 function escapeQuotes ($str, $single = FALSE) {
1671         // Should we escape all?
1672         if ($single === TRUE) {
1673                 // Escape all (including null)
1674                 $str = addslashes($str);
1675         } else {
1676                 // Replace all chars at once
1677                 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1678         }
1679
1680         // Return the escape'd string
1681         return $str;
1682 }
1683
1684 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1685 function escapeJavaScriptQuotes ($str) {
1686         // Replace all double-quotes and secure back-ticks
1687         $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1688
1689         // Return it
1690         return $str;
1691 }
1692
1693 // Send out mails depending on the 'mod/modes' combination
1694 // @TODO Lame description for this function
1695 function sendModeMails ($mod, $modes) {
1696         // Init user data
1697         $content = array ();
1698
1699         // Load hash
1700         if (fetchUserData(getMemberId())) {
1701                 // Extract salt from cookie
1702                 $salt = substr(getSession('u_hash'), 0, -40);
1703
1704                 // Now let's compare passwords
1705                 $hash = encodeHashForCookie(getUserData('password'));
1706
1707                 // Does the hash match or should we change it?
1708                 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1709                         // Load the data
1710                         $content = getUserDataArray();
1711
1712                         // Clear/init the content variable
1713                         $content['message'] = '';
1714
1715                         // Which mail?
1716                         // @TODO Move this in a filter
1717                         switch ($mod) {
1718                                 case 'mydata':
1719                                         foreach ($modes as $mode) {
1720                                                 switch ($mode) {
1721                                                         case 'normal': break; // Do not add any special lines
1722                                                         case 'email': // Email was changed!
1723                                                                 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1724                                                                 break;
1725
1726                                                         case 'password': // Password was changed
1727                                                                 $content['message'] = '{--MEMBER_CHANGED_PASSWORD--}' . PHP_EOL;
1728                                                                 break;
1729
1730                                                         default:
1731                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown mode %s detected.', $mode));
1732                                                                 $content['message'] = '{%message,MEMBER_UNKNOWN_MODE=' .  $mode . '%}' . PHP_EOL . PHP_EOL;
1733                                                                 break;
1734                                                 } // END - switch
1735                                         } // END - foreach
1736
1737                                         if (isExtensionActive('country')) {
1738                                                 // Replace code with description
1739                                                 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1740                                         } // END - if
1741
1742                                         // Merge content with data from POST
1743                                         $content = merge_array($content, postRequestArray());
1744
1745                                         // Load template
1746                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1747
1748                                         if (isAdminNotificationEnabled()) {
1749                                                 // The admin needs to be notified about a profile change
1750                                                 $message_admin = 'admin_mydata_notify';
1751                                                 $subjectAdmin   = '{--ADMIN_CHANGED_DATA_SUBJECT--}';
1752                                         } else {
1753                                                 // No mail to admin
1754                                                 $message_admin = '';
1755                                                 $subjectAdmin  = '';
1756                                         }
1757
1758                                         // Set subject lines
1759                                         $subjectMember = '{--MEMBER_CHANGED_DATA--}';
1760
1761                                         // Output success message
1762                                         $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1763                                         break;
1764
1765                                 default: // Unsupported module!
1766                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unsupported module %s detected.', $mod));
1767                                         $content['message'] = '<span class="bad">{%message,UNKNOWN_MODULE=' . $mod . '%}</span>';
1768                                         break;
1769                         } // END - switch
1770                 } else {
1771                         // Passwords mismatch
1772                         $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1773                 }
1774         } else {
1775                 // Could not load profile
1776                 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1777         }
1778
1779         // Send email to user if required
1780         if ((!empty($subjectMember)) && (!empty($message)) && (!empty($content['userid']))) {
1781                 // Send member mail
1782                 sendEmail($content['userid'], $subjectMember, $message);
1783         } // END - if
1784
1785         // Send only if no other error has occured
1786         if ((!empty($subjectAdmin)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1787                 // Send admin mail
1788                 sendAdminNotification($subjectAdmin, $message_admin, $content, getMemberId());
1789         } elseif (isAdminNotificationEnabled()) {
1790                 // Cannot send mails to admin!
1791                 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1792         } else {
1793                 // No mail to admin
1794                 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1795         }
1796
1797         // Load template
1798         displayMessage($content['message']);
1799 }
1800
1801 // Generates a 'selection box' from given array
1802 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1803         // options must be an array
1804         assert(is_array($options));
1805
1806         // Default is empty
1807         $addKey = '';
1808
1809         // Use default value as array key?
1810         if ($useDefaultAsArray === TRUE) {
1811                 // Then set it
1812                 $addKey = '[' . convertNullToZero($default) . ']';
1813         } // END - if
1814
1815         // Start the output
1816         $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1817 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1818
1819         // Allow none?
1820         if ($allowNone === TRUE) {
1821                 // Then add it
1822                 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1823         } // END - if
1824
1825         // Walk through all options
1826         foreach ($options as $option) {
1827                 // Default 'default' is not set
1828                 $option['default'] = '';
1829
1830                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1831                 // Is default value same as given value?
1832                 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1833                         // Then set default
1834                         $option['default'] = ' selected="selected"';
1835                 } // END - if
1836
1837                 // Is 'nameElement' set?
1838                 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1839                         // Then set this as extraName, but lower-case
1840                         $extraName = '_' . strtolower($option[$nameElement]);
1841                 } // END - if
1842
1843                 // Add the <option> entry from ...
1844                 if (empty($optionContent)) {
1845                         // Is a template name given?
1846                         if (empty($templateName)) {
1847                                 // ... $name template
1848                                 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1849                         } else {
1850                                 // ... $templateName template
1851                                 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1852                         }
1853                 } else {
1854                         // ... direct HTML code
1855                         $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1856                 }
1857         } // END - foreach
1858
1859         // Finish selection box
1860         $OUT .= '</select>';
1861
1862         // Prepare output
1863         $content = array(
1864                 'selection_box' => $OUT,
1865         );
1866
1867         // Load template and return it
1868         if (empty($templateName)) {
1869                 // Use name from $name + $extraName
1870                 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1871         } else {
1872                 // Use name from $templateName + $extraName
1873                 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1874         }
1875 }
1876
1877 // Prepares the header for HTML output
1878 function loadHtmlHeader () {
1879         /*
1880          * Run two filters:
1881          * 1.) pre_page_header (mainly loads the page_header template and includes
1882          *     meta description)
1883          */
1884         runFilterChain('pre_page_header');
1885
1886         /*
1887          * Here can be something be added, but normally one of the two filters
1888          * around this line should do the job for you.
1889          */
1890
1891         /*
1892          * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1893          *     to close the head-tag)
1894          * Include more header data here
1895          */
1896         runFilterChain('post_page_header');
1897 }
1898
1899 // Adds page header and footer to output array element
1900 function addPageHeaderFooter () {
1901         // Init output
1902         $OUT = '';
1903
1904         // Add them all together. This is maybe to simple
1905         foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1906                 // Add page part if set
1907                 if (isset($GLOBALS[$pagePart])) {
1908                         $OUT .= $GLOBALS[$pagePart];
1909                 } // END - if
1910         } // END - foreach
1911
1912         // Transfer $OUT to '__output'
1913         $GLOBALS['__output'] = $OUT;
1914 }
1915
1916 // Generates meta description for current module and 'what' value
1917 function generateMetaDescriptionCode () {
1918         // Only include from guest area and if ext-sql_patches has correct version
1919         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1920                 // Output it directly
1921                 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1922         } // END - if
1923
1924         // Initialize referral system
1925         initReferralSystem();
1926 }
1927
1928 // Generates an FQFN for template cache from the given template name
1929 function generateCacheFqfn ($prefix, $template) {
1930         // Is this cached?
1931         if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1932                 // Generate the FQFN
1933                 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1934                         '%s%s_compiled/%s/%s%s',
1935                         getPath(),
1936                         getCachePath(),
1937                         $prefix,
1938                         $template,
1939                         getCacheExtension()
1940                 );
1941         } // END - if
1942
1943         // Return it
1944         return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1945 }
1946
1947 // "Fixes" null or empty string to count of dashes
1948 function fixNullEmptyToDashes ($str, $num) {
1949         // Use str as default
1950         $return = $str;
1951
1952         // Is it empty?
1953         if ((is_null($str)) || (trim($str) == '')) {
1954                 // Set it
1955                 $return = str_repeat('-', $num);
1956         } // END - if
1957
1958         // Return final string
1959         return $return;
1960 }
1961
1962 // Translates the "pool type" into human-readable
1963 function translatePoolType ($type) {
1964         // Return "translation"
1965         return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1966 }
1967
1968 // "Translates" given time unit
1969 function translateTimeUnit ($unit) {
1970         // Default is unknown
1971         $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1972
1973         // "Detect" it
1974         if (!isset($GLOBALS['time_units'][$unit])) {
1975                 // Not found
1976                 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1977         } else {
1978                 // Translate it with generic function
1979                 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1980         }
1981
1982         // Return message
1983         return $message;
1984 }
1985
1986 // Displays given message in admin_settings_saved template
1987 function displayMessage ($message) {
1988         // Call inner function
1989         outputHtml(returnMessage($message));
1990 }
1991
1992 // Returns given message in admin_settings_saved template
1993 function returnMessage ($message) {
1994         // Load the template
1995         return loadTemplate('admin_settings_saved', TRUE, $message);
1996 }
1997
1998 // Displays given error message in admin_settings_unsaved template
1999 function displayErrorMessage ($message) {
2000         // Load the template
2001         outputHtml(returnErrorMessage($message));
2002 }
2003
2004 // Displays given error message in admin_settings_unsaved template
2005 function returnErrorMessage ($message) {
2006         // Load the template
2007         return loadTemplate('admin_settings_unsaved', TRUE, $message);
2008 }
2009
2010 // Generates a selection box for (maybe) given gender
2011 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
2012         // Start the HTML code
2013         $out  = '<select name="' . $fieldName . '" size="1" class="form_select">';
2014
2015         // Add options
2016         $out .= generateOptions(
2017                 '/ARRAY/',
2018                 array(
2019                         'M',
2020                         'F',
2021                         'C'
2022                 ), array(
2023                         '{--GENDER_M--}',
2024                         '{--GENDER_F--}',
2025                         '{--GENDER_C--}'
2026                 ),
2027                 $selectedGender
2028         );
2029
2030         // Finish HTML code
2031         $out .= '</select>';
2032
2033         // Return the code
2034         return $out;
2035 }
2036
2037 // Generates a selection box for given default value
2038 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2039         // Init variables
2040         $messageIds = array();
2041
2042         // Generate message id array
2043         foreach ($unitArray as $unit) {
2044                 // "Translate" it
2045                 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2046         } // END - foreach
2047
2048         // Start the HTML code
2049         $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2050
2051         // Add options
2052         $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2053
2054         // Finish HTML code
2055         $out .= '</select>';
2056
2057         // Return the code
2058         return $out;
2059 }
2060
2061 // Function to add style tag (whether display:none/block)
2062 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2063         // Is there foo_menu_javascript enabled?
2064         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2065                 // Silently abort here, not enabled
2066                 return '';
2067         } // END - if
2068
2069         // Is action=mainAction?
2070         if ($action == $mainAction) {
2071                 // Add "menu open" style
2072                 return ' style="display:block"';
2073         } else {
2074                 return ' style="display:none"';
2075         }
2076 }
2077
2078 // Function to add onclick attribute
2079 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2080         // Is there foo_menu_javascript enabled?
2081         if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2082                 // Silently abort here, not enabled
2083                 return '';
2084         } // END - if
2085
2086         // Prepare output
2087         $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2088
2089         // Return output
2090         return $OUT;
2091 }
2092
2093 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2094 function anonymizeSensitiveData ($data) {
2095         // Trim it
2096         $data = trim($data);
2097
2098         // Is it empty?
2099         if (empty($data)) {
2100                 // Then add three dashes
2101                 $data = '---';
2102         } elseif (isUrlValid($data)) {
2103                 // Is a referrer, so is it black-listed?
2104                 if (isAdmin()) {
2105                         // Is admin, has always priority
2106                         $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2107                 } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
2108                         // Yes, so replace it with text
2109                         $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2110                 } else {
2111                         // A  member is viewing this referral URL
2112                         $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2113                 }
2114         } elseif (isIp4AddressValid($data)) {
2115                 // Is an IPv4 address
2116                 $ipArray = explode('.', $data);
2117
2118                 // Only display first 2 octets
2119                 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2120         } else {
2121                 // Generic data
2122                 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2123         }
2124
2125         // Return it (hopefully) anonymized
2126         return $data;
2127 }
2128
2129 /**
2130  * Removes all comments, tabs and new-line characters to compact the content
2131  *
2132  * @param       $uncompactedContent             The uncompacted content
2133  * @return      $compactedContent               The compacted content
2134  */
2135 function compactContent ($uncompactedContent) {
2136         // First, remove all tab/new-line/revert characters
2137         $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2138
2139         // Make a space after >
2140         $compactedContent = str_replace(array('>', '  '), array('> ', ' '), $compactedContent);
2141
2142         // Then regex all comments like <!-- //--> away
2143         preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2144
2145         // Do we have entries?
2146         if (isset($matches[0][0])) {
2147                 // Remove all
2148                 foreach ($matches[0] as $match) {
2149                         // Remove the match
2150                         $compactedContent = str_replace($match, '', $compactedContent);
2151                 } // END - foreach
2152         } // END - if
2153
2154         // Return compacted content
2155         return $compactedContent;
2156 }
2157
2158 //-----------------------------------------------------------------------------
2159 //                     Template helper functions for EL code
2160 //-----------------------------------------------------------------------------
2161
2162 // Color-switch helper function
2163 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2164         // Is it there?
2165         if (!isset($GLOBALS['color_switch'][$templateName])) {
2166                 // Initialize it
2167                 initTemplateColorSwitch($templateName);
2168         } elseif ($clear === FALSE) {
2169                 // Switch color if called from loadTemplate()
2170                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2171                 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2172         }
2173
2174         // Return CSS class name
2175         if ($return === TRUE) {
2176                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2177                 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2178         } // END - if
2179 }
2180
2181 // Helper function for extension registration link
2182 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2183         // Default is all non-productive
2184         $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2185
2186         // Is the given extension non-productive?
2187         if (isExtensionDeprecated($ext_name)) {
2188                 // Is deprecated
2189                 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2190         } elseif (isExtensionProductive($ext_name)) {
2191                 // Productive code
2192                 $OUT = '<a title="{--ADMIN_TASK_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&amp;what=extensions&amp;register_ext=' . $ext_name . '%}">{--ADMIN_TASK_REGISTER_EXTENSION--}</a>';
2193         }
2194
2195         // Return code
2196         return $OUT;
2197 }
2198
2199 // Helper function to create bonus mail admin links
2200 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2201         // Call the inner function
2202         return generateAdminMailLinks('bonus', $bonusId);
2203 }
2204
2205 // Helper function to create member mail admin links
2206 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2207         // Call the inner function
2208         return generateAdminMailLinks('normal', $mailId);
2209 }
2210
2211 // Helper function to create a selection box for YES/NO configuration entries
2212 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2213         // Default is a "missing entry" warning
2214         $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2215
2216         // Generate the HTML code
2217         if (isConfigEntrySet($configEntry)) {
2218                 // Configuration entry is found
2219                 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2220 {%config,generateYesNoOptions=' . $configEntry . '%}
2221 </select>';
2222         } // END - if
2223
2224         // Return it
2225         return $OUT;
2226 }
2227
2228 // Helper function to create a selection box for YES/NO form fields
2229 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2230         // Generate the HTML code
2231         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2232 {%pipe,generateYesNoOptions%}
2233 </select>';
2234
2235         // Return it
2236         return $OUT;
2237 }
2238
2239 // Helper function to create a selection box for YES/NO form fields, by NO is default
2240 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2241         // Generate the HTML code
2242         $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2243 {%pipe,generateYesNoOptions=N%}
2244 </select>';
2245
2246         // Return it
2247         return $OUT;
2248 }
2249
2250 // Helper function to add extra content for guest area (module=index and others)
2251 function doTemplateGuestFooterExtras ($templateName, $clear) {
2252         // Init filter data
2253         $filterData = array(
2254                 // Name of used template
2255                 'template' => $templateName,
2256                 // Target array for gathered data
2257                 '__data'   => array(),
2258                 // Where the HTML output will go
2259                 '__output' => '',
2260         );
2261
2262         // Run the filter chain
2263         $filterData = runFilterChain('guest_footer_extras', $filterData);
2264
2265         // Return output
2266         return $filterData['__output'];
2267 }
2268
2269 // Helper function to add extra content for member area (module=login)
2270 function doTemplateMemberFooterExtras ($templateName, $clear) {
2271         // Is a member logged in?
2272         if (!isMember()) {
2273                 // This shall not happen
2274                 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2275         } // END - if
2276
2277         // Init filter data
2278         $filterData = array(
2279                 // Current user's id number
2280                 'userid'   => getMemberId(),
2281                 // Name of used template
2282                 'template' => $templateName,
2283                 // Target array for gathered data
2284                 '__data'   => array(),
2285                 // Where the HTML output will go
2286                 '__output' => '',
2287         );
2288
2289         // Run the filter chain
2290         $filterData = runFilterChain('member_footer_extras', $filterData);
2291
2292         // Return output
2293         return $filterData['__output'];
2294 }
2295
2296 /**
2297  * Helper function to determine whether current userid is set, if none is set,
2298  * return a zero, else an EL code is being returned as of this function is used
2299  * only in templates.
2300  *
2301  * @param       $templateName   Name of template (unused)
2302  * @param       $clear                  Wether to clear something (unused)
2303  * @return      $userId                 Wether zero or EL code snippet
2304  */
2305 function doTemplateUserId ($templateName, $clear) {
2306         // By default no userid is set
2307         $userId = '0';
2308
2309         // Is there a user id currently set?
2310         if (isCurrentUserIdSet()) {
2311                 // Then get the current user id
2312                 $userId = getCurrentUserId();
2313         } // END - if
2314
2315         // Return it
2316         return $userId;
2317 }
2318
2319 // Template helper function to generate "Terms&Conditions" link (EL code again)
2320 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2321         /*
2322          * Use default link by default ;-) This link, however, will become
2323          * deprecated once ext-terms is rolled out.
2324          */
2325         $linkCode = '{%url=modules.php?module=index&amp;what=agb%}';
2326
2327         // Is ext-terms installed?
2328         if (isExtensionInstalled('terms')) {
2329                 // Then use that link (only 'what' has changed)
2330                 $linkCode = '{%url=modules.php?module=index&amp;what=terms%}';
2331         } // END - if
2332
2333         // Return link (EL) code
2334         return $linkCode;
2335 }
2336
2337 // Template helper function to create selection box for "locked points mode"
2338 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2339         // Init array
2340         $lockedModes = array(
2341                 0 => array('mode' => 'LOCKED'),
2342                 1 => array('mode' => 'UNLOCKED'),
2343         );
2344
2345         // Handle it over to generateSelectionBoxFromArray()
2346         $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2347
2348         // Return prepared content
2349         return $content;
2350 }
2351
2352 // Template helper function to create selection box for payment method
2353 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2354         // Init array
2355         $paymentMethods = array(
2356                 0 => array('method' => 'DIRECT'),
2357                 1 => array('method' => 'REFERRAL'),
2358         );
2359
2360         // Handle it over to generateSelectionBoxFromArray()
2361         $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2362
2363         // Return prepared content
2364         return $content;
2365 }
2366
2367 // Template helper function to create a deferrer code if URL is not empty
2368 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2369         // Is the URL not NULL and not empty?
2370         if ((!is_null($url)) && (!empty($url))) {
2371                 // Set HTML with EL code
2372                 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2373         } // END - if
2374
2375         // Return URL (or content) or dashes if empty
2376         return fixEmptyContentToDashes($url);
2377 }
2378
2379 // Load another template and return its content
2380 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = array()) {
2381         // Load "the" template
2382         return loadTemplate($theTemplate, TRUE, $content);
2383 }
2384
2385 // Output HTML code for favicon.ico, if found
2386 function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
2387         // Default is not found
2388         $out = '';
2389
2390         // Check all common extensions
2391         foreach (array('ico', 'gif', 'png') as $extension) {
2392                 // Is the file there?
2393                 if (isFileReadable(getPath() . 'favicon.' . $extension)) {
2394                         // Then use this and abort
2395                         $out = '<link rel="shortcut icon" href="{%url=favicon.' . $extension . '%}" type="image/' . $extension . '" />';
2396                         break;
2397                 } // END - if
2398         } // END - while
2399
2400         // Return code
2401         return $out;
2402 }
2403
2404 // Helper function to display referral id or hide it depending on settings
2405 function doTemplateDisplayReferralIdContent ($template, $clear = FALSE) {
2406         // Ddisplay the refid or make it editable?
2407         if (isDisplayRefidEnabled()) {
2408                 // Load "hide" form template
2409                 $out = loadTemplate('guest_register_refid_hide', TRUE);
2410         } else {
2411                 // Load template to enter it
2412                 $out = loadTemplate('guest_register_refid', TRUE);
2413         }
2414
2415         // Return code
2416         return $out;
2417 }
2418
2419 // "Getter" for template base path
2420 function getTemplateBasePath ($part) {
2421         // Is there cache?
2422         if (!isset($GLOBALS[__FUNCTION__][$part])) {
2423                 // "Build" path
2424                 $GLOBALS[__FUNCTION__][$part] = sprintf('%stemplates/%s/%s', getPath(), getLanguage(), $part);
2425         } // END - if
2426
2427         // Return cache
2428         return $GLOBALS[__FUNCTION__][$part];
2429 }
2430
2431 // Removes comments with @DEPRECATED
2432 function removeDeprecatedComment ($output) {
2433         // Explode it into pieces ... ;)
2434         $lines = explode(chr(10), $output);
2435
2436         // Walk through all
2437         $return = '';
2438         foreach ($lines as $line) {
2439                 // Is there a @DEPRECATED?
2440                 if (isInString('@DEPRECATED', $line)) {
2441                         // Ignore this line
2442                         continue;
2443                 } // END - if
2444
2445                 // Add it
2446                 $return .= $line . chr(13);
2447         } // END - foreach
2448
2449         // Returned cleaned content
2450         return $return;
2451 }
2452
2453 // Generates a selection box suitable for e.g. birthdays: day, month and year
2454 function generateDayMonthYearSelectionBox ($day, $month, $year) {
2455         // This depends on selected language
2456         switch (getLanguage()) {
2457                 case 'de': // German date format
2458                         $content = addSelectionBox('da', $day) . addSelectionBox('mo', $month) . addSelectionBox('ye', $year);
2459                         break;
2460
2461                 default: // Default is the US date format... :)
2462                         $content = addSelectionBox('mo', $month) . addSelectionBox('da', $day) . addSelectionBox('ye', $year);
2463                         break;
2464         } // END - switch
2465
2466         // Return content
2467         return $content;
2468 }
2469
2470 // [EOF]
2471 ?>