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