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 - 2013 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 = array(), $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 = '<div class="para">
391 {--TEMPLATE_CONTENT--}:
392 <pre>' . print_r($content, TRUE) . '</pre>
396 $GLOBALS['template_eval']['html'][$template] = '404';
401 if ((isset($GLOBALS['template_eval']['html'][$template])) && ($GLOBALS['template_eval']['html'][$template] != '404')) {
403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
404 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['html'][$template]).'</pre>');
405 eval($GLOBALS['template_eval']['html'][$template]);
406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
409 // Is there some content to output or return?
410 if ((empty($templateContent)) && (isDebugModeEnabled())) {
411 // Warning, empty output!
412 return 'E:' . $template . ',content=<pre>' . print_r($content, TRUE) . '</pre>';
415 // Not empty so let's put it out! ;)
416 if ($return === TRUE) {
417 // Return the HTML code
418 return $templateContent;
421 outputHtml($templateContent);
425 // Detects the extra template path from given template name
426 function detectExtraTemplatePath ($prefix, $template) {
431 if (!isset($GLOBALS['extra_path'][$prefix][$template])) {
432 // Check for admin/guest/member/etc. templates
433 if (substr($template, 0, 6) == 'admin_') {
434 // Admin template found
435 $extraPath = 'admin/';
436 } elseif (substr($template, 0, 6) == 'guest_') {
437 // Guest template found
438 $extraPath = 'guest/';
439 } elseif (substr($template, 0, 7) == 'member_') {
440 // Member template found
441 $extraPath = 'member/';
442 } elseif (substr($template, 0, 7) == 'select_') {
443 // Selection template found
444 $extraPath = 'select/';
445 } elseif (substr($template, 0, 8) == 'install_') {
446 // Installation template found
447 $extraPath = 'install/';
448 } elseif (substr($template, 0, 4) == 'ext_') {
449 // Extension template found
451 } elseif (substr($template, 0, 3) == 'la_') {
452 // 'Logical-area' template found
454 } elseif (substr($template, 0, 3) == 'js_') {
455 // JavaScript template found
457 } elseif (substr($template, 0, 5) == 'menu_') {
458 // Menu template found
459 $extraPath = 'menu/';
461 // Test for extension
462 $test = substr($template, 0, strpos($template, '_'));
464 // Probe for valid extension name
465 if (isExtensionNameValid($test)) {
466 // Set extra path to extension's name
467 $extraPath = $test . '/';
472 $GLOBALS['extra_path'][$prefix][$template] = $extraPath;
476 return $GLOBALS['extra_path'][$prefix][$template];
479 // Loads an email template and compiles it
480 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = TRUE) {
481 // Make sure all template names are lowercase!
482 $template = strtolower($template);
484 // Set current template
485 $GLOBALS['current_template'] = $template;
487 // Is content an array?
488 if (is_array($content)) {
489 // Add expiration to array
490 if ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
491 // Will never expire!
492 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
493 } elseif ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge'))) {
494 // Create nice date string
495 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
498 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
503 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('email', $template))) {
504 // Evaluate the cache
505 $templateContent = readTemplateCache('email', $template, $content);
507 // Better remove array element which is need only in uncached mode
508 unset($GLOBALS['template_eval']['email'][$template]);
509 } elseif (!isset($GLOBALS['template_eval']['email'][$template])) {
511 $basePath = getTemplateBasePath('emails');
514 $extraPath = detectExtraTemplatePath('email', $template);
516 // Generate full FQFN
517 $FQFN = $basePath . '/' . $extraPath . $template . '.tpl';
519 // Does the special template exists?
520 if (!isFileReadable($FQFN)) {
521 // Reset to default template
522 $FQFN = $basePath . '/' . $template . '.tpl';
525 // Now does the final template exists?
526 $templateContent = '';
527 if (isFileReadable($FQFN)) {
528 // The local file does exists so we load it. :)
529 $GLOBALS['template_content']['email'][$template] = readFromFile($FQFN);
532 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
533 $GLOBALS['template_eval']['email'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['email'][$template])) . '");';
534 } elseif (!empty($template)) {
535 // Template file not found
536 $templateContent = '<div class="para">
537 {--TEMPLATE_404--}: ' . $template . '
540 {--TEMPLATE_CONTENT--}:
541 <pre>' . print_r($content, TRUE) . '</pre>
544 // Don't cache this, as there is no template to cache
545 $GLOBALS['template_eval']['email'][$template] = '404';
547 // Debug mode not active? Then remove the HTML tags
548 if (!isDebugModeEnabled()) {
550 $templateContent = secureString($templateContent);
553 // No template name supplied!
554 $templateContent = '{--NO_TEMPLATE_SUPPLIED--}';
555 $GLOBALS['template_eval']['email'][$template] = '404';
559 // Is there something to eval?
560 if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
563 //* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
564 //* DEBUG: */ die('<pre>'.print_r($content, TRUE).'</pre><pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
565 eval($GLOBALS['template_eval']['email'][$template]);
566 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
569 // Are there some content?
570 if (empty($templateContent)) {
572 $templateContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
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.";
581 // Remove content and data
585 return $templateContent;
588 // "Getter" for menu CSS classes, mainly used in templates
589 function getMenuCssClasses ($data) {
590 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
593 if (!isset($GLOBALS[__FUNCTION__][$data])) {
594 // $data needs to be converted into an array
595 $content = explode('|', $data);
597 // Non-existent index 2 will happen in menu blocks
598 if (!isset($content[2])) {
602 // Re-construct the array: 0=visible,1=locked,2=prefix
603 $content['visible'] = $content[0];
604 $content['locked'] = $content[1];
606 // Call our "translator" function
607 $content = translateMenuVisibleLocked($content, $content[2]);
610 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
614 return $GLOBALS[__FUNCTION__][$data];
617 // Generate XHTML code for the CAPTCHA
618 function generateCaptchaCode ($code, $type, $urlId, $userid) {
619 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&' . $type . '=' . $urlId . '&do=img&code=' . $code . '%}" />';
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
631 $startCompile = microtime(TRUE);
634 $code = compileRawCode($code, $full, $compileCode);
637 $compilationTime = $startCompile - microtime(TRUE);
639 // Add timing if enabled
640 if (isTemplateHtml()) {
641 // Add timing, this should be disabled in
642 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
645 // Return compiled code
650 function compileRawCode ($code, $full = TRUE, $compileCode = TRUE) {
651 //* DIE: */ reportBug(__FUNCTION__, __LINE__, 'Called with ' . strlen($code) . ' code length.');
652 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called with code()=' . strlen($code) . ',full=' . intval($full) . ',compileCode=' . intval($compileCode));
654 // Is the code a string or shall we not compile?
655 if ((!is_string($code)) || ($compileCode === FALSE)) {
656 // Silently return it
657 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code[]= ' . gettype($code) . ' is not a string or compileCode(' . intval($compileCode) . ') is FALSE.');
661 // Init replacement-array with smaller set of security characters
662 $secChars = $GLOBALS['url_chars'];
664 // Select full set of chars to replace when we e.g. want to compile URLs
665 if ($full === TRUE) {
666 $secChars = $GLOBALS['security_chars'];
669 // First compile these chars
670 array_unshift($secChars['to'] , '{--' , '--}');
671 array_unshift($secChars['from'], '{%message,', '%}' );
673 // Replace QUOT and other non-HTML codes
674 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
675 $code = str_replace($secChars['to'], $secChars['from'], $code);
676 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
678 // Compile the prepared code through a filter chain
679 $code = runFilterChain('compile_code', $code);
681 // Find all $content[bla][blub] entries
682 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
683 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
685 // Are some matches found?
686 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
687 // Replace all matches
688 $matchesFound = array();
689 foreach ($matches[0] as $key => $match) {
690 // Fuzzy look has failed by default
693 // "Cache" match length
694 $matchLength = strlen($match);
696 // Fuzzy look on match if already found
697 foreach ($matchesFound as $found => $set) {
699 $test = substr($found, 0, $matchLength);
701 // Does this entry exist?
702 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
703 if ($test == $match) {
705 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
712 if ($fuzzyFound === TRUE) {
716 // Take all string elements
717 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
718 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
719 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
720 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
721 $code = str_replace($match, '".' . $newMatch . '."', $code);
722 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
723 $matchesFound[$match] = TRUE;
724 } elseif (!isset($matchesFound[$match])) {
726 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
727 $code = str_replace($match, '".' . $match . '."', $code);
728 $matchesFound[$match] = 1;
730 // Everthing else should be a least logged
731 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
737 * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
738 * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
739 * therefore the variable's value won't be inserted. This is why
740 * {COMPILE_DOLLAR} is being used in above loop and at the end of this
741 * function being replace with the original dollar sign again.
743 preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
745 // Are some matches found?
746 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
747 // Scan all matches for not $content
748 foreach ($matches[0] as $match) {
750 $match = trim($match);
753 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
755 // Is the first part not $content/$userid and not empty?
756 // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
757 if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
758 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
759 // Then replace $ with {DOLLAR}
760 $matchSecured = str_replace('$', '{DOLLAR}', $match);
762 // And in $code as well
763 $code = str_replace($match, $matchSecured, $code);
768 // Add 'COMPILE_DOLLAR' again
769 array_push($secChars['to'] , '{COMPILE_DOLLAR}');
770 array_push($secChars['from'], '$');
772 // Replace QUOT and other non-HTML codes
773 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
774 $code = str_replace($secChars['to'], $secChars['from'], $code);
775 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
778 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Exiting with code()=' . strlen($code));
783 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select') {
787 // This is a yes/no selection only!
788 if (isValidId($id)) $prefix .= '[' . $id . ']';
789 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
791 // Begin with regular selection box here
792 if (!empty($prefix)) $prefix .= '_';
794 if (isValidId($id)) $type2 .= '[' . $id . ']';
795 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
803 // Use configured min age or fixed?
804 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
806 $startYear = $year - getMinAge();
809 $startYear = $year - 16;
812 // Calculate earliest year (100 years old people can still enter Internet???)
813 $minYear = $year - 100;
815 // Check if the default value is larger than minimum and bigger than actual year
816 if (($default > $minYear) && ($default >= $year)) {
817 for ($idx = $year; $idx < ($year + 11); $idx++) {
818 $OUT .= '<option value="' . $idx . '"';
819 if ($default == $idx) $OUT .= ' selected="selected"';
820 $OUT .= '>' . $idx . '</option>';
822 } elseif ($default == -1) {
823 // Current year minus 1
824 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
825 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
828 // Get current year and subtract the configured minimum age
829 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
831 // Construct year selection list
832 for ($idx = $minYear; $idx <= $startYear; $idx++) {
833 $OUT .= '<option value="' . $idx . '"';
834 if ($default == $idx) $OUT .= ' selected="selected"';
835 $OUT .= '>' . $idx . '</option>';
841 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
842 $OUT .= '<option value="' . $idx . '"';
843 if ($default == $idx) $OUT .= ' selected="selected"';
844 $OUT .= '>' . $descr . '</option>';
848 case 'mn': // Months, numeric
849 for ($idx = 0; $idx <= 12; $idx++) {
850 $OUT .= '<option value="' . $idx . '"';
851 if ($default == $idx) $OUT .= ' selected="selected"';
852 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
857 for ($idx = 0; $idx <= 4; $idx++) {
858 $OUT .= ' <option value="' . $idx . '"';
859 if ($default == $idx) $OUT .= ' selected="selected"';
860 $OUT .= '>' . $idx . '</option>';
865 for ($idx = 0; $idx <= 31; $idx++) {
866 $OUT .= '<option value="' . $idx . '"';
867 if ($default == $idx) $OUT .= ' selected="selected"';
868 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
873 for ($idx = 0; $idx <= 23; $idx++) {
874 $padded = padLeftZero($idx, 2);
875 $OUT .= '<option value="' . $padded . '"';
876 if ($default == $padded) $OUT .= ' selected="selected"';
877 $OUT .= '>' . $padded . '</option>';
881 case 'mi': // Minutes
882 case 'se': // Seconds
883 for ($idx = 0; $idx <= 59; $idx+=5) {
884 $padded = padLeftZero($idx, 2);
885 $OUT .= '<option value="' . $padded . '"';
886 if ($default == $padded) $OUT .= ' selected="selected"';
887 $OUT .= '>' . $padded . '</option>';
892 $OUT .= '<option value="Y"';
893 if ($default == 'Y') $OUT .= ' selected="selected"';
894 $OUT .= '>{--YES--}</option><option value="N"';
895 if ($default != 'Y') $OUT .= ' selected="selected"';
896 $OUT .= '>{--NO--}</option>';
899 default: // Not detected
900 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' . $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
907 // Insert the code in $img_code into jpeg or PNG image
908 function generateImageOrCode ($img_code, $headerSent = TRUE) {
909 // Is the code size oversized or shouldn't we display it?
910 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
911 // Stop execution of function here because of over-sized code length
912 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
913 } elseif ($headerSent === FALSE) {
914 // Return an HTML code here
915 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
919 $img = sprintf('%s/theme/%s/images/code_bg.%s',
926 if (isFileReadable($img)) {
928 switch (getImgType()) {
929 case 'jpg': // Okay, load image and hide all errors
930 $image = imagecreatefromjpeg($img);
933 case 'png': // Okay, load image and hide all errors
934 $image = imagecreatefrompng($img);
938 // Silently log the error
939 logDebugMessage(__FUNCTION__, __LINE__, sprintf('File for image-type %s in theme %s not found.', getImgType(), getCurrentTheme()));
943 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
944 $text_color = imagecolorallocate($image, 0, 0, 0);
946 // Insert code into image
947 imagestring($image, 5, 14, 2, $img_code, $text_color);
950 setContentType('image/' . getImgType());
952 // Output image with matching image factory
953 switch (getImgType()) {
954 case 'jpg': imagejpeg($image); break;
955 case 'png': imagepng($image); break;
958 // Remove image from memory
959 imagedestroy($image);
962 // Create selection box or array of splitted timestamp
963 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE) {
964 // Do not continue if ONE_DAY is absend
965 if (!isConfigEntrySet('ONE_DAY')) {
967 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
970 // Calculate 2-seconds timestamp
971 $stamp = round($timestamp);
972 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
974 // Is there a leap year?
976 $TEST = getYear() / 4;
978 $M2 = getMonth(time() + $timestamp);
980 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
981 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
982 $SWITCH = getOneDay();
985 // First of all years...
986 $year = abs(floor($timestamp / (31536000 + $SWITCH)));
987 //* DEBUG: */ debugOutput('year=' . $year);
989 $month = abs(floor($timestamp / 2628000 - $year * 12));
990 //* DEBUG: */ debugOutput('month=' . $month);
992 $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
993 //* DEBUG: */ debugOutput('week=' . $week);
995 $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
996 //* DEBUG: */ debugOutput('day=' . $day);
998 $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
999 //* DEBUG: */ debugOutput('hour=' . $hour);
1001 $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));
1002 //* DEBUG: */ debugOutput('minute=' . $minute);
1003 // And at last seconds...
1004 $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));
1005 //* DEBUG: */ debugOutput('second=' . $second);
1007 // Is seconds zero and time is < 60 seconds?
1008 if (($second < 1) && ($timestamp < 60)) {
1010 $second = round($timestamp);
1013 // Put all calculated values in array
1025 // Now we convert them in seconds...
1027 if ($asArray === TRUE) {
1028 // Just put data array out
1033 // Time unit -> field name
1034 'unit_field' => array(
1043 // Time unit -> label
1044 'unit_label' => array(
1056 $OUT = '<div align="' . $align . '">';
1057 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1060 // "Walk" through all units
1061 foreach ($units['unit_field'] as $unit => $field) {
1062 // Is this displayed or zero?
1063 if (isInString($unit, $display) || (empty($display))) {
1064 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1065 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1069 // Close table row and open new one
1073 // "Walk" through all units again
1074 foreach ($units['unit_field'] as $unit => $field) {
1076 if (isInString($unit, $display) || (empty($display))) {
1077 // Generate year selection
1078 $OUT .= '<td align="center">';
1079 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select');
1082 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1092 // Return generated HTML code or data array
1096 // Generate a list of administrative links to a given userid
1097 function generateMemberAdminActionLinks ($userid) {
1098 // Make sure userid is a number
1099 if ($userid != bigintval($userid)) {
1100 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1103 // Define all main targets
1104 $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1107 $status = getFetchedUserData('userid', $userid, 'status');
1109 // Begin of navigation links
1112 foreach ($targetArray as $target) {
1113 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $target . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1114 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1115 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1116 // Locked accounts shall be unlocked
1117 $OUT .= 'UNLOCK_USER';
1118 } elseif ($target == 'del_user') {
1119 // @TODO Deprecate this thing
1120 $OUT .= 'DELETE_USER';
1122 // All other status is fine
1123 $OUT .= strtoupper($target);
1125 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1126 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1127 // Locked accounts shall be unlocked
1128 $OUT .= 'UNLOCK_USER';
1129 } elseif ($target == 'del_user') {
1130 // @TODO Deprecate this thing
1131 $OUT .= 'DELETE_USER';
1133 // All other status is fine
1134 $OUT .= strtoupper($target);
1136 $OUT .= '--}</a></span>|';
1139 // Add special link, in case of the account is unconfirmed
1140 if ($status == 'UNCONFIRMED') {
1142 $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>|';
1145 // Finish navigation link
1146 $OUT = substr($OUT, 0, -1) . ']';
1152 // Generate an email link
1153 function generateEmailLink ($email, $table = 'admins') {
1154 // Default email link (INSECURE! Spammer can read this by harvester programs)
1155 $EMAIL = 'mailto:' . $email;
1157 // Check for several extensions
1158 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1159 // Create email link for contacting admin in guest area
1160 $EMAIL = generateAdminEmailLink($email);
1161 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1162 // Create email link for contacting a member within admin area (or later in other areas, too?)
1163 $EMAIL = generateUserEmailLink($email);
1164 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1165 // Create email link to contact sponsor within admin area (or like the link above?)
1166 $EMAIL = generateSponsorEmailLink($email);
1169 // Return email link
1174 * Outputs an error message in a "fashioned way" to the user, by putting it into
1175 * a nice looking web page, if one of HTML or CSS output mode is active.
1177 * Please use reportBug() instead of this function. reportBug() has more helpful
1178 * functionality like logging and admin notification (which you can configure
1179 * through your admin area).
1181 * @param $file Function or file basename where the error came from
1182 * @param $line Line number where the error came from
1183 * @param $message Message which shall be output to web
1186 function app_exit ($file, $line, $message) {
1187 // Check if Script is already dieing and not let it kill itself another 1000 times
1188 if (isset($GLOBALS['app_died'])) {
1189 // Script tried to kill itself twice
1190 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $file . ', line=' . $line);
1193 // Make sure, that the script realy realy diese here and now
1194 $GLOBALS['app_died'] = TRUE;
1196 // Is this AJAX mode?
1197 if (isAjaxOutputMode()) {
1198 // Set content type as application/json
1199 setContentType('application/json');
1201 // Set content type as text/html
1202 setContentType('text/html');
1208 // Rewrite message for output
1210 getMessage('MAILER_HAS_DIED'),
1216 // Is this AJAX mode again
1217 if (isAjaxOutputMode()) {
1218 // Load the message template
1219 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1221 // Output it as JSON encoded
1222 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation(compileRawCode($OUT))))));
1224 // Load the message template
1225 loadTemplate('app_exit_message', FALSE, $message);
1232 // Display parsing time and number of SQL queries in footer
1233 function displayParsingTime () {
1234 // Is the timer started?
1235 if (!isset($GLOBALS['__start_time'])) {
1241 $endTime = microtime(TRUE);
1243 // "Explode" both times
1244 $start = explode(' ', $GLOBALS['__start_time']);
1245 $end = explode(' ', $endTime);
1246 $runTime = $end[0] - $start[0];
1252 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1254 'run_time' => $runTime,
1255 'sql_time' => (getConfig('sql_time') * 1000),
1258 // Load the template
1259 $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1261 // Is debug enabled?
1262 if (isDebugModeEnabled()) {
1263 // Log loading of total includes
1264 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
1269 * Outputs an error message and backtrace to the user, by default a mail with
1270 * all relevant data is being mailed to the configured administrators.
1272 * This function shall be used "publicly" because of logging, admin notification
1273 * and double-call prevention (see first if() block) instead of app_exit().
1274 * app_exit() is more a "private" function and will only output a bug message to
1275 * the user, no email and no logging.
1277 * @param $file Function or file basename where the error came from
1278 * @param $line Line number where the error came from
1279 * @param $sendEmail Wether to send an email to all configured administrators
1282 function reportBug ($file, $line, $message = '', $sendEmail = TRUE) {
1283 // Is this already called?
1284 if (isset($GLOBALS[__FUNCTION__])) {
1286 print '[' . $file . ':' . $line . ':] ' . __FUNCTION__ . '() has already died! Message:' . $message . '<br />Backtrace:<pre>';
1287 debug_print_backtrace();
1291 // Set HTTP status to 500 (e.g. for AJAX requests)
1292 setHttpStatus('500 Internal Server Error');
1294 // Mark this function as called
1295 $GLOBALS[__FUNCTION__] = TRUE;
1300 // Is the optional message set?
1301 if (!empty($message)) {
1303 $debug = sprintf("Note: %s<br />\n",
1307 // @TODO Add a little more infos here
1308 logDebugMessage($file, $line, strip_tags($message));
1312 $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>';
1313 $debug .= debug_get_printable_backtrace();
1315 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1316 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1318 // Send an email? (e.g. not wanted for evaluation errors)
1319 if (($sendEmail === TRUE) && (!isInstaller()) && (isAdminRegistered())) {
1322 'message' => trim($message),
1323 'backtrace' => trim(debug_get_mailable_backtrace())
1326 // Send email to webmaster
1327 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1330 // Is there HTML/CSS/AJAX mode while debug-mode is enabled?
1331 if (((isDebugModeEnabled()) || (isInstaller())) && ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode()))) {
1333 app_exit($file, $line, $debug);
1334 } elseif (isAjaxOutputMode()) {
1335 // Load include (again?)
1336 loadIncludeOnce('inc/ajax-functions.php');
1341 // Set HTTP status to 500 again
1342 setHttpStatus('500 Internal Server Error');
1344 // Is AJAX output mode, then output message as JSON
1345 setAjaxReplyContent($debug);
1347 // Send it out to browser
1348 sendAjaxContent(TRUE);
1353 // Raw/image output mode and all other modes doesn't work well with text ...
1358 // Compile characters which are allowed in URLs
1359 function compileUriCode ($code, $simple = TRUE) {
1361 $test = trim($code);
1365 // Then abort here and return the original code
1369 // Compile these by default
1370 $charsCompile = array(
1395 // Compile constants
1396 if ($simple === FALSE) {
1398 array_unshift($charsCompile['from'], '{--', '--}');
1401 array_unshift($charsCompile['to'], '".', '."');
1404 // Compile QUOT and other non-HTML codes
1405 $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1408 // Return compiled code
1412 // Handle message codes from URL
1413 function handleCodeMessage () {
1415 if (isGetRequestElementSet('code')) {
1416 // Default extension is 'unknown'
1419 // Is extension given?
1420 if (isGetRequestElementSet('ext')) {
1421 $ext = getRequestElement('ext');
1424 // Convert the 'code' parameter from URL to a human-readable message
1425 $message = getMessageFromErrorCode(getRequestElement('code'));
1427 // Load message template
1428 loadTemplate('message', FALSE, $message);
1432 // Generates a 'extension foo out-dated' message
1433 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1434 // Is the extension empty?
1435 if (empty($ext_name)) {
1436 // This should not happen
1437 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1441 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1443 // Is an admin logged in?
1445 // Then output admin message
1446 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1449 // Return prepared message
1453 // Generates a 'extension foo inactive' message
1454 function generateExtensionInactiveMessage ($ext_name) {
1455 // Is the extension empty?
1456 if (empty($ext_name)) {
1457 // This should not happen
1458 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1462 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1464 // Is an admin logged in?
1466 // Then output admin message
1467 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1470 // Return prepared message
1474 // Generates a 'extension foo not installed' message
1475 function generateExtensionNotInstalledMessage ($ext_name) {
1476 // Is the extension empty?
1477 if (empty($ext_name)) {
1478 // This should not happen
1479 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1483 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1485 // Is an admin logged in?
1487 // Then output admin message
1488 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1491 // Return prepared message
1495 // Generates a message depending on if the extension is not installed or not
1497 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1501 // Is the extension not installed or just deactivated?
1502 switch (isExtensionInstalled($ext_name)) {
1503 case TRUE; // Deactivated!
1504 $message = generateExtensionInactiveMessage($ext_name);
1507 case FALSE; // Not installed!
1508 $message = generateExtensionNotInstalledMessage($ext_name);
1511 default: // Should not happen!
1512 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid state of extension %s detected.', $ext_name));
1513 $message = sprintf('Invalid state of extension %s detected.', $ext_name);
1517 // Return the message
1521 // Print code with line numbers
1522 function lineNumberCode ($code) {
1523 // By default copy the code
1526 if (!is_array($code)) {
1527 // We need an array, so try it with the new-line character
1528 $codeE = explode(PHP_EOL, $code);
1531 $count_lines = count($codeE);
1533 $r = 'Line | Code:<br />';
1534 foreach ($codeE as $line => $c) {
1535 $r .= '<div class="line"><span class="linenum">';
1536 if ($count_lines == 1) {
1539 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1544 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1547 return '<div class="code">' . $r . '</div>';
1550 // Determines the right page title
1551 function determinePageTitle () {
1555 // Config and database connection valid?
1556 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1557 // Title decoration enabled?
1558 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1559 $pageTitle .= '{%config,trim=title_left%} ';
1562 // Is there an extra title?
1563 if (isExtraTitleSet()) {
1565 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1569 $pageTitle .= '{?MAIN_TITLE?}';
1571 // Add title of module? (middle decoration will also be added!)
1572 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1573 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1576 // Get menu mode from module
1577 $menuMode = getMenuModeFromModule();
1579 // Add middle part (always in admin area!)
1580 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1581 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1584 // Add title decorations? (right)
1585 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1586 $pageTitle .= ' {%config,trim=title_right%}';
1588 } elseif ((isInstalled()) && (isAdminRegistered())) {
1589 // Installed, admin registered but no ext-sql_patches
1590 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1591 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1592 // Installed but no admin registered
1593 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1594 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1595 // Installation mode
1596 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1598 // Configuration not found
1599 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1601 // Do not add the fatal message in installation mode
1602 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1603 // Please report this
1604 reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1609 return decodeEntities($pageTitle);
1612 // Checks whethere there is a cache file there. This function is cached.
1613 function isTemplateCached ($prefix, $template) {
1614 // Is there cached this result?
1615 if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1617 $FQFN = generateCacheFqfn($prefix, $template);
1620 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1624 return $GLOBALS['template_cache'][$prefix][$template];
1627 // Flushes non-flushed template cache to disk
1628 function flushTemplateCache ($prefix, $template, $eval) {
1629 // Is this cache flushed?
1630 if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1632 $FQFN = generateCacheFqfn($prefix, $template);
1634 // Compile code another round for better performance and preserve $ signs
1635 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1637 // Is this a XML template?
1638 if ($prefix == 'xml') {
1639 // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1640 $eval = compactContent($eval);
1644 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1648 // Reads a template cache
1649 function readTemplateCache ($prefix, $template, $content) {
1651 if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1652 // This should not happen
1653 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1657 if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1659 $FQFN = generateCacheFqfn($prefix, $template);
1664 * WARNING: Do not replace this include() call with loadInclude() as it
1665 * would hide local variables away which is here required to make this
1670 // Is the template cache valid?
1671 if (!isset($templateContent)) {
1672 // Please clear your cache!
1673 reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1678 return $templateContent;
1681 // Escapes quotes (default is only double-quotes)
1682 function escapeQuotes ($str, $single = FALSE) {
1683 // Should we escape all?
1684 if ($single === TRUE) {
1685 // Escape all (including null)
1686 $str = addslashes($str);
1688 // Replace all chars at once
1689 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1692 // Return the escape'd string
1696 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1697 function escapeJavaScriptQuotes ($str) {
1698 // Replace all double-quotes and secure back-ticks
1699 $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1705 // Send out mails depending on the 'mod/modes' combination
1706 // @TODO Lame description for this function
1707 function sendModeMails ($mod, $modes) {
1709 $content = array ();
1712 if (fetchUserData(getMemberId())) {
1713 // Extract salt from cookie
1714 $salt = substr(getSession('u_hash'), 0, -40);
1716 // Now let's compare passwords
1717 $hash = encodeHashForCookie(getUserData('password'));
1719 // Does the hash match or should we change it?
1720 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1722 $content = getUserDataArray();
1724 // Clear/init the content variable
1725 $content['message'] = '';
1728 // @TODO Move this in a filter
1731 foreach ($modes as $mode) {
1733 case 'normal': break; // Do not add any special lines
1734 case 'email': // Email was changed!
1735 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1738 case 'password': // Password was changed
1739 $content['message'] = '{--MEMBER_CHANGED_PASSWORD--}' . PHP_EOL;
1743 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown mode %s detected.', $mode));
1744 $content['message'] = '{%message,MEMBER_UNKNOWN_MODE=' . $mode . '%}' . PHP_EOL . PHP_EOL;
1749 if (isExtensionActive('country')) {
1750 // Replace code with description
1751 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1754 // Merge content with data from POST
1755 $content = merge_array($content, postRequestArray());
1758 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1760 if (isAdminNotificationEnabled()) {
1761 // The admin needs to be notified about a profile change
1762 $message_admin = 'admin_mydata_notify';
1763 $subjectAdmin = '{--ADMIN_CHANGED_DATA_SUBJECT--}';
1766 $message_admin = '';
1770 // Set subject lines
1771 $subjectMember = '{--MEMBER_CHANGED_DATA--}';
1773 // Output success message
1774 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1777 default: // Unsupported module!
1778 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unsupported module %s detected.', $mod));
1779 $content['message'] = '<span class="bad">{%message,UNKNOWN_MODULE=' . $mod . '%}</span>';
1783 // Passwords mismatch
1784 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1787 // Could not load profile
1788 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1791 // Send email to user if required
1792 if ((!empty($subjectMember)) && (!empty($message)) && (!empty($content['userid']))) {
1794 sendEmail($content['userid'], $subjectMember, $message);
1797 // Send only if no other error has occured
1798 if ((!empty($subjectAdmin)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1800 sendAdminNotification($subjectAdmin, $message_admin, $content, getMemberId());
1801 } elseif (isAdminNotificationEnabled()) {
1802 // Cannot send mails to admin!
1803 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1806 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1810 displayMessage($content['message']);
1813 // Generates a 'selection box' from given array
1814 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1815 // options must be an array
1816 assert(is_array($options));
1821 // Use default value as array key?
1822 if ($useDefaultAsArray === TRUE) {
1824 $addKey = '[' . convertNullToZero($default) . ']';
1828 $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1829 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1832 if ($allowNone === TRUE) {
1834 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1837 // Walk through all options
1838 foreach ($options as $option) {
1839 // Default 'default' is not set
1840 $option['default'] = '';
1842 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1843 // Is default value same as given value?
1844 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1846 $option['default'] = ' selected="selected"';
1849 // Is 'nameElement' set?
1850 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1851 // Then set this as extraName, but lower-case
1852 $extraName = '_' . strtolower($option[$nameElement]);
1855 // Add the <option> entry from ...
1856 if (empty($optionContent)) {
1857 // Is a template name given?
1858 if (empty($templateName)) {
1859 // ... $name template
1860 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1862 // ... $templateName template
1863 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1866 // ... direct HTML code
1867 $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1871 // Finish selection box
1872 $OUT .= '</select>';
1876 'selection_box' => $OUT,
1879 // Load template and return it
1880 if (empty($templateName)) {
1881 // Use name from $name + $extraName
1882 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1884 // Use name from $templateName + $extraName
1885 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1889 // Prepares the header for HTML output
1890 function loadHtmlHeader () {
1893 * 1.) pre_page_header (mainly loads the page_header template and includes
1896 runFilterChain('pre_page_header');
1899 * Here can be something be added, but normally one of the two filters
1900 * around this line should do the job for you.
1904 * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1905 * to close the head-tag)
1906 * Include more header data here
1908 runFilterChain('post_page_header');
1911 // Adds page header and footer to output array element
1912 function addPageHeaderFooter () {
1916 // Add them all together. This is maybe to simple
1917 foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1918 // Add page part if set
1919 if (isset($GLOBALS[$pagePart])) {
1920 $OUT .= $GLOBALS[$pagePart];
1924 // Transfer $OUT to '__output'
1925 $GLOBALS['__output'] = $OUT;
1928 // Generates meta description for current module and 'what' value
1929 function generateMetaDescriptionCode () {
1930 // Only include from guest area and if ext-sql_patches has correct version
1931 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1932 // Output it directly
1933 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1936 // Initialize referral system
1937 initReferralSystem();
1940 // Generates an FQFN for template cache from the given template name
1941 function generateCacheFqfn ($prefix, $template) {
1943 if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1944 // Generate the FQFN
1945 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1946 '%s%s_compiled/%s/%s%s',
1956 return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1959 // "Fixes" null or empty string to count of dashes
1960 function fixNullEmptyToDashes ($str, $num) {
1961 // Use str as default
1965 if ((is_null($str)) || (trim($str) == '')) {
1967 $return = str_repeat('-', $num);
1970 // Return final string
1974 // Translates the "pool type" into human-readable
1975 function translatePoolType ($type) {
1976 // Return "translation"
1977 return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1980 // "Translates" given time unit
1981 function translateTimeUnit ($unit) {
1982 // Default is unknown
1983 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1986 if (!isset($GLOBALS['time_units'][$unit])) {
1988 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1990 // Translate it with generic function
1991 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1998 // Displays given message in admin_settings_saved template
1999 function displayMessage ($message) {
2000 // Call inner function
2001 outputHtml(returnMessage($message));
2004 // Returns given message in admin_settings_saved template
2005 function returnMessage ($message) {
2006 // Load the template
2007 return loadTemplate('admin_settings_saved', TRUE, $message);
2010 // Displays given error message in admin_settings_unsaved template
2011 function displayErrorMessage ($message) {
2012 // Load the template
2013 outputHtml(returnErrorMessage($message));
2016 // Displays given error message in admin_settings_unsaved template
2017 function returnErrorMessage ($message) {
2018 // Load the template
2019 return loadTemplate('admin_settings_unsaved', TRUE, $message);
2022 // Generates a selection box for (maybe) given gender
2023 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
2024 // Start the HTML code
2025 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2028 $out .= generateOptions(
2043 $out .= '</select>';
2049 // Generates a selection box for given default value
2050 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2052 $messageIds = array();
2054 // Generate message id array
2055 foreach ($unitArray as $unit) {
2057 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2060 // Start the HTML code
2061 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2064 $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2067 $out .= '</select>';
2073 // Function to add style tag (whether display:none/block)
2074 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2075 // Is there foo_menu_javascript enabled?
2076 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2077 // Silently abort here, not enabled
2081 // Is action=mainAction?
2082 if ($action == $mainAction) {
2083 // Add "menu open" style
2084 return ' style="display:block"';
2086 return ' style="display:none"';
2090 // Function to add onclick attribute
2091 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2092 // Is there foo_menu_javascript enabled?
2093 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2094 // Silently abort here, not enabled
2099 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2105 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2106 function anonymizeSensitiveData ($data) {
2108 $data = trim($data);
2112 // Then add three dashes
2114 } elseif (isUrlValid($data)) {
2115 // Is a referrer, so is it black-listed?
2117 // Is admin, has always priority
2118 $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2119 } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
2120 // Yes, so replace it with text
2121 $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2123 // A member is viewing this referral URL
2124 $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2126 } elseif (isIp4AddressValid($data)) {
2127 // Is an IPv4 address
2128 $ipArray = explode('.', $data);
2130 // Only display first 2 octets
2131 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2134 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2137 // Return it (hopefully) anonymized
2142 * Removes all comments, tabs and new-line characters to compact the content
2144 * @param $uncompactedContent The uncompacted content
2145 * @return $compactedContent The compacted content
2147 function compactContent ($uncompactedContent) {
2148 // First, remove all tab/new-line/revert characters
2149 $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2151 // Make a space after >
2152 $compactedContent = str_replace(array('>', ' '), array('> ', ' '), $compactedContent);
2154 // Then regex all comments like <!-- //--> away
2155 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2157 // Do we have entries?
2158 if (isset($matches[0][0])) {
2160 foreach ($matches[0] as $match) {
2162 $compactedContent = str_replace($match, '', $compactedContent);
2166 // Return compacted content
2167 return $compactedContent;
2170 //-----------------------------------------------------------------------------
2171 // Template helper functions for EL code
2172 //-----------------------------------------------------------------------------
2174 // Color-switch helper function
2175 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2177 if (!isset($GLOBALS['color_switch'][$templateName])) {
2179 initTemplateColorSwitch($templateName);
2180 } elseif ($clear === FALSE) {
2181 // Switch color if called from loadTemplate()
2182 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2183 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2186 // Return CSS class name
2187 if ($return === TRUE) {
2188 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2189 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2193 // Helper function for extension registration link
2194 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2195 // Default is all non-productive
2196 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2198 // Is the given extension non-productive?
2199 if (isExtensionDeprecated($ext_name)) {
2201 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2202 } elseif (isExtensionProductive($ext_name)) {
2204 $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>';
2211 // Helper function to create bonus mail admin links
2212 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2213 // Call the inner function
2214 return generateAdminMailLinks('bonus', $bonusId);
2217 // Helper function to create member mail admin links
2218 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2219 // Call the inner function
2220 return generateAdminMailLinks('normal', $mailId);
2223 // Helper function to create a selection box for YES/NO configuration entries
2224 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2225 // Default is a "missing entry" warning
2226 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2228 // Generate the HTML code
2229 if (isConfigEntrySet($configEntry)) {
2230 // Configuration entry is found
2231 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2232 {%config,generateYesNoOptions=' . $configEntry . '%}
2240 // Helper function to create a selection box for YES/NO form fields
2241 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2242 // Generate the HTML code
2243 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2244 {%pipe,generateYesNoOptions%}
2251 // Helper function to create a selection box for YES/NO form fields, by NO is default
2252 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2253 // Generate the HTML code
2254 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2255 {%pipe,generateYesNoOptions=N%}
2262 // Helper function to add extra content for guest area (module=index and others)
2263 function doTemplateGuestFooterExtras ($templateName, $clear) {
2265 $filterData = array(
2266 // Name of used template
2267 'template' => $templateName,
2268 // Target array for gathered data
2269 '__data' => array(),
2270 // Where the HTML output will go
2274 // Run the filter chain
2275 $filterData = runFilterChain('guest_footer_extras', $filterData);
2278 return $filterData['__output'];
2281 // Helper function to add extra content for member area (module=login)
2282 function doTemplateMemberFooterExtras ($templateName, $clear) {
2283 // Is a member logged in?
2285 // This shall not happen
2286 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2290 $filterData = array(
2291 // Current user's id number
2292 'userid' => getMemberId(),
2293 // Name of used template
2294 'template' => $templateName,
2295 // Target array for gathered data
2296 '__data' => array(),
2297 // Where the HTML output will go
2301 // Run the filter chain
2302 $filterData = runFilterChain('member_footer_extras', $filterData);
2305 return $filterData['__output'];
2309 * Helper function to determine whether current userid is set, if none is set,
2310 * return a zero, else an EL code is being returned as of this function is used
2311 * only in templates.
2313 * @param $templateName Name of template (unused)
2314 * @param $clear Wether to clear something (unused)
2315 * @return $userId Wether zero or EL code snippet
2317 function doTemplateUserId ($templateName, $clear) {
2318 // By default no userid is set
2321 // Is there a user id currently set?
2322 if (isCurrentUserIdSet()) {
2323 // Then get the current user id
2324 $userId = getCurrentUserId();
2331 // Template helper function to generate "Terms&Conditions" link (EL code again)
2332 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2334 * Use default link by default ;-) This link, however, will become
2335 * deprecated once ext-terms is rolled out.
2337 $linkCode = '{%url=modules.php?module=index&what=agb%}';
2339 // Is ext-terms installed?
2340 if (isExtensionInstalled('terms')) {
2341 // Then use that link (only 'what' has changed)
2342 $linkCode = '{%url=modules.php?module=index&what=terms%}';
2345 // Return link (EL) code
2349 // Template helper function to create selection box for "locked points mode"
2350 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2352 $lockedModes = array(
2353 0 => array('mode' => 'LOCKED'),
2354 1 => array('mode' => 'UNLOCKED'),
2357 // Handle it over to generateSelectionBoxFromArray()
2358 $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2360 // Return prepared content
2364 // Template helper function to create selection box for payment method
2365 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2367 $paymentMethods = array(
2368 0 => array('method' => 'DIRECT'),
2369 1 => array('method' => 'REFERRAL'),
2372 // Handle it over to generateSelectionBoxFromArray()
2373 $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2375 // Return prepared content
2379 // Template helper function to create a deferrer code if URL is not empty
2380 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2381 // Is the URL not NULL and not empty?
2382 if ((!is_null($url)) && (!empty($url))) {
2383 // Set HTML with EL code
2384 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2387 // Return URL (or content) or dashes if empty
2388 return fixEmptyContentToDashes($url);
2391 // Load another template and return its content
2392 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = array()) {
2393 // Load "the" template
2394 return loadTemplate($theTemplate, TRUE, $content);
2397 // Output HTML code for favicon.ico, if found
2398 function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
2399 // Default is not found
2402 // Check all common extensions
2403 foreach (array('ico', 'gif', 'png') as $extension) {
2404 // Is the file there?
2405 if (isFileReadable(getPath() . 'favicon.' . $extension)) {
2406 // Then use this and abort
2407 $out = '<link rel="shortcut icon" href="{%url=favicon.' . $extension . '%}" type="image/' . $extension . '" />';
2416 // Helper function to display referral id or hide it depending on settings
2417 function doTemplateDisplayReferralIdContent ($template, $clear = FALSE) {
2418 // Ddisplay the refid or make it editable?
2419 if (isDisplayRefidEnabled()) {
2420 // Load "hide" form template
2421 $out = loadTemplate('guest_register_refid_hide', TRUE);
2423 // Load template to enter it
2424 $out = loadTemplate('guest_register_refid', TRUE);
2431 // "Getter" for template base path
2432 function getTemplateBasePath ($part) {
2434 if (!isset($GLOBALS[__FUNCTION__][$part])) {
2436 $GLOBALS[__FUNCTION__][$part] = sprintf('%stemplates/%s/%s', getPath(), getLanguage(), $part);
2440 return $GLOBALS[__FUNCTION__][$part];
2443 // Removes comments with @DEPRECATED
2444 function removeDeprecatedComment ($output) {
2445 // Explode it into pieces ... ;)
2446 $lines = explode(chr(10), $output);
2450 foreach ($lines as $line) {
2451 // Is there a @DEPRECATED?
2452 if (isInString('@DEPRECATED', $line)) {
2458 $return .= $line . chr(13);
2461 // Returned cleaned content
2465 // Generates a selection box suitable for e.g. birthdays: day, month and year
2466 function generateDayMonthYearSelectionBox ($day, $month, $year) {
2467 // This depends on selected language
2468 switch (getLanguage()) {
2469 case 'de': // German date format
2470 $content = addSelectionBox('da', $day) . addSelectionBox('mo', $month) . addSelectionBox('ye', $year);
2473 default: // Default is the US date format... :)
2474 $content = addSelectionBox('mo', $month) . addSelectionBox('da', $day) . addSelectionBox('ye', $year);
2482 // Loads page header
2483 function loadPageHeader () {
2485 $GLOBALS['__page_header'] = '';
2487 // Is the header already sent?
2488 if (($GLOBALS['__header_sent'] != 1) && ($GLOBALS['__header_sent'] != 2)) {
2489 // Set default HTTP status to "200 OK"
2490 setHttpStatus('200 OK');
2492 // If not in CSS mode generate the header
2493 if ((!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode())) {
2494 // Prepare the header for HTML output
2499 if ($GLOBALS['__header_sent'] == '0') {
2500 $GLOBALS['__header_sent'] = 1;
2504 // Add BODY tag or not?
2505 // @TODO Find a way to not use direct module comparison
2506 if ((!isCssOutputMode()) && (!isRawOutputMode()) && ($GLOBALS['__header_sent'] == 1) && (getModule() != 'frametester') && (!isFramesetModeEnabled())) {
2507 loadTemplate('page_body');
2508 $GLOBALS['__header_sent'] = 2;
2512 // Loads page footer and calls doShutdown()
2513 function loadPageFooter () {
2515 $GLOBALS['__page_footer'] = '';
2517 // Footer disabled (e.g. CSS/AJAX/image output) or already sent?
2518 // 1234 5 54 45 5 5 543 3 443 3 443 3 44321
2519 if ((((!isset($GLOBALS['__footer_sent'])) || (($GLOBALS['__footer_sent'] != 1) && ($GLOBALS['__footer_sent'] != 2))) && (!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode()))) {
2520 // Run the filter, sweet huh?
2521 runFilterChain('page_footer');
2524 $GLOBALS['__page_footer'] .= loadTemplate('page_footer', TRUE);
2527 // Footer has been reached
2528 $GLOBALS['__footer_sent'] = 1;