2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 04/04/2009 *
4 * =================== Last change: 04/04/2009 *
6 * -------------------------------------------------------------------- *
7 * File : template-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Template functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Template-Funktionen *
12 * -------------------------------------------------------------------- *
13 * Copyright (c) 2003 - 2009 by Roland Haeder *
14 * Copyright (c) 2009 - 2016 by Mailer Developer Team *
15 * For more information visit: http://mxchange.org *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the Free Software *
29 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
31 ************************************************************************/
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
38 // Wrapper until we merged to the EL branch
39 function preCompileCode ($code, $full = TRUE) {
40 return compileCode($code, $full);
43 // Setter for 'is_template_html'
44 function enableTemplateHtml ($enable = TRUE) {
45 $GLOBALS['is_template_html'] = (bool) $enable;
48 // Checks whether the template is HTML or not by previously set flag
50 function isTemplateHtml () {
51 // Is the output_mode other than 0 (HTML), then no comments are enabled
52 if (!isHtmlOutputMode()) {
57 return $GLOBALS['is_template_html'];
61 // Wrapper for writing debug informations to the browser
62 function debugOutput ($message) {
63 outputHtml('<div class="debug_message">' . $message . '</div>');
66 // "Fixes" an empty string into three dashes (use for templates)
67 function fixEmptyContentToDashes ($str) {
68 // Call inner function
69 $str = fixNullEmptyToDashes($str, 3);
76 function initTemplateColorSwitch ($template) {
77 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
78 $GLOBALS['color_switch'][$template] = 2;
81 // "Getter" for color switch code
82 function getColorSwitchCode ($template) {
84 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', FALSE, FALSE) . {DQUOTE}";
90 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
91 function outputHtml ($htmlCode = NULL, $newLine = TRUE) {
93 if (!isset($GLOBALS['__output'])) {
94 $GLOBALS['__output'] = '';
97 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getOutputMode()=' . getOutputMode() . ',htmlCode(length)=' . strlen($htmlCode) . ',output(length)=' . strlen($GLOBALS['__output']));
98 // Is there HTML-Code here?
99 if ((!is_null($htmlCode)) && (!empty($htmlCode))) {
100 // Yes, so we handle it as you have configured
101 switch (getOutputMode()) {
103 // But if PHP is caching, then we don't need to do that
104 if (getPhpCaching() == 'on') {
105 // Output into PHP's internal buffer
106 outputRawCode($htmlCode);
108 // That's why you don't need any \n at the end of your HTML code... :-)
109 if ($newLine === TRUE) {
110 outputRawCode(PHP_EOL);
113 // Render mode for old or lame servers...
114 $GLOBALS['__output'] .= $htmlCode;
116 // That's why you don't need any \n at the end of your HTML code... :-)
117 if ($newLine === TRUE) {
118 $GLOBALS['__output'] .= PHP_EOL;
124 // If we are switching from 'render' to 'direct' mode, all data in '__output' must be flushed and cleared
125 if ((!empty($GLOBALS['__output'])) && (getPhpCaching() != 'on')) {
126 outputRawCode($GLOBALS['__output']);
127 $GLOBALS['__output'] = '';
130 // The same as above... ^
131 outputRawCode($htmlCode);
132 if ($newLine === TRUE) {
133 outputRawCode(PHP_EOL);
138 // Huh, something goes wrong or maybe you have edited config.php ???
139 reportBug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
142 } elseif ((getPhpCaching() == 'on') && (!isFilledArray($GLOBALS['http_header'])) && (!isRawOutputMode())) {
143 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getPhpCaching()=' . getPhpCaching() . ',isset(http_header)=' . intval(isset($GLOBALS['http_header'])) . ',getScriptOutputMode()=' . getScriptOutputMode() . '');
144 // Output cached HTML code
145 $GLOBALS['__output'] = ob_get_contents();
147 // Clear output buffer for later output if output is found
148 if (!empty($GLOBALS['__output'])) {
152 // Send all HTTP headers
155 // Compile and run finished rendered HTML code
156 compileFinalOutput();
158 // Output code here, DO NOT REMOVE! ;-)
159 outputRawCode($GLOBALS['__output']);
160 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['__output'])) && (!isRawOutputMode())) {
161 // Send all HTTP headers
164 // Compile and run finished rendered HTML code
165 compileFinalOutput();
167 // Output code here, DO NOT REMOVE! ;-)
168 outputRawCode($GLOBALS['__output']);
170 // And flush all headers
175 // Compiles the final output
176 function compileFinalOutput () {
177 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ',getScriptOutputMode()=' . getScriptOutputMode() . ' - ENTERED!');
178 // Is this function called?
179 if (isset($GLOBALS[__FUNCTION__])) {
181 reportBug(__FUNCTION__, __LINE__, 'Double call of ' . __FUNCTION__ . ' causes problems with sent headers.');
184 // Mark this function as called
185 $GLOBALS[__FUNCTION__] = TRUE;
187 // Add page header and footer
188 addPageHeaderFooter();
189 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ' - After addPageHeaderFooter() call.');
191 // Do the final (general) compilation
192 $GLOBALS['__output'] = doFinalCompilation($GLOBALS['__output']);
194 // Compile any other things out
195 $GLOBALS['__output'] = compileUriCode($GLOBALS['__output']);
197 // Extension 'rewrite' installed?
198 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
199 $GLOBALS['__output'] = rewriteLinksInCode($GLOBALS['__output']);
204 * @TODO On some pages this is buggy
205 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
206 // Compress it for HTTP gzip
207 $GLOBALS['__output'] = gzencode($GLOBALS['__output'], 9);
210 addHttpHeader('Content-Encoding: gzip');
211 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
212 // Compress it for HTTP deflate
213 $GLOBALS['__output'] = gzcompress($GLOBALS['__output'], 9);
216 addHttpHeader('Content-Encoding: deflate');
221 addHttpHeader('Content-Length: ' . strlen($GLOBALS['__output']));
227 // Main compilation loop
228 function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE) {
229 // Code must not be an array (happens in installer)
230 assert(!is_array($code));
232 // Insert comments? (Only valid with HTML templates, of course)
233 enableTemplateHtml($insertComments);
236 $totalCompilations = 0;
239 while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($totalCompilations < 7)) {
240 // Init common variables
245 //* DEBUG: */ debugOutput('<pre>'.lineNumberCode($code).'</pre>');
246 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code[]=' . gettype($code) . ',enableCodes[]=' . gettype($enableCodes));
247 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), $enableCodes)) . '";';
248 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.lineNumberCode($eval).'</pre>');
250 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.lineNumberCode($newContent).'</pre>');
251 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
253 // Was that eval okay?
254 if (empty($newContent)) {
255 // Something went wrong!
256 reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . lineNumberCode($eval) . '</pre>', FALSE);
262 // Compile the final code if insertComments is true
263 if ($insertComments == TRUE) {
264 // ... because SQL queries shall keep OPEN_CONFIG and such in
265 $code = compileRawCode($code);
269 $totalCompilations++;
272 // Add debugging data in HTML code, if mode is enabled
273 if ((isDebugModeEnabled()) && ($insertComments === TRUE) && (isHtmlOutputMode())) {
275 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isDebugModeEnabled()=' . intval(isDebugModeEnabled()) . ',insertComments=' . intval($insertComments) . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()));
276 $code .= '<!-- Total compilation loop=' . $totalCompilations . ' //-->';
279 // Return the compiled code
283 // Output the raw HTML code
284 function outputRawCode ($htmlCode) {
285 // Output stripped HTML code to avoid broken JavaScript code, etc.
286 print(str_replace('{BACK}', chr(92), $htmlCode));
288 // Flush the output if only getPhpCaching() is not 'on'
289 if (getPhpCaching() != 'on') {
295 // Load a template file and return it's content (only it's name; do not use ' or ")
296 function loadTemplate ($template, $return = FALSE, $content = [], $compileCode = TRUE) {
297 // @TODO Remove these sanity checks if all is fine
298 if (!is_bool($return)) {
299 // $return has to be boolean
300 reportBug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
301 } elseif (!is_string($template)) {
302 // $template has to be string
303 reportBug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
306 // Init returned content
307 $templateContent = '';
309 // Set current template
310 $GLOBALS['current_template'] = $template;
313 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('html', $template))) {
314 // Evaluate the cache
315 $templateContent = readTemplateCache('html', $template, $content);
317 // Better remove array element which is only needed in uncached mode
318 unset($GLOBALS['template_eval']['html'][$template]);
319 } elseif (!isset($GLOBALS['template_eval']['html'][$template])) {
320 // Make all template names lowercase
321 $template = strtolower($template);
324 $basePath = getTemplateBasePath('html');
325 $extraPath = detectExtraTemplatePath('html', $template);
328 $FQFN = $basePath . '/' . $extraPath . $template . '.tpl';
329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Template ' . $template . ' is solved to FQFN=' . $FQFN);
331 // Does the special template exists?
332 if (!isFileReadable($FQFN)) {
333 // Reset to default template
334 $FQFN = $basePath . '/' . $template . '.tpl';
337 // Now does the final template exists?
338 if (isFileReadable($FQFN)) {
339 // Count the template load
340 incrementConfigEntry('num_templates');
342 // The local file does exists so we load it. :)
343 $GLOBALS['template_content']['html'][$template] = readFromFile($FQFN);
345 // Is there to compile the code?
346 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]))) {
347 // Normal HTML output?
348 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
349 // Add surrounding HTML comments to help finding bugs faster
350 $code = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
352 // Prepare eval() command
353 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
354 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($code), TRUE, $compileCode) . '";';
355 } elseif (substr($template, 0, 3) == 'js_') {
356 // JavaScripts don't like entities, dollar signs and timings
357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
358 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]) . '");';
359 } elseif (isAjaxOutputMode()) {
360 // AJAX (JSON content)
361 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
362 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]) . '";';
364 // Prepare eval() command, other output doesn't like entities, maybe
365 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
366 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
368 } elseif (isHtmlOutputMode()) {
369 // Add surrounding HTML comments to help finding bugs faster
370 $templateContent = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
371 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
372 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($templateContent), TRUE, $compileCode) . '";';
373 } elseif (isAjaxOutputMode()) {
374 // AJAX (JSON content)
375 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
376 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]) . '";';
379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
380 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]) . '");';
382 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
383 // Only admins shall see this warning or when installation mode is active
384 $templateContent = sprintf('<div class="para">
391 {--TEMPLATE_CONTENT--}:
395 print_r($content, TRUE)
399 $GLOBALS['template_eval']['html'][$template] = '404';
404 if ((isset($GLOBALS['template_eval']['html'][$template])) && ($GLOBALS['template_eval']['html'][$template] != '404')) {
406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
407 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['html'][$template]).'</pre>');
408 eval($GLOBALS['template_eval']['html'][$template]);
409 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
412 // Is there some content to output or return?
413 if ((empty($templateContent)) && (isDebugModeEnabled())) {
414 // Warning, empty output!
415 return 'E:' . $template . ',content=<pre>' . print_r($content, TRUE) . '</pre>';
418 // Not empty so let's put it out! ;)
419 if ($return === TRUE) {
420 // Return the HTML code
421 return $templateContent;
424 outputHtml($templateContent);
428 // Detects the extra template path from given template name
429 function detectExtraTemplatePath ($prefix, $template) {
434 if (!isset($GLOBALS['extra_path'][$prefix][$template])) {
435 // Check for admin/guest/member/etc. templates
436 if (substr($template, 0, 6) == 'admin_') {
437 // Admin template found
438 $extraPath = 'admin/';
439 } elseif (substr($template, 0, 6) == 'guest_') {
440 // Guest template found
441 $extraPath = 'guest/';
442 } elseif (substr($template, 0, 7) == 'member_') {
443 // Member template found
444 $extraPath = 'member/';
445 } elseif (substr($template, 0, 7) == 'select_') {
446 // Selection template found
447 $extraPath = 'select/';
448 } elseif (substr($template, 0, 8) == 'install_') {
449 // Installation template found
450 $extraPath = 'install/';
451 } elseif (substr($template, 0, 4) == 'ext_') {
452 // Extension template found
454 } elseif (substr($template, 0, 3) == 'la_') {
455 // 'Logical-area' template found
457 } elseif (substr($template, 0, 3) == 'js_') {
458 // JavaScript template found
460 } elseif (substr($template, 0, 5) == 'menu_') {
461 // Menu template found
462 $extraPath = 'menu/';
464 // Test for extension
465 $test = substr($template, 0, strpos($template, '_'));
467 // Probe for valid extension name
468 if (isExtensionNameValid($test)) {
469 // Set extra path to extension's name
470 $extraPath = $test . '/';
475 $GLOBALS['extra_path'][$prefix][$template] = $extraPath;
479 return $GLOBALS['extra_path'][$prefix][$template];
482 // Loads an email template and compiles it
483 function loadEmailTemplate ($template, $content = [], $userid = NULL, $loadUserData = TRUE) {
484 // Make sure all template names are lowercase!
485 $template = strtolower($template);
487 // Set current template
488 $GLOBALS['current_template'] = $template;
490 // Is content an array?
491 if (is_array($content)) {
492 // Add expiration to array
493 if ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
494 // Will never expire!
495 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
496 } elseif ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge'))) {
497 // Create nice date string
498 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
501 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
506 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('email', $template))) {
507 // Evaluate the cache
508 $templateContent = readTemplateCache('email', $template, $content);
510 // Better remove array element which is need only in uncached mode
511 unset($GLOBALS['template_eval']['email'][$template]);
512 } elseif (!isset($GLOBALS['template_eval']['email'][$template])) {
514 $basePath = getTemplateBasePath('emails');
517 $extraPath = detectExtraTemplatePath('email', $template);
519 // Generate full FQFN
520 $FQFN = $basePath . '/' . $extraPath . $template . '.tpl';
522 // Does the special template exists?
523 if (!isFileReadable($FQFN)) {
524 // Reset to default template
525 $FQFN = $basePath . '/' . $template . '.tpl';
528 // Now does the final template exists?
529 $templateContent = '';
530 if (isFileReadable($FQFN)) {
531 // The local file does exists so we load it. :)
532 $GLOBALS['template_content']['email'][$template] = readFromFile($FQFN);
535 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
536 $GLOBALS['template_eval']['email'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['email'][$template])) . '");';
537 } elseif (!empty($template)) {
538 // Template file not found
539 $templateContent = '<div class="para">
540 {--TEMPLATE_404--}: ' . $template . '
543 {--TEMPLATE_CONTENT--}:
544 <pre>' . print_r($content, TRUE) . '</pre>
547 // Don't cache this, as there is no template to cache
548 $GLOBALS['template_eval']['email'][$template] = '404';
550 // Debug mode not active? Then remove the HTML tags
551 if (!isDebugModeEnabled()) {
553 $templateContent = secureString($templateContent);
556 // No template name supplied!
557 $templateContent = '{--NO_TEMPLATE_SUPPLIED--}';
558 $GLOBALS['template_eval']['email'][$template] = '404';
562 // Is there something to eval?
563 if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
565 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
566 //* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
567 //* DEBUG: */ die('<pre>'.print_r($content, TRUE).'</pre><pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
568 eval($GLOBALS['template_eval']['email'][$template]);
569 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
572 // Are there some content?
573 if (empty($templateContent)) {
575 $templateContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
577 // Add last error if the required function exists
578 if (function_exists('error_get_last')) {
579 // Add last error and some lines for better overview
580 $templateContent .= "\n--------------------------------------\nDebug:\n" . print_r(error_get_last(), TRUE) . "--------------------------------------\nPlease don't alter these informations!\nThanx.";
584 // Remove content and data
588 return $templateContent;
591 // "Getter" for menu CSS classes, mainly used in templates
592 function getMenuCssClasses ($data) {
593 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
596 if (!isset($GLOBALS[__FUNCTION__][$data])) {
597 // $data needs to be converted into an array
598 $content = explode('|', $data);
600 // Non-existent index 2 will happen in menu blocks
601 if (!isset($content[2])) {
605 // Re-construct the array: 0=visible,1=locked,2=prefix
606 $content['visible'] = $content[0];
607 $content['locked'] = $content[1];
609 // Call our "translator" function
610 $content = translateMenuVisibleLocked($content, $content[2]);
613 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
617 return $GLOBALS[__FUNCTION__][$data];
620 // Generate XHTML code for the CAPTCHA
621 function generateCaptchaCode ($code, $type, $urlId, $userid) {
622 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&' . $type . '=' . $urlId . '&do=img&code=' . $code . '%}" />';
625 // Compiles the given HTML/mail code
626 function compileCode ($code, $full = TRUE, $compileCode = TRUE) {
627 // Is the code a string or should we not compile?
628 if ((!is_string($code)) || ($compileCode === FALSE)) {
629 // Silently return it
634 $startCompile = microtime(TRUE);
637 $code = compileRawCode($code, $full, $compileCode);
640 $compilationTime = $startCompile - microtime(TRUE);
642 // Add timing if enabled
643 if (isTemplateHtml()) {
644 // Add timing, this should be disabled in
645 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
648 // Return compiled code
653 function compileRawCode ($code, $full = TRUE, $compileCode = TRUE) {
654 //* DIE: */ reportBug(__FUNCTION__, __LINE__, 'Called with ' . strlen($code) . ' code length.');
655 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called with code()=' . strlen($code) . ',full=' . intval($full) . ',compileCode=' . intval($compileCode));
657 // Is the code a string or shall we not compile?
658 if ((!is_string($code)) || ($compileCode === FALSE)) {
659 // Silently return it
660 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code[]= ' . gettype($code) . ' is not a string or compileCode(' . intval($compileCode) . ') is FALSE.');
664 // Init replacement-array with smaller set of security characters
665 $secChars = $GLOBALS['url_chars'];
667 // Select full set of chars to replace when we e.g. want to compile URLs
668 if ($full === TRUE) {
669 $secChars = $GLOBALS['security_chars'];
672 // First compile these chars
673 array_unshift($secChars['to'] , '{--' , '--}');
674 array_unshift($secChars['from'], '{%message,', '%}' );
676 // Replace QUOT and other non-HTML codes
677 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
678 $code = str_replace($secChars['to'], $secChars['from'], $code);
679 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
681 // Compile the prepared code through a filter chain
682 $code = runFilterChain('compile_code', $code);
684 // Find all $content[bla][blub] entries
685 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
686 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
688 // Are some matches found?
689 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
690 // Replace all matches
692 foreach ($matches[0] as $key => $match) {
693 // Fuzzy look has failed by default
696 // "Cache" match length
697 $matchLength = strlen($match);
699 // Fuzzy look on match if already found
700 foreach ($matchesFound as $found => $set) {
702 $test = substr($found, 0, $matchLength);
704 // Does this entry exist?
705 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
706 if ($test == $match) {
708 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
715 if ($fuzzyFound === TRUE) {
719 // Take all string elements
720 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
721 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
722 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
723 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
724 $code = str_replace($match, '".' . $newMatch . '."', $code);
725 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
726 $matchesFound[$match] = TRUE;
727 } elseif (!isset($matchesFound[$match])) {
729 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
730 $code = str_replace($match, '".' . $match . '."', $code);
731 $matchesFound[$match] = 1;
733 // Everthing else should be a least logged
734 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
740 * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
741 * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
742 * therefore the variable's value won't be inserted. This is why
743 * {COMPILE_DOLLAR} is being used in above loop and at the end of this
744 * function being replace with the original dollar sign again.
746 preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
748 // Are some matches found?
749 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
750 // Scan all matches for not $content
751 foreach ($matches[0] as $match) {
753 $match = trim($match);
756 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
758 // Is the first part not $content/$userid and not empty?
759 // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
760 if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
761 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
762 // Then replace $ with {DOLLAR}
763 $matchSecured = str_replace('$', '{DOLLAR}', $match);
765 // And in $code as well
766 $code = str_replace($match, $matchSecured, $code);
771 // Add 'COMPILE_DOLLAR' again
772 array_push($secChars['to'] , '{COMPILE_DOLLAR}');
773 array_push($secChars['from'], '$');
775 // Replace QUOT and other non-HTML codes
776 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
777 $code = str_replace($secChars['to'], $secChars['from'], $code);
778 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
781 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Exiting with code()=' . strlen($code));
786 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select', $allSteps = FALSE) {
790 // This is a yes/no selection only!
791 if (isValidId($id)) $prefix .= '[' . $id . ']';
792 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
794 // Begin with regular selection box here
795 if (!empty($prefix)) $prefix .= '_';
797 if (isValidId($id)) $type2 .= '[' . $id . ']';
798 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
806 // Use configured min age or fixed?
807 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
809 $startYear = $year - getMinAge();
812 $startYear = $year - 16;
815 // Calculate earliest year (100 years old people can still enter Internet???)
816 $minYear = $year - 100;
818 // Check if the default value is larger than minimum and bigger than actual year
819 if (($default > $minYear) && ($default >= $year)) {
820 for ($idx = $year; $idx < ($year + 11); $idx++) {
821 $OUT .= '<option value="' . $idx . '"';
822 if ($default == $idx) $OUT .= ' selected="selected"';
823 $OUT .= '>' . $idx . '</option>';
825 } elseif ($default == -1) {
826 // Current year minus 1
827 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
828 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
831 // Get current year and subtract the configured minimum age
832 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
834 // Construct year selection list
835 for ($idx = $minYear; $idx <= $startYear; $idx++) {
836 $OUT .= '<option value="' . $idx . '"';
837 if ($default == $idx) $OUT .= ' selected="selected"';
838 $OUT .= '>' . $idx . '</option>';
844 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
845 $OUT .= '<option value="' . $idx . '"';
846 if ($default == $idx) $OUT .= ' selected="selected"';
847 $OUT .= '>' . $descr . '</option>';
851 case 'mn': // Months, numeric
852 for ($idx = 0; $idx <= 12; $idx++) {
853 $OUT .= '<option value="' . $idx . '"';
854 if ($default == $idx) $OUT .= ' selected="selected"';
855 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
860 for ($idx = 0; $idx <= 4; $idx++) {
861 $OUT .= ' <option value="' . $idx . '"';
862 if ($default == $idx) $OUT .= ' selected="selected"';
863 $OUT .= '>' . $idx . '</option>';
868 for ($idx = 0; $idx <= 31; $idx++) {
869 $OUT .= '<option value="' . $idx . '"';
870 if ($default == $idx) $OUT .= ' selected="selected"';
871 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
876 for ($idx = 0; $idx <= 23; $idx++) {
877 $padded = padLeftZero($idx, 2);
878 $OUT .= '<option value="' . $padded . '"';
879 if ($default == $padded) $OUT .= ' selected="selected"';
880 $OUT .= '>' . $padded . '</option>';
884 case 'mi': // Minutes
885 case 'se': // Seconds
886 // Default is 5 minutes/seconds step
890 if ($allSteps === TRUE) {
895 for ($idx = 0; $idx <= 59; $idx += $step) {
896 $padded = padLeftZero($idx, 2);
897 $OUT .= '<option value="' . $padded . '"';
898 if ($default == $padded) $OUT .= ' selected="selected"';
899 $OUT .= '>' . $padded . '</option>';
904 $OUT .= '<option value="Y"';
905 if ($default == 'Y') $OUT .= ' selected="selected"';
906 $OUT .= '>{--YES--}</option><option value="N"';
907 if ($default != 'Y') $OUT .= ' selected="selected"';
908 $OUT .= '>{--NO--}</option>';
911 default: // Not detected
912 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' . $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
919 // Insert the code in $img_code into jpeg or PNG image
920 function generateImageOrCode ($img_code, $headerSent = TRUE) {
921 // Is the code size oversized or shouldn't we display it?
922 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
923 // Stop execution of function here because of over-sized code length
924 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
925 } elseif ($headerSent === FALSE) {
926 // Return an HTML code here
927 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
931 $img = sprintf('%s/theme/%s/images/code_bg.%s',
938 if (isFileReadable($img)) {
940 switch (getImgType()) {
941 case 'jpg': // Okay, load image and hide all errors
942 $image = imagecreatefromjpeg($img);
945 case 'png': // Okay, load image and hide all errors
946 $image = imagecreatefrompng($img);
950 // Silently log the error
951 logDebugMessage(__FUNCTION__, __LINE__, sprintf('File for image-type %s in theme %s not found.', getImgType(), getCurrentTheme()));
955 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
956 $text_color = imagecolorallocate($image, 0, 0, 0);
958 // Insert code into image
959 imagestring($image, 5, 14, 2, $img_code, $text_color);
962 setContentType('image/' . getImgType());
964 // Output image with matching image factory
965 switch (getImgType()) {
966 case 'jpg': imagejpeg($image); break;
967 case 'png': imagepng($image); break;
970 // Remove image from memory
971 imagedestroy($image);
974 // Create selection box or array of splitted timestamp
975 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE, $allSteps = FALSE) {
976 // Do not continue if ONE_DAY is absend
977 if (!isConfigEntrySet('ONE_DAY')) {
979 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
982 // Calculate 2-seconds timestamp
983 $stamp = round($timestamp);
984 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
986 // Is there a leap year?
988 $TEST = getYear() / 4;
990 $M2 = getMonth(time() + $timestamp);
992 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
993 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
994 $SWITCH = getOneDay();
997 // First of all years...
998 $year = abs(floor($timestamp / (31536000 + $SWITCH)));
999 //* DEBUG: */ debugOutput('year=' . $year);
1001 $month = abs(floor($timestamp / 2628000 - $year * 12));
1002 //* DEBUG: */ debugOutput('month=' . $month);
1004 $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
1005 //* DEBUG: */ debugOutput('week=' . $week);
1007 $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
1008 //* DEBUG: */ debugOutput('day=' . $day);
1010 $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
1011 //* DEBUG: */ debugOutput('hour=' . $hour);
1013 $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));
1014 //* DEBUG: */ debugOutput('minute=' . $minute);
1015 // And at last seconds...
1016 $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));
1017 //* DEBUG: */ debugOutput('second=' . $second);
1019 // Is seconds zero and time is < 60 seconds?
1020 if (($second < 1) && ($timestamp < 60)) {
1022 $second = round($timestamp);
1025 // Put all calculated values in array
1037 // Now we convert them in seconds...
1039 if ($asArray === TRUE) {
1040 // Just put data array out
1045 // Time unit -> field name
1046 'unit_field' => array(
1055 // Time unit -> label
1056 'unit_label' => array(
1068 $OUT = '<div align="' . $align . '">';
1069 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1072 // "Walk" through all units
1073 foreach ($units['unit_field'] as $unit => $field) {
1074 // Is this displayed or zero?
1075 if (isInString($unit, $display) || (empty($display))) {
1076 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1077 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1081 // Close table row and open new one
1085 // "Walk" through all units again
1086 foreach ($units['unit_field'] as $unit => $field) {
1088 if (isInString($unit, $display) || (empty($display))) {
1089 // Generate year selection
1090 $OUT .= '<td align="center">';
1091 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select', $allSteps);
1094 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1104 // Return generated HTML code or data array
1108 // Generate a list of administrative links to a given userid
1109 function generateMemberAdminActionLinks ($userid) {
1110 // Make sure userid is a number
1111 if ($userid != bigintval($userid)) {
1112 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1115 // Define all main targets
1116 $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1119 $status = getFetchedUserData('userid', $userid, 'status');
1121 // Begin of navigation links
1124 foreach ($targetArray as $target) {
1125 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $target . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1126 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1127 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1128 // Locked accounts shall be unlocked
1129 $OUT .= 'UNLOCK_USER';
1130 } elseif ($target == 'del_user') {
1131 // @TODO Deprecate this thing
1132 $OUT .= 'DELETE_USER';
1134 // All other status is fine
1135 $OUT .= strtoupper($target);
1137 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1138 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1139 // Locked accounts shall be unlocked
1140 $OUT .= 'UNLOCK_USER';
1141 } elseif ($target == 'del_user') {
1142 // @TODO Deprecate this thing
1143 $OUT .= 'DELETE_USER';
1145 // All other status is fine
1146 $OUT .= strtoupper($target);
1148 $OUT .= '--}</a></span>|';
1151 // Add special link, in case of the account is unconfirmed
1152 if ($status == 'UNCONFIRMED') {
1154 $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>|';
1157 // Finish navigation link
1158 $OUT = substr($OUT, 0, -1) . ']';
1164 // Generate an email link
1165 function generateEmailLink ($email, $table = 'admins') {
1166 // Default email link (INSECURE! Spammer can read this by harvester programs)
1167 $EMAIL = 'mailto:' . $email;
1169 // Check for several extensions
1170 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1171 // Create email link for contacting admin in guest area
1172 $EMAIL = generateAdminEmailLink($email);
1173 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1174 // Create email link for contacting a member within admin area (or later in other areas, too?)
1175 $EMAIL = generateUserEmailLink($email);
1176 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1177 // Create email link to contact sponsor within admin area (or like the link above?)
1178 $EMAIL = generateSponsorEmailLink($email);
1181 // Return email link
1186 * Outputs an error message in a "fashioned way" to the user, by putting it into
1187 * a nice looking web page, if one of HTML or CSS output mode is active.
1189 * Please use reportBug() instead of this function. reportBug() has more helpful
1190 * functionality like logging and admin notification (which you can configure
1191 * through your admin area).
1193 * @param $file Function or file basename where the error came from
1194 * @param $line Line number where the error came from
1195 * @param $message Message which shall be output to web
1198 function app_exit ($file, $line, $message) {
1199 // Check if Script is already dieing and not let it kill itself another 1000 times
1200 if (isset($GLOBALS['app_died'])) {
1201 // Script tried to kill itself twice
1202 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $file . ', line=' . $line);
1205 // Make sure, that the script realy realy diese here and now
1206 $GLOBALS['app_died'] = TRUE;
1208 // Is this AJAX mode?
1209 if (isAjaxOutputMode()) {
1210 // Set content type as application/json
1211 setContentType('application/json');
1213 // Set content type as text/html
1214 setContentType('text/html');
1220 // Rewrite message for output
1222 getMessage('MAILER_HAS_DIED'),
1228 // Is this AJAX mode again
1229 if (isAjaxOutputMode()) {
1230 // Load the message template
1231 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1233 // Output it as JSON encoded
1234 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation(compileRawCode($OUT))))));
1236 // Load the message template
1237 loadTemplate('app_exit_message', FALSE, $message);
1244 // Display parsing time and number of SQL queries in footer
1245 function displayParsingTime () {
1246 // Is the timer started?
1247 if (!isset($GLOBALS['__start_time'])) {
1253 $endTime = microtime(TRUE);
1255 // "Explode" both times
1256 $start = explode(' ', $GLOBALS['__start_time']);
1257 $end = explode(' ', $endTime);
1258 $runTime = $end[0] - $start[0];
1264 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1266 'run_time' => $runTime,
1267 'sql_time' => (getConfig('sql_time') * 1000),
1270 // Load the template
1271 $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1273 // Is debug enabled?
1274 if (isDebugModeEnabled()) {
1275 // Log loading of total includes
1276 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
1281 * Outputs an error message and backtrace to the user, by default a mail with
1282 * all relevant data is being mailed to the configured administrators.
1284 * This function shall be used "publicly" because of logging, admin notification
1285 * and double-call prevention (see first if() block) instead of app_exit().
1286 * app_exit() is more a "private" function and will only output a bug message to
1287 * the user, no email and no logging.
1289 * @param $file Function or file basename where the error came from
1290 * @param $line Line number where the error came from
1291 * @param $sendEmail Wether to send an email to all configured administrators
1294 function reportBug ($file, $line, $message = '', $sendEmail = TRUE) {
1295 // Is this already called?
1296 if (isset($GLOBALS[__FUNCTION__])) {
1298 print '[' . $file . ':' . $line . ':] ' . __FUNCTION__ . '() has already died! Message:' . $message . '<br />Backtrace:<pre>';
1299 debug_print_backtrace();
1303 // Set HTTP status to 500 (e.g. for AJAX requests)
1304 setHttpStatus('500 Internal Server Error');
1306 // Mark this function as called
1307 $GLOBALS[__FUNCTION__] = TRUE;
1312 // Is the optional message set?
1313 if (!empty($message)) {
1315 $debug = sprintf("Note: %s<br />\n",
1319 // @TODO Add a little more infos here
1320 logDebugMessage($file, $line, strip_tags($message));
1324 $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>';
1325 $debug .= debug_get_printable_backtrace();
1327 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1328 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1330 // Send an email? (e.g. not wanted for evaluation errors)
1331 if (($sendEmail === TRUE) && (!isInstaller()) && (isAdminRegistered())) {
1334 'message' => trim($message),
1335 'backtrace' => trim(debug_get_mailable_backtrace())
1338 // Send email to webmaster
1339 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1342 // Is there HTML/CSS/AJAX mode while debug-mode is enabled?
1343 if (((isDebugModeEnabled()) || (isInstaller())) && ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode()))) {
1345 app_exit($file, $line, $debug);
1346 } elseif (isAjaxOutputMode()) {
1347 // Load include (again?)
1348 loadIncludeOnce('inc/ajax-functions.php');
1353 // Set HTTP status to 500 again
1354 setHttpStatus('500 Internal Server Error');
1356 // Is AJAX output mode, then output message as JSON
1357 setAjaxReplyContent($debug);
1359 // Send it out to browser
1360 sendAjaxContent(TRUE);
1365 // Raw/image output mode and all other modes doesn't work well with text ...
1370 // Compile characters which are allowed in URLs
1371 function compileUriCode ($code, $simple = TRUE) {
1373 $test = trim($code);
1377 // Then abort here and return the original code
1381 // Compile these by default
1382 $charsCompile = array(
1407 // Compile constants
1408 if ($simple === FALSE) {
1410 array_unshift($charsCompile['from'], '{--', '--}');
1413 array_unshift($charsCompile['to'], '".', '."');
1416 // Compile QUOT and other non-HTML codes
1417 $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1418 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1420 // Return compiled code
1424 // Handle message codes from URL
1425 function handleCodeMessage () {
1427 if (isGetRequestElementSet('code')) {
1428 // Default extension is 'unknown'
1431 // Is extension given?
1432 if (isGetRequestElementSet('ext')) {
1433 $ext = getRequestElement('ext');
1436 // Convert the 'code' parameter from URL to a human-readable message
1437 $message = getMessageFromErrorCode(getRequestElement('code'));
1439 // Load message template
1440 loadTemplate('message', FALSE, $message);
1444 // Generates a 'extension foo out-dated' message
1445 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1446 // Is the extension empty?
1447 if (empty($ext_name)) {
1448 // This should not happen
1449 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1453 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1455 // Is an admin logged in?
1457 // Then output admin message
1458 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1461 // Return prepared message
1465 // Generates a 'extension foo inactive' message
1466 function generateExtensionInactiveMessage ($ext_name) {
1467 // Is the extension empty?
1468 if (empty($ext_name)) {
1469 // This should not happen
1470 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1474 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1476 // Is an admin logged in?
1478 // Then output admin message
1479 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1482 // Return prepared message
1486 // Generates a 'extension foo not installed' message
1487 function generateExtensionNotInstalledMessage ($ext_name) {
1488 // Is the extension empty?
1489 if (empty($ext_name)) {
1490 // This should not happen
1491 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1495 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1497 // Is an admin logged in?
1499 // Then output admin message
1500 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1503 // Return prepared message
1507 // Generates a message depending on if the extension is not installed or not
1509 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1513 // Is the extension not installed or just deactivated?
1514 switch (isExtensionInstalled($ext_name)) {
1515 case TRUE; // Deactivated!
1516 $message = generateExtensionInactiveMessage($ext_name);
1519 case FALSE; // Not installed!
1520 $message = generateExtensionNotInstalledMessage($ext_name);
1523 default: // Should not happen!
1524 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid state of extension %s detected.', $ext_name));
1525 $message = sprintf('Invalid state of extension %s detected.', $ext_name);
1529 // Return the message
1533 // Print code with line numbers
1534 function lineNumberCode ($code) {
1535 // By default copy the code
1538 if (!is_array($code)) {
1539 // We need an array, so try it with the new-line character
1540 $codeE = explode(PHP_EOL, $code);
1543 $count_lines = count($codeE);
1545 $r = 'Line | Code:<br />';
1546 foreach ($codeE as $line => $c) {
1547 $r .= '<div class="line"><span class="linenum">';
1548 if ($count_lines == 1) {
1551 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1556 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1559 return '<div class="code">' . $r . '</div>';
1562 // Determines the right page title
1563 function determinePageTitle () {
1567 // Config and database connection valid?
1568 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1569 // Title decoration enabled?
1570 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1571 $pageTitle .= '{%config,trim=title_left%} ';
1574 // Is there an extra title?
1575 if (isExtraTitleSet()) {
1577 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1581 $pageTitle .= '{?MAIN_TITLE?}';
1583 // Add title of module? (middle decoration will also be added!)
1584 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1585 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1588 // Get menu mode from module
1589 $menuMode = getMenuModeFromModule();
1591 // Add middle part (always in admin area!)
1592 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1593 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1596 // Add title decorations? (right)
1597 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1598 $pageTitle .= ' {%config,trim=title_right%}';
1600 } elseif ((isInstalled()) && (isAdminRegistered())) {
1601 // Installed, admin registered but no ext-sql_patches
1602 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1603 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1604 // Installed but no admin registered
1605 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1606 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1607 // Installation mode
1608 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1610 // Configuration not found
1611 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1613 // Do not add the fatal message in installation mode
1614 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1615 // Please report this
1616 reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1621 return decodeEntities($pageTitle);
1624 // Checks whethere there is a cache file there. This function is cached.
1625 function isTemplateCached ($prefix, $template) {
1626 // Is there cached this result?
1627 if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1629 $FQFN = generateCacheFqfn($prefix, $template);
1632 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1636 return $GLOBALS['template_cache'][$prefix][$template];
1639 // Flushes non-flushed template cache to disk
1640 function flushTemplateCache ($prefix, $template, $eval) {
1641 // Is this cache flushed?
1642 if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1644 $FQFN = generateCacheFqfn($prefix, $template);
1646 // Compile code another round for better performance and preserve $ signs
1647 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1649 // Is this a XML template?
1650 if ($prefix == 'xml') {
1651 // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1652 $eval = compactContent($eval);
1656 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1660 // Reads a template cache
1661 function readTemplateCache ($prefix, $template, $content) {
1663 if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1664 // This should not happen
1665 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1669 if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1671 $FQFN = generateCacheFqfn($prefix, $template);
1676 * WARNING: Do not replace this include() call with loadInclude() as it
1677 * would hide local variables away which is here required to make this
1682 // Is the template cache valid?
1683 if (!isset($templateContent)) {
1684 // Please clear your cache!
1685 reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1690 return $templateContent;
1693 // Escapes quotes (default is only double-quotes)
1694 function escapeQuotes ($str, $single = FALSE) {
1695 // Should we escape all?
1696 if ($single === TRUE) {
1697 // Escape all (including null)
1698 $str = addslashes($str);
1700 // Replace all chars at once
1701 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1704 // Return the escape'd string
1708 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1709 function escapeJavaScriptQuotes ($str) {
1710 // Replace all double-quotes and secure back-ticks
1711 $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1717 // Send out mails depending on the 'mod/modes' combination
1718 // @TODO Lame description for this function
1719 function sendModeMails ($mod, $modes) {
1721 $content = array ();
1724 if (fetchUserData(getMemberId())) {
1725 // Extract salt from cookie
1726 $salt = substr(getSession('u_hash'), 0, -40);
1728 // Now let's compare passwords
1729 $hash = encodeHashForCookie(getUserData('password'));
1731 // Does the hash match or should we change it?
1732 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1734 $content = getUserDataArray();
1736 // Clear/init the content variable
1737 $content['message'] = '';
1740 // @TODO Move this in a filter
1743 foreach ($modes as $mode) {
1745 case 'normal': break; // Do not add any special lines
1746 case 'email': // Email was changed!
1747 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1750 case 'password': // Password was changed
1751 $content['message'] = '{--MEMBER_CHANGED_PASSWORD--}' . PHP_EOL;
1755 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown mode %s detected.', $mode));
1756 $content['message'] = '{%message,MEMBER_UNKNOWN_MODE=' . $mode . '%}' . PHP_EOL . PHP_EOL;
1761 if (isExtensionActive('country')) {
1762 // Replace code with description
1763 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1766 // Merge content with data from POST
1767 $content = merge_array($content, postRequestArray());
1770 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1772 if (isAdminNotificationEnabled()) {
1773 // The admin needs to be notified about a profile change
1774 $message_admin = 'admin_mydata_notify';
1775 $subjectAdmin = '{--ADMIN_CHANGED_DATA_SUBJECT--}';
1778 $message_admin = '';
1782 // Set subject lines
1783 $subjectMember = '{--MEMBER_CHANGED_DATA--}';
1785 // Output success message
1786 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1789 default: // Unsupported module!
1790 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unsupported module %s detected.', $mod));
1791 $content['message'] = '<span class="bad">{%message,UNKNOWN_MODULE=' . $mod . '%}</span>';
1795 // Passwords mismatch
1796 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1799 // Could not load profile
1800 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1803 // Send email to user if required
1804 if ((!empty($subjectMember)) && (!empty($message)) && (!empty($content['userid']))) {
1806 sendEmail($content['userid'], $subjectMember, $message);
1809 // Send only if no other error has occured
1810 if ((!empty($subjectAdmin)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1812 sendAdminNotification($subjectAdmin, $message_admin, $content, getMemberId());
1813 } elseif (isAdminNotificationEnabled()) {
1814 // Cannot send mails to admin!
1815 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1818 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1822 displayMessage($content['message']);
1825 // Generates a 'selection box' from given array
1826 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1827 // options must be an array
1828 assert(is_array($options));
1833 // Use default value as array key?
1834 if ($useDefaultAsArray === TRUE) {
1836 $addKey = '[' . convertNullToZero($default) . ']';
1840 $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1841 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1844 if ($allowNone === TRUE) {
1846 $OUT .= '<option value="">{--SELECT_NONE--}</option>';
1849 // Walk through all options
1850 foreach ($options as $option) {
1851 // Default 'default' is not set
1852 $option['default'] = '';
1854 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1855 // Is default value same as given value?
1856 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default === $option[$optionKey])) {
1858 $option['default'] = ' selected="selected"';
1861 // Is 'nameElement' set?
1862 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1863 // Then set this as extraName, but lower-case
1864 $extraName = '_' . strtolower($option[$nameElement]);
1867 // Add the <option> entry from ...
1868 if (empty($optionContent)) {
1869 // Is a template name given?
1870 if (empty($templateName)) {
1871 // ... $name template
1872 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1874 // ... $templateName template
1875 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1878 // ... direct HTML code
1879 $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1883 // Finish selection box
1884 $OUT .= '</select>';
1888 'selection_box' => $OUT,
1891 // Load template and return it
1892 if (empty($templateName)) {
1893 // Use name from $name + $extraName
1894 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1896 // Use name from $templateName + $extraName
1897 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1901 // Prepares the header for HTML output
1902 function loadHtmlHeader () {
1905 * 1.) pre_page_header (mainly loads the page_header template and includes
1908 runFilterChain('pre_page_header');
1911 * Here can be something be added, but normally one of the two filters
1912 * around this line should do the job for you.
1916 * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1917 * to close the head-tag)
1918 * Include more header data here
1920 runFilterChain('post_page_header');
1923 // Adds page header and footer to output array element
1924 function addPageHeaderFooter () {
1928 // Add them all together. This is maybe to simple
1929 foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1930 // Add page part if set
1931 if (isset($GLOBALS[$pagePart])) {
1932 $OUT .= $GLOBALS[$pagePart];
1936 // Transfer $OUT to '__output'
1937 $GLOBALS['__output'] = $OUT;
1940 // Generates meta description for current module and 'what' value
1941 function generateMetaDescriptionCode () {
1942 // Only include from guest area and if ext-sql_patches has correct version
1943 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1944 // Output it directly
1945 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1948 // Initialize referral system
1949 initReferralSystem();
1952 // Generates an FQFN for template cache from the given template name
1953 function generateCacheFqfn ($prefix, $template) {
1955 if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1956 // Generate the FQFN
1957 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1958 '%s%s_compiled/%s/%s%s',
1968 return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1971 // "Fixes" null or empty string to count of dashes
1972 function fixNullEmptyToDashes ($str, $num) {
1973 // Use str as default
1977 if ((is_null($str)) || (trim($str) == '')) {
1979 $return = str_repeat('-', $num);
1982 // Return final string
1986 // Translates the "pool type" into human-readable
1987 function translatePoolType ($type) {
1988 // Return "translation"
1989 return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1992 // "Translates" given time unit
1993 function translateTimeUnit ($unit) {
1994 // Default is unknown
1995 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1998 if (!isset($GLOBALS['time_units'][$unit])) {
2000 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
2002 // Translate it with generic function
2003 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
2010 // Displays given message in admin_settings_saved template
2011 function displayMessage ($message) {
2012 // Call inner function
2013 outputHtml(returnMessage($message));
2016 // Returns given message in admin_settings_saved template
2017 function returnMessage ($message) {
2018 // Load the template
2019 return loadTemplate('admin_settings_saved', TRUE, $message);
2022 // Displays given error message in admin_settings_unsaved template
2023 function displayErrorMessage ($message) {
2024 // Load the template
2025 outputHtml(returnErrorMessage($message));
2028 // Displays given error message in admin_settings_unsaved template
2029 function returnErrorMessage ($message) {
2030 // Load the template
2031 return loadTemplate('admin_settings_unsaved', TRUE, $message);
2034 // Generates a selection box for (maybe) given gender
2035 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
2036 // Start the HTML code
2037 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2040 $out .= generateOptions(
2055 $out .= '</select>';
2061 // Generates a selection box for given default value
2062 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2066 // Generate message id array
2067 foreach ($unitArray as $unit) {
2069 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2072 // Start the HTML code
2073 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2076 $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2079 $out .= '</select>';
2085 // Function to add style tag (whether display:none/block)
2086 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2087 // Is there foo_menu_javascript enabled?
2088 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2089 // Silently abort here, not enabled
2093 // Is action=mainAction?
2094 if ($action == $mainAction) {
2095 // Add "menu open" style
2096 return ' style="display:block"';
2098 return ' style="display:none"';
2102 // Function to add onclick attribute
2103 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2104 // Is there foo_menu_javascript enabled?
2105 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2106 // Silently abort here, not enabled
2111 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2117 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2118 function anonymizeSensitiveData ($data) {
2120 $data = trim($data);
2124 // Then add three dashes
2126 } elseif (isUrlValid($data)) {
2127 // Is a referrer, so is it black-listed?
2129 // Is admin, has always priority
2130 $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2131 } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
2132 // Yes, so replace it with text
2133 $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2135 // A member is viewing this referral URL
2136 $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2138 } elseif (isIp4AddressValid($data)) {
2139 // Is an IPv4 address
2140 $ipArray = explode('.', $data);
2142 // Only display first 2 octets
2143 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2146 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2149 // Return it (hopefully) anonymized
2154 * Removes all comments, tabs and new-line characters to compact the content
2156 * @param $uncompactedContent The uncompacted content
2157 * @return $compactedContent The compacted content
2159 function compactContent ($uncompactedContent) {
2160 // First, remove all tab/new-line/revert characters
2161 $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2163 // Make a space after >
2164 $compactedContent = str_replace(array('>', ' '), array('> ', ' '), $compactedContent);
2166 // Then regex all comments like <!-- //--> away
2167 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2169 // Do we have entries?
2170 if (isset($matches[0][0])) {
2172 foreach ($matches[0] as $match) {
2174 $compactedContent = str_replace($match, '', $compactedContent);
2178 // Return compacted content
2179 return $compactedContent;
2182 //-----------------------------------------------------------------------------
2183 // Template helper functions for EL code
2184 //-----------------------------------------------------------------------------
2186 // Color-switch helper function
2187 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2189 if (!isset($GLOBALS['color_switch'][$templateName])) {
2191 initTemplateColorSwitch($templateName);
2192 } elseif ($clear === FALSE) {
2193 // Switch color if called from loadTemplate()
2194 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2195 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2198 // Return CSS class name
2199 if ($return === TRUE) {
2200 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2201 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2205 // Helper function for extension registration link
2206 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2207 // Default is all non-productive
2208 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2210 // Is the given extension non-productive?
2211 if (isExtensionDeprecated($ext_name)) {
2213 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2214 } elseif (isExtensionProductive($ext_name)) {
2216 $OUT = '<a title="{--ADMIN_TASK_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&register_ext=' . $ext_name . '%}">{--ADMIN_TASK_REGISTER_EXTENSION--}</a>';
2223 // Helper function to create bonus mail admin links
2224 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2225 // Call the inner function
2226 return generateAdminMailLinks('bonus', $bonusId);
2229 // Helper function to create member mail admin links
2230 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2231 // Call the inner function
2232 return generateAdminMailLinks('normal', $mailId);
2235 // Helper function to create a selection box for YES/NO configuration entries
2236 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2237 // Default is a "missing entry" warning
2238 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2240 // Generate the HTML code
2241 if (isConfigEntrySet($configEntry)) {
2242 // Configuration entry is found
2243 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2244 {%config,generateYesNoOptions=' . $configEntry . '%}
2252 // Helper function to create a selection box for YES/NO form fields
2253 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2254 // Generate the HTML code
2255 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2256 {%pipe,generateYesNoOptions%}
2263 // Helper function to create a selection box for YES/NO form fields, by NO is default
2264 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2265 // Generate the HTML code
2266 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2267 {%pipe,generateYesNoOptions=N%}
2274 // Helper function to add extra content for guest area (module=index and others)
2275 function doTemplateGuestFooterExtras ($templateName, $clear) {
2277 $filterData = array(
2278 // Name of used template
2279 'template' => $templateName,
2280 // Target array for gathered data
2282 // Where the HTML output will go
2286 // Run the filter chain
2287 $filterData = runFilterChain('guest_footer_extras', $filterData);
2290 return $filterData['__output'];
2293 // Helper function to add extra content for member area (module=login)
2294 function doTemplateMemberFooterExtras ($templateName, $clear) {
2295 // Is a member logged in?
2297 // This shall not happen
2298 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2302 $filterData = array(
2303 // Current user's id number
2304 'userid' => getMemberId(),
2305 // Name of used template
2306 'template' => $templateName,
2307 // Target array for gathered data
2309 // Where the HTML output will go
2313 // Run the filter chain
2314 $filterData = runFilterChain('member_footer_extras', $filterData);
2317 return $filterData['__output'];
2321 * Helper function to determine whether current userid is set, if none is set,
2322 * return a zero, else an EL code is being returned as of this function is used
2323 * only in templates.
2325 * @param $templateName Name of template (unused)
2326 * @param $clear Wether to clear something (unused)
2327 * @return $userId Wether zero or EL code snippet
2329 function doTemplateUserId ($templateName, $clear) {
2330 // By default no userid is set
2333 // Is there a user id currently set?
2334 if (isCurrentUserIdSet()) {
2335 // Then get the current user id
2336 $userId = getCurrentUserId();
2343 // Template helper function to generate "Terms&Conditions" link (EL code again)
2344 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2346 * Use default link by default ;-) This link, however, will become
2347 * deprecated once ext-terms is rolled out.
2349 $linkCode = '{%url=modules.php?module=index&what=agb%}';
2351 // Is ext-terms installed?
2352 if (isExtensionInstalled('terms')) {
2353 // Then use that link (only 'what' has changed)
2354 $linkCode = '{%url=modules.php?module=index&what=terms%}';
2357 // Return link (EL) code
2361 // Template helper function to create selection box for "locked points mode"
2362 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2364 $lockedModes = array(
2365 0 => array('mode' => 'LOCKED'),
2366 1 => array('mode' => 'UNLOCKED'),
2369 // Handle it over to generateSelectionBoxFromArray()
2370 $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2372 // Return prepared content
2376 // Template helper function to create selection box for payment method
2377 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2379 $paymentMethods = array(
2380 0 => array('method' => 'DIRECT'),
2381 1 => array('method' => 'REFERRAL'),
2384 // Handle it over to generateSelectionBoxFromArray()
2385 $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2387 // Return prepared content
2391 // Template helper function to create a deferrer code if URL is not empty
2392 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2393 // Is the URL not NULL and not empty?
2394 if ((!is_null($url)) && (!empty($url))) {
2395 // Set HTML with EL code
2396 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2399 // Return URL (or content) or dashes if empty
2400 return fixEmptyContentToDashes($url);
2403 // Load another template and return its content
2404 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = []) {
2405 // Load "the" template
2406 return loadTemplate($theTemplate, TRUE, $content);
2409 // Output HTML code for favicon.ico, if found
2410 function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
2411 // Default is not found
2414 // Check all common extensions
2415 foreach (array('ico', 'gif', 'png') as $extension) {
2416 // Is the file there?
2417 if (isFileReadable(getPath() . 'favicon.' . $extension)) {
2418 // Then use this and abort
2419 $out = '<link rel="shortcut icon" href="{%url=favicon.' . $extension . '%}" type="image/' . $extension . '" />';
2428 // Helper function to display referral id or hide it depending on settings
2429 function doTemplateDisplayReferralIdContent ($template, $clear = FALSE) {
2430 // Ddisplay the refid or make it editable?
2431 if (isDisplayRefidEnabled()) {
2432 // Load "hide" form template
2433 $out = loadTemplate('guest_register_refid_hide', TRUE);
2435 // Load template to enter it
2436 $out = loadTemplate('guest_register_refid', TRUE);
2443 // "Getter" for template base path
2444 function getTemplateBasePath ($part) {
2446 if (!isset($GLOBALS[__FUNCTION__][$part])) {
2448 $GLOBALS[__FUNCTION__][$part] = sprintf('%stemplates/%s/%s', getPath(), getLanguage(), $part);
2452 return $GLOBALS[__FUNCTION__][$part];
2455 // Removes comments with @DEPRECATED
2456 function removeDeprecatedComment ($output) {
2457 // Explode it into pieces ... ;)
2458 $lines = explode(chr(10), $output);
2462 foreach ($lines as $line) {
2463 // Is there a @DEPRECATED?
2464 if (isInString('@DEPRECATED', $line)) {
2470 $return .= $line . chr(13);
2473 // Returned cleaned content
2477 // Generates a selection box suitable for e.g. birthdays: day, month and year
2478 function generateDayMonthYearSelectionBox ($day, $month, $year) {
2479 // This depends on selected language
2480 switch (getLanguage()) {
2481 case 'de': // German date format
2482 $content = addSelectionBox('da', $day) . addSelectionBox('mo', $month) . addSelectionBox('ye', $year);
2485 default: // Default is the US date format... :)
2486 $content = addSelectionBox('mo', $month) . addSelectionBox('da', $day) . addSelectionBox('ye', $year);
2494 // Loads page header
2495 function loadPageHeader () {
2497 $GLOBALS['__page_header'] = '';
2499 // Is the header already sent?
2500 if (($GLOBALS['__header_sent'] != 1) && ($GLOBALS['__header_sent'] != 2)) {
2501 // Set default HTTP status to "200 OK"
2502 setHttpStatus('200 OK');
2504 // If not in CSS mode generate the header
2505 if ((!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode())) {
2506 // Prepare the header for HTML output
2511 if ($GLOBALS['__header_sent'] == '0') {
2512 $GLOBALS['__header_sent'] = 1;
2516 // Add BODY tag or not?
2517 // @TODO Find a way to not use direct module comparison
2518 if ((!isCssOutputMode()) && (!isRawOutputMode()) && ($GLOBALS['__header_sent'] == 1) && (getModule() != 'frametester') && (!isFramesetModeEnabled())) {
2519 loadTemplate('page_body');
2520 $GLOBALS['__header_sent'] = 2;
2524 // Loads page footer and calls doShutdown()
2525 function loadPageFooter () {
2527 $GLOBALS['__page_footer'] = '';
2529 // Footer disabled (e.g. CSS/AJAX/image output) or already sent?
2530 // 1234 5 54 45 5 5 543 3 443 3 443 3 44321
2531 if ((((!isset($GLOBALS['__footer_sent'])) || (($GLOBALS['__footer_sent'] != 1) && ($GLOBALS['__footer_sent'] != 2))) && (!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode()))) {
2532 // Run the filter, sweet huh?
2533 runFilterChain('page_footer');
2536 $GLOBALS['__page_footer'] .= loadTemplate('page_footer', TRUE);
2539 // Footer has been reached
2540 $GLOBALS['__footer_sent'] = 1;