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 // "Renders" color switch code
82 function renderColorSwitchCode ($template) {
84 $code = sprintf("{DQUOTE} . doTemplateColorSwitch('%s', FALSE, FALSE) . {DQUOTE}", $template);
90 // Output HTML code directly or 'render' it. You can 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 = "' . renderColorSwitchCode($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 = "' . renderColorSwitchCode($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 = sprintf('<div class="para">
540 {--TEMPLATE_404--}: %s
543 {--TEMPLATE_CONTENT--}:
547 print_r($content, TRUE)
550 // Don't cache this, as there is no template to cache
551 $GLOBALS['template_eval']['email'][$template] = '404';
553 // Debug mode not active? Then remove the HTML tags
554 if (!isDebugModeEnabled()) {
556 $templateContent = secureString($templateContent);
559 // No template name supplied!
560 $templateContent = '{--NO_TEMPLATE_SUPPLIED--}';
561 $GLOBALS['template_eval']['email'][$template] = '404';
565 // Is there something to eval?
566 if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
568 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
569 //* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
570 //* DEBUG: */ die('<pre>'.print_r($content, TRUE).'</pre><pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
571 eval($GLOBALS['template_eval']['email'][$template]);
572 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
575 // Are there some content?
576 if (empty($templateContent)) {
578 $templateContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
580 // Add last error if the required function exists
581 if (function_exists('error_get_last')) {
582 // Add last error and some lines for better overview
583 $templateContent .= "\n--------------------------------------\nDebug:\n" . print_r(error_get_last(), TRUE) . "--------------------------------------\nPlease don't alter these informations!\nThanx.";
587 // Remove content and data
591 return $templateContent;
594 // "Getter" for menu CSS classes, mainly used in templates
595 function getMenuCssClasses ($data) {
596 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
599 if (!isset($GLOBALS[__FUNCTION__][$data])) {
600 // $data needs to be converted into an array
601 $content = explode('|', $data);
603 // Non-existent index 2 will happen in menu blocks
604 if (!isset($content[2])) {
608 // Re-construct the array: 0=visible,1=locked,2=prefix
609 $content['visible'] = $content[0];
610 $content['locked'] = $content[1];
612 // Call our "translator" function
613 $content = translateMenuVisibleLocked($content, $content[2]);
616 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
620 return $GLOBALS[__FUNCTION__][$data];
623 // Generate XHTML code for the CAPTCHA
624 function generateCaptchaCode ($code, $type, $urlId, $userid) {
625 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&' . $type . '=' . $urlId . '&do=img&code=' . $code . '%}" />';
628 // Compiles the given HTML/mail code
629 function compileCode ($code, $full = TRUE, $compileCode = TRUE) {
630 // Is the code a string or should we not compile?
631 if ((!is_string($code)) || ($compileCode === FALSE)) {
632 // Silently return it
637 $startCompile = microtime(TRUE);
640 $code = compileRawCode($code, $full, $compileCode);
643 $compilationTime = $startCompile - microtime(TRUE);
645 // Add timing if enabled
646 if (isTemplateHtml()) {
647 // Add timing, this should be disabled in
648 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
651 // Return compiled code
656 function compileRawCode ($code, $full = TRUE, $compileCode = TRUE) {
657 //* DIE: */ reportBug(__FUNCTION__, __LINE__, 'Called with ' . strlen($code) . ' code length.');
658 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called with code()=' . strlen($code) . ',full=' . intval($full) . ',compileCode=' . intval($compileCode));
660 // Is the code a string or shall we not compile?
661 if ((!is_string($code)) || ($compileCode === FALSE)) {
662 // Silently return it
663 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code[]= ' . gettype($code) . ' is not a string or compileCode(' . intval($compileCode) . ') is FALSE.');
667 // Init replacement-array with smaller set of security characters
668 $secChars = $GLOBALS['url_chars'];
670 // Select full set of chars to replace when we e.g. want to compile URLs
671 if ($full === TRUE) {
672 $secChars = $GLOBALS['security_chars'];
675 // First compile these chars
676 array_unshift($secChars['to'] , '{--' , '--}');
677 array_unshift($secChars['from'], '{%message,', '%}' );
679 // Replace QUOT and other non-HTML codes
680 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
681 $code = str_replace($secChars['to'], $secChars['from'], $code);
682 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
684 // Compile the prepared code through a filter chain
685 $code = runFilterChain('compile_code', $code);
687 // Find all $content[bla][blub] entries
688 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
689 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
691 // Are some matches found?
692 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
693 // Replace all matches
695 foreach ($matches[0] as $key => $match) {
696 // Fuzzy look has failed by default
699 // "Cache" match length
700 $matchLength = strlen($match);
702 // Fuzzy look on match if already found
703 foreach ($matchesFound as $found => $set) {
705 $test = substr($found, 0, $matchLength);
707 // Does this entry exist?
708 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
709 if ($test == $match) {
711 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
718 if ($fuzzyFound === TRUE) {
722 // Take all string elements
723 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
724 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
725 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
726 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
727 $code = str_replace($match, '".' . $newMatch . '."', $code);
728 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
729 $matchesFound[$match] = TRUE;
730 } elseif (!isset($matchesFound[$match])) {
732 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
733 $code = str_replace($match, '".' . $match . '."', $code);
734 $matchesFound[$match] = 1;
736 // Everthing else should be a least logged
737 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
743 * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
744 * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
745 * therefore the variable's value won't be inserted. This is why
746 * {COMPILE_DOLLAR} is being used in above loop and at the end of this
747 * function being replace with the original dollar sign again.
749 preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
751 // Are some matches found?
752 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
753 // Scan all matches for not $content
754 foreach ($matches[0] as $match) {
756 $match = trim($match);
759 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
761 // Is the first part not $content/$userid and not empty?
762 // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
763 if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
764 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
765 // Then replace $ with {DOLLAR}
766 $matchSecured = str_replace('$', '{DOLLAR}', $match);
768 // And in $code as well
769 $code = str_replace($match, $matchSecured, $code);
774 // Add 'COMPILE_DOLLAR' again
775 array_push($secChars['to'] , '{COMPILE_DOLLAR}');
776 array_push($secChars['from'], '$');
778 // Replace QUOT and other non-HTML codes
779 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - before str_replace() ...');
780 $code = str_replace($secChars['to'], $secChars['from'], $code);
781 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code()=' . strlen($code) . ' - after str_replace() ...');
784 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Exiting with code()=' . strlen($code));
789 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select', $allSteps = FALSE) {
793 // This is a yes/no selection only!
794 if (isValidId($id)) $prefix .= '[' . $id . ']';
795 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
797 // Begin with regular selection box here
798 if (!empty($prefix)) $prefix .= '_';
800 if (isValidId($id)) $type2 .= '[' . $id . ']';
801 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
809 // Use configured min age or fixed?
810 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
812 $startYear = $year - getMinAge();
815 $startYear = $year - 16;
818 // Calculate earliest year (100 years old people can still enter Internet???)
819 $minYear = $year - 100;
821 // Check if the default value is larger than minimum and bigger than actual year
822 if (($default > $minYear) && ($default >= $year)) {
823 for ($idx = $year; $idx < ($year + 11); $idx++) {
824 $OUT .= '<option value="' . $idx . '"';
825 if ($default == $idx) $OUT .= ' selected="selected"';
826 $OUT .= '>' . $idx . '</option>';
828 } elseif ($default == -1) {
829 // Current year minus 1
830 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
831 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
834 // Get current year and subtract the configured minimum age
835 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
837 // Construct year selection list
838 for ($idx = $minYear; $idx <= $startYear; $idx++) {
839 $OUT .= '<option value="' . $idx . '"';
840 if ($default == $idx) $OUT .= ' selected="selected"';
841 $OUT .= '>' . $idx . '</option>';
847 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
848 $OUT .= '<option value="' . $idx . '"';
849 if ($default == $idx) $OUT .= ' selected="selected"';
850 $OUT .= '>' . $descr . '</option>';
854 case 'mn': // Months, numeric
855 for ($idx = 0; $idx <= 12; $idx++) {
856 $OUT .= '<option value="' . $idx . '"';
857 if ($default == $idx) $OUT .= ' selected="selected"';
858 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
863 for ($idx = 0; $idx <= 4; $idx++) {
864 $OUT .= ' <option value="' . $idx . '"';
865 if ($default == $idx) $OUT .= ' selected="selected"';
866 $OUT .= '>' . $idx . '</option>';
871 for ($idx = 0; $idx <= 31; $idx++) {
872 $OUT .= '<option value="' . $idx . '"';
873 if ($default == $idx) $OUT .= ' selected="selected"';
874 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
879 for ($idx = 0; $idx <= 23; $idx++) {
880 $padded = padLeftZero($idx, 2);
881 $OUT .= '<option value="' . $padded . '"';
882 if ($default == $padded) $OUT .= ' selected="selected"';
883 $OUT .= '>' . $padded . '</option>';
887 case 'mi': // Minutes
888 case 'se': // Seconds
889 // Default is 5 minutes/seconds step
893 if ($allSteps === TRUE) {
898 for ($idx = 0; $idx <= 59; $idx += $step) {
899 $padded = padLeftZero($idx, 2);
900 $OUT .= '<option value="' . $padded . '"';
901 if ($default == $padded) $OUT .= ' selected="selected"';
902 $OUT .= '>' . $padded . '</option>';
907 $OUT .= '<option value="Y"';
908 if ($default == 'Y') $OUT .= ' selected="selected"';
909 $OUT .= '>{--YES--}</option><option value="N"';
910 if ($default != 'Y') $OUT .= ' selected="selected"';
911 $OUT .= '>{--NO--}</option>';
914 default: // Not detected
915 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' . $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
922 // Insert the code in $img_code into jpeg or PNG image
923 function generateImageOrCode ($img_code, $headerSent = TRUE) {
924 // Is the code size oversized or shouldn't we display it?
925 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
926 // Stop execution of function here because of over-sized code length
927 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
928 } elseif ($headerSent === FALSE) {
929 // Return an HTML code here
930 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
934 $img = sprintf('%s/theme/%s/images/code_bg.%s',
941 if (isFileReadable($img)) {
943 switch (getImgType()) {
944 case 'jpg': // Okay, load image and hide all errors
945 $image = imagecreatefromjpeg($img);
948 case 'png': // Okay, load image and hide all errors
949 $image = imagecreatefrompng($img);
953 // Silently log the error
954 logDebugMessage(__FUNCTION__, __LINE__, sprintf('File for image-type %s in theme %s not found.', getImgType(), getCurrentTheme()));
958 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
959 $text_color = imagecolorallocate($image, 0, 0, 0);
961 // Insert code into image
962 imagestring($image, 5, 14, 2, $img_code, $text_color);
965 setContentType('image/' . getImgType());
967 // Output image with matching image factory
968 switch (getImgType()) {
969 case 'jpg': imagejpeg($image); break;
970 case 'png': imagepng($image); break;
973 // Remove image from memory
974 imagedestroy($image);
977 // Create selection box or array of splitted timestamp
978 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE, $allSteps = FALSE) {
979 // Do not continue if ONE_DAY is absend
980 if (!isConfigEntrySet('ONE_DAY')) {
982 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
985 // Calculate 2-seconds timestamp
986 $stamp = round($timestamp);
987 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
989 // Is there a leap year?
991 $TEST = getYear() / 4;
993 $M2 = getMonth(time() + $timestamp);
995 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
996 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
997 $SWITCH = getOneDay();
1000 // First of all years...
1001 $year = abs(floor($timestamp / (31536000 + $SWITCH)));
1002 //* DEBUG: */ debugOutput('year=' . $year);
1004 $month = abs(floor($timestamp / 2628000 - $year * 12));
1005 //* DEBUG: */ debugOutput('month=' . $month);
1007 $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
1008 //* DEBUG: */ debugOutput('week=' . $week);
1010 $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
1011 //* DEBUG: */ debugOutput('day=' . $day);
1013 $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
1014 //* DEBUG: */ debugOutput('hour=' . $hour);
1016 $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));
1017 //* DEBUG: */ debugOutput('minute=' . $minute);
1018 // And at last seconds...
1019 $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));
1020 //* DEBUG: */ debugOutput('second=' . $second);
1022 // Is seconds zero and time is < 60 seconds?
1023 if (($second < 1) && ($timestamp < 60)) {
1025 $second = round($timestamp);
1028 // Put all calculated values in array
1040 // Now we convert them in seconds...
1042 if ($asArray === TRUE) {
1043 // Just put data array out
1048 // Time unit -> field name
1049 'unit_field' => array(
1058 // Time unit -> label
1059 'unit_label' => array(
1071 $OUT = '<div align="' . $align . '">';
1072 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1075 // "Walk" through all units
1076 foreach ($units['unit_field'] as $unit => $field) {
1077 // Is this displayed or zero?
1078 if (isInString($unit, $display) || (empty($display))) {
1079 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1080 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1084 // Close table row and open new one
1088 // "Walk" through all units again
1089 foreach ($units['unit_field'] as $unit => $field) {
1091 if (isInString($unit, $display) || (empty($display))) {
1092 // Generate year selection
1093 $OUT .= '<td align="center">';
1094 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select', $allSteps);
1097 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1107 // Return generated HTML code or data array
1111 // Generate a list of administrative links to a given userid
1112 function generateMemberAdminActionLinks ($userid) {
1113 // Make sure userid is a number
1114 if ($userid != bigintval($userid)) {
1115 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1118 // Define all main targets
1119 $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1122 $status = getFetchedUserData('userid', $userid, 'status');
1124 // Begin of navigation links
1127 foreach ($targetArray as $target) {
1128 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $target . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1129 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1130 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1131 // Locked accounts shall be unlocked
1132 $OUT .= 'UNLOCK_USER';
1133 } elseif ($target == 'del_user') {
1134 // @TODO Deprecate this thing
1135 $OUT .= 'DELETE_USER';
1137 // All other status is fine
1138 $OUT .= strtoupper($target);
1140 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1141 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1142 // Locked accounts shall be unlocked
1143 $OUT .= 'UNLOCK_USER';
1144 } elseif ($target == 'del_user') {
1145 // @TODO Deprecate this thing
1146 $OUT .= 'DELETE_USER';
1148 // All other status is fine
1149 $OUT .= strtoupper($target);
1151 $OUT .= '--}</a></span>|';
1154 // Add special link, in case of the account is unconfirmed
1155 if ($status == 'UNCONFIRMED') {
1157 $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>|';
1160 // Finish navigation link
1161 $OUT = substr($OUT, 0, -1) . ']';
1167 // Generate an email link
1168 function generateEmailLink ($email, $table = 'admins') {
1169 // Default email link (INSECURE! Spammer can read this by harvester programs)
1170 $EMAIL = 'mailto:' . $email;
1172 // Check for several extensions
1173 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1174 // Create email link for contacting admin in guest area
1175 $EMAIL = generateAdminEmailLink($email);
1176 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1177 // Create email link for contacting a member within admin area (or later in other areas, too?)
1178 $EMAIL = generateUserEmailLink($email);
1179 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1180 // Create email link to contact sponsor within admin area (or like the link above?)
1181 $EMAIL = generateSponsorEmailLink($email);
1184 // Return email link
1189 * Outputs an error message in a "fashioned way" to the user, by putting it into
1190 * a nice looking web page, if one of HTML or CSS output mode is active.
1192 * Please use reportBug() instead of this function. reportBug() has more helpful
1193 * functionality like logging and admin notification (which you can configure
1194 * through your admin area).
1196 * @param $file Function or file basename where the error came from
1197 * @param $line Line number where the error came from
1198 * @param $message Message which shall be output to web
1201 function app_exit ($file, $line, $message) {
1202 // Check if Script is already dieing and not let it kill itself another 1000 times
1203 if (isset($GLOBALS['app_died'])) {
1204 // Script tried to kill itself twice
1205 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $file . ', line=' . $line);
1208 // Make sure, that the script realy realy diese here and now
1209 $GLOBALS['app_died'] = TRUE;
1211 // Is this AJAX mode?
1212 if (isAjaxOutputMode()) {
1213 // Set content type as application/json
1214 setContentType('application/json');
1216 // Set content type as text/html
1217 setContentType('text/html');
1223 // Rewrite message for output
1225 getMessage('MAILER_HAS_DIED'),
1231 // Is this AJAX mode again
1232 if (isAjaxOutputMode()) {
1233 // Load the message template
1234 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1236 // Output it as JSON encoded
1237 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation(compileRawCode($OUT))))));
1239 // Load the message template
1240 loadTemplate('app_exit_message', FALSE, $message);
1247 // Display parsing time and number of SQL queries in footer
1248 function displayParsingTime () {
1249 // Is the timer started?
1250 if (!isset($GLOBALS['__start_time'])) {
1256 $endTime = microtime(TRUE);
1258 // "Explode" both times
1259 $start = explode(' ', $GLOBALS['__start_time']);
1260 $end = explode(' ', $endTime);
1261 $runTime = $end[0] - $start[0];
1267 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1269 'run_time' => $runTime,
1270 'sql_time' => (getConfig('sql_time') * 1000),
1273 // Load the template
1274 $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1276 // Is debug enabled?
1277 if (isDebugModeEnabled()) {
1278 // Log loading of total includes
1279 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
1284 * Outputs an error message and backtrace to the user, by default a mail with
1285 * all relevant data is being mailed to the configured administrators.
1287 * This function shall be used "publicly" because of logging, admin notification
1288 * and double-call prevention (see first if() block) instead of app_exit().
1289 * app_exit() is more a "private" function and will only output a bug message to
1290 * the user, no email and no logging.
1292 * @param $file Function or file basename where the error came from
1293 * @param $line Line number where the error came from
1294 * @param $sendEmail Wether to send an email to all configured administrators
1297 function reportBug ($file, $line, $message = '', $sendEmail = TRUE) {
1298 // Is this already called?
1299 if (isset($GLOBALS[__FUNCTION__])) {
1301 print '[' . $file . ':' . $line . ':] ' . __FUNCTION__ . '() has already died! Message:' . $message . '<br />Backtrace:<pre>';
1302 debug_print_backtrace();
1306 // Set HTTP status to 500 (e.g. for AJAX requests)
1307 setHttpStatus('500 Internal Server Error');
1309 // Mark this function as called
1310 $GLOBALS[__FUNCTION__] = TRUE;
1315 // Is the optional message set?
1316 if (!empty($message)) {
1318 $debug = sprintf("Note: %s<br />\n",
1322 // @TODO Add a little more infos here
1323 logDebugMessage($file, $line, strip_tags($message));
1327 $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>';
1328 $debug .= debug_get_printable_backtrace();
1330 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1331 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1333 // Send an email? (e.g. not wanted for evaluation errors)
1334 if (($sendEmail === TRUE) && (!isInstaller()) && (isAdminRegistered())) {
1337 'message' => trim($message),
1338 'backtrace' => trim(debug_get_mailable_backtrace())
1341 // Send email to webmaster
1342 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1345 // Is there HTML/CSS/AJAX mode while debug-mode is enabled?
1346 if (((isDebugModeEnabled()) || (isInstaller())) && ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode()))) {
1348 app_exit($file, $line, $debug);
1349 } elseif (isAjaxOutputMode()) {
1350 // Load include (again?)
1351 loadIncludeOnce('inc/ajax-functions.php');
1356 // Set HTTP status to 500 again
1357 setHttpStatus('500 Internal Server Error');
1359 // Is AJAX output mode, then output message as JSON
1360 setAjaxReplyContent($debug);
1362 // Send it out to browser
1363 sendAjaxContent(TRUE);
1368 // Raw/image output mode and all other modes doesn't work well with text ...
1373 // Compile characters which are allowed in URLs
1374 function compileUriCode ($code, $simple = TRUE) {
1376 $test = trim($code);
1380 // Then abort here and return the original code
1384 // Compile these by default
1385 $charsCompile = array(
1410 // Compile constants
1411 if ($simple === FALSE) {
1413 array_unshift($charsCompile['from'], '{--', '--}');
1416 array_unshift($charsCompile['to'], '".', '."');
1419 // Compile QUOT and other non-HTML codes
1420 $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1421 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1423 // Return compiled code
1427 // Handle message codes from URL
1428 function handleCodeMessage () {
1430 if (isGetRequestElementSet('code')) {
1431 // Default extension is 'unknown'
1434 // Is extension given?
1435 if (isGetRequestElementSet('ext')) {
1436 $ext = getRequestElement('ext');
1439 // Convert the 'code' parameter from URL to a human-readable message
1440 $message = getMessageFromErrorCode(getRequestElement('code'));
1442 // Load message template
1443 loadTemplate('message', FALSE, $message);
1447 // Generates a 'extension foo out-dated' message
1448 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1449 // Is the extension empty?
1450 if (empty($ext_name)) {
1451 // This should not happen
1452 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1456 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1458 // Is an admin logged in?
1460 // Then output admin message
1461 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1464 // Return prepared message
1468 // Generates a 'extension foo inactive' message
1469 function generateExtensionInactiveMessage ($ext_name) {
1470 // Is the extension empty?
1471 if (empty($ext_name)) {
1472 // This should not happen
1473 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1477 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1479 // Is an admin logged in?
1481 // Then output admin message
1482 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1485 // Return prepared message
1489 // Generates a 'extension foo not installed' message
1490 function generateExtensionNotInstalledMessage ($ext_name) {
1491 // Is the extension empty?
1492 if (empty($ext_name)) {
1493 // This should not happen
1494 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1498 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1500 // Is an admin logged in?
1502 // Then output admin message
1503 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1506 // Return prepared message
1510 // Generates a message depending on if the extension is not installed or not
1512 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1516 // Is the extension not installed or just deactivated?
1517 switch (isExtensionInstalled($ext_name)) {
1518 case TRUE; // Deactivated!
1519 $message = generateExtensionInactiveMessage($ext_name);
1522 case FALSE; // Not installed!
1523 $message = generateExtensionNotInstalledMessage($ext_name);
1526 default: // Should not happen!
1527 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid state of extension %s detected.', $ext_name));
1528 $message = sprintf('Invalid state of extension %s detected.', $ext_name);
1532 // Return the message
1536 // Print code with line numbers
1537 function lineNumberCode ($code) {
1538 // By default copy the code
1541 if (!is_array($code)) {
1542 // We need an array, so try it with the new-line character
1543 $codeE = explode(PHP_EOL, $code);
1546 $count_lines = count($codeE);
1548 $r = 'Line | Code:<br />';
1549 foreach ($codeE as $line => $c) {
1550 $r .= '<div class="line"><span class="linenum">';
1551 if ($count_lines == 1) {
1554 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1559 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1562 return '<div class="code">' . $r . '</div>';
1565 // Determines the right page title
1566 function determinePageTitle () {
1570 // Config and database connection valid?
1571 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1572 // Title decoration enabled?
1573 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1574 $pageTitle .= '{%config,trim=title_left%} ';
1577 // Is there an extra title?
1578 if (isExtraTitleSet()) {
1580 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1584 $pageTitle .= '{?MAIN_TITLE?}';
1586 // Add title of module? (middle decoration will also be added!)
1587 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1588 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1591 // Get menu mode from module
1592 $menuMode = getMenuModeFromModule();
1594 // Add middle part (always in admin area!)
1595 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1596 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1599 // Add title decorations? (right)
1600 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1601 $pageTitle .= ' {%config,trim=title_right%}';
1603 } elseif ((isInstalled()) && (isAdminRegistered())) {
1604 // Installed, admin registered but no ext-sql_patches
1605 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1606 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1607 // Installed but no admin registered
1608 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1609 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1610 // Installation mode
1611 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1613 // Configuration not found
1614 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1616 // Do not add the fatal message in installation mode
1617 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1618 // Please report this
1619 reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1624 return decodeEntities($pageTitle);
1627 // Checks whethere there is a cache file there. This function is cached.
1628 function isTemplateCached ($prefix, $template) {
1629 // Is there cached this result?
1630 if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1632 $FQFN = generateCacheFqfn($prefix, $template);
1635 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1639 return $GLOBALS['template_cache'][$prefix][$template];
1642 // Flushes non-flushed template cache to disk
1643 function flushTemplateCache ($prefix, $template, $eval) {
1644 // Is this cache flushed?
1645 if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1647 $FQFN = generateCacheFqfn($prefix, $template);
1649 // Compile code another round for better performance and preserve $ signs
1650 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1652 // Is this a XML template?
1653 if ($prefix == 'xml') {
1654 // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1655 $eval = compactContent($eval);
1659 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1663 // Reads a template cache
1664 function readTemplateCache ($prefix, $template, $content) {
1666 if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1667 // This should not happen
1668 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1672 if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1674 $FQFN = generateCacheFqfn($prefix, $template);
1679 * WARNING: Do not replace this include() call with loadInclude() as it
1680 * would hide local variables away which is here required to make this
1685 // Is the template cache valid?
1686 if (!isset($templateContent)) {
1687 // Please clear your cache!
1688 reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1693 return $templateContent;
1696 // Escapes quotes (default is only double-quotes)
1697 function escapeQuotes ($str, $single = FALSE) {
1698 // Should we escape all?
1699 if ($single === TRUE) {
1700 // Escape all (including null)
1701 $str = addslashes($str);
1703 // Replace all chars at once
1704 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1707 // Return the escape'd string
1711 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1712 function escapeJavaScriptQuotes ($str) {
1713 // Replace all double-quotes and secure back-ticks
1714 $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1720 // Send out mails depending on the 'mod/modes' combination
1721 // @TODO Lame description for this function
1722 function sendModeMails ($mod, $modes) {
1724 $content = array ();
1727 if (fetchUserData(getMemberId())) {
1728 // Extract salt from cookie
1729 $salt = substr(getSession('u_hash'), 0, -40);
1731 // Now let's compare passwords
1732 $hash = encodeHashForCookie(getUserData('password'));
1734 // Does the hash match or should we change it?
1735 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1737 $content = getUserDataArray();
1739 // Clear/init the content variable
1740 $content['message'] = '';
1743 // @TODO Move this in a filter
1746 foreach ($modes as $mode) {
1748 case 'normal': break; // Do not add any special lines
1749 case 'email': // Email was changed!
1750 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1753 case 'password': // Password was changed
1754 $content['message'] = '{--MEMBER_CHANGED_PASSWORD--}' . PHP_EOL;
1758 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown mode %s detected.', $mode));
1759 $content['message'] = '{%message,MEMBER_UNKNOWN_MODE=' . $mode . '%}' . PHP_EOL . PHP_EOL;
1764 if (isExtensionActive('country')) {
1765 // Replace code with description
1766 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1769 // Merge content with data from POST
1770 $content = merge_array($content, postRequestArray());
1773 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1775 if (isAdminNotificationEnabled()) {
1776 // The admin needs to be notified about a profile change
1777 $message_admin = 'admin_mydata_notify';
1778 $subjectAdmin = '{--ADMIN_CHANGED_DATA_SUBJECT--}';
1781 $message_admin = '';
1785 // Set subject lines
1786 $subjectMember = '{--MEMBER_CHANGED_DATA--}';
1788 // Output success message
1789 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1792 default: // Unsupported module!
1793 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unsupported module %s detected.', $mod));
1794 $content['message'] = '<span class="bad">{%message,UNKNOWN_MODULE=' . $mod . '%}</span>';
1798 // Passwords mismatch
1799 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1802 // Could not load profile
1803 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1806 // Send email to user if required
1807 if ((!empty($subjectMember)) && (!empty($message)) && (!empty($content['userid']))) {
1809 sendEmail($content['userid'], $subjectMember, $message);
1812 // Send only if no other error has occured
1813 if ((!empty($subjectAdmin)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1815 sendAdminNotification($subjectAdmin, $message_admin, $content, getMemberId());
1816 } elseif (isAdminNotificationEnabled()) {
1817 // Cannot send mails to admin!
1818 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1821 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1825 displayMessage($content['message']);
1828 // Generates a 'selection box' from given array
1829 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1830 // options must be an array
1831 assert(is_array($options));
1836 // Use default value as array key?
1837 if ($useDefaultAsArray === TRUE) {
1839 $addKey = '[' . convertNullToZero($default) . ']';
1843 $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1844 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1847 if ($allowNone === TRUE) {
1849 $OUT .= '<option value="">{--SELECT_NONE--}</option>';
1852 // Walk through all options
1853 foreach ($options as $option) {
1854 // Default 'default' is not set
1855 $option['default'] = '';
1857 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1858 // Is default value same as given value?
1859 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default === $option[$optionKey])) {
1861 $option['default'] = ' selected="selected"';
1864 // Is 'nameElement' set?
1865 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1866 // Then set this as extraName, but lower-case
1867 $extraName = '_' . strtolower($option[$nameElement]);
1870 // Add the <option> entry from ...
1871 if (empty($optionContent)) {
1872 // Is a template name given?
1873 if (empty($templateName)) {
1874 // ... $name template
1875 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1877 // ... $templateName template
1878 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1881 // ... direct HTML code
1882 $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1886 // Finish selection box
1887 $OUT .= '</select>';
1891 'selection_box' => $OUT,
1894 // Load template and return it
1895 if (empty($templateName)) {
1896 // Use name from $name + $extraName
1897 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1899 // Use name from $templateName + $extraName
1900 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1904 // Prepares the header for HTML output
1905 function loadHtmlHeader () {
1908 * 1.) pre_page_header (mainly loads the page_header template and includes
1911 runFilterChain('pre_page_header');
1914 * Here can be something be added, but normally one of the two filters
1915 * around this line should do the job for you.
1919 * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1920 * to close the head-tag)
1921 * Include more header data here
1923 runFilterChain('post_page_header');
1926 // Adds page header and footer to output array element
1927 function addPageHeaderFooter () {
1931 // Add them all together. This is maybe to simple
1932 foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1933 // Add page part if set
1934 if (isset($GLOBALS[$pagePart])) {
1935 $OUT .= $GLOBALS[$pagePart];
1939 // Transfer $OUT to '__output'
1940 $GLOBALS['__output'] = $OUT;
1943 // Generates meta description for current module and 'what' value
1944 function generateMetaDescriptionCode () {
1945 // Only include from guest area and if ext-sql_patches has correct version
1946 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1947 // Output it directly
1948 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1951 // Initialize referral system
1952 initReferralSystem();
1955 // Generates an FQFN for template cache from the given template name
1956 function generateCacheFqfn ($prefix, $template) {
1958 if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1959 // Generate the FQFN
1960 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1961 '%s%s_compiled/%s/%s%s',
1971 return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1974 // "Fixes" null or empty string to count of dashes
1975 function fixNullEmptyToDashes ($str, $num) {
1976 // Use str as default
1980 if ((is_null($str)) || (trim($str) == '')) {
1982 $return = str_repeat('-', $num);
1985 // Return final string
1989 // Translates the "pool type" into human-readable
1990 function translatePoolType ($type) {
1991 // Return "translation"
1992 return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1995 // "Translates" given time unit
1996 function translateTimeUnit ($unit) {
1997 // Default is unknown
1998 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
2001 if (!isset($GLOBALS['time_units'][$unit])) {
2003 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
2005 // Translate it with generic function
2006 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
2013 // Displays given message in admin_settings_saved template
2014 function displayMessage ($message) {
2015 // Call inner function
2016 outputHtml(returnMessage($message));
2019 // Returns given message in admin_settings_saved template
2020 function returnMessage ($message) {
2021 // Load the template
2022 return loadTemplate('admin_settings_saved', TRUE, $message);
2025 // Displays given error message in admin_settings_unsaved template
2026 function displayErrorMessage ($message) {
2027 // Load the template
2028 outputHtml(returnErrorMessage($message));
2031 // Displays given error message in admin_settings_unsaved template
2032 function returnErrorMessage ($message) {
2033 // Load the template
2034 return loadTemplate('admin_settings_unsaved', TRUE, $message);
2037 // Generates a selection box for (maybe) given sex
2038 function generateSexSelectionBox ($selectedSex = '', $fieldName = 'sex') {
2039 // Start the HTML code
2040 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2043 $out .= generateOptions(
2058 $out .= '</select>';
2064 // Generates a selection box for given default value
2065 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2069 // Generate message id array
2070 foreach ($unitArray as $unit) {
2072 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2075 // Start the HTML code
2076 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2079 $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2082 $out .= '</select>';
2088 // Function to add style tag (whether display:none/block)
2089 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2090 // Is there foo_menu_javascript enabled?
2091 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2092 // Silently abort here, not enabled
2096 // Is action=mainAction?
2097 if ($action == $mainAction) {
2098 // Add "menu open" style
2099 return ' style="display:block"';
2101 return ' style="display:none"';
2105 // Function to add onclick attribute
2106 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2107 // Is there foo_menu_javascript enabled?
2108 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2109 // Silently abort here, not enabled
2114 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2120 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2121 function anonymizeSensitiveData ($data) {
2123 $data = trim($data);
2127 // Then add three dashes
2129 } elseif (isUrlValid($data)) {
2130 // Is a referrer, so is it black-listed?
2132 // Is admin, has always priority
2133 $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2134 } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
2135 // Yes, so replace it with text
2136 $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2138 // A member is viewing this referral URL
2139 $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2141 } elseif (isIp4AddressValid($data)) {
2142 // Is an IPv4 address
2143 $ipArray = explode('.', $data);
2145 // Only display first 2 octets
2146 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2149 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2152 // Return it (hopefully) anonymized
2157 * Removes all comments, tabs and new-line characters to compact the content
2159 * @param $uncompactedContent The uncompacted content
2160 * @return $compactedContent The compacted content
2162 function compactContent ($uncompactedContent) {
2163 // First, remove all tab/new-line/revert characters
2164 $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2166 // Make a space after >
2167 $compactedContent = str_replace(array('>', ' '), array('> ', ' '), $compactedContent);
2169 // Then regex all comments like <!-- //--> away
2170 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2172 // Do we have entries?
2173 if (isset($matches[0][0])) {
2175 foreach ($matches[0] as $match) {
2177 $compactedContent = str_replace($match, '', $compactedContent);
2181 // Return compacted content
2182 return $compactedContent;
2185 //-----------------------------------------------------------------------------
2186 // Template helper functions for EL code
2187 //-----------------------------------------------------------------------------
2189 // Color-switch helper function
2190 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2192 if (!isset($GLOBALS['color_switch'][$templateName])) {
2194 initTemplateColorSwitch($templateName);
2195 } elseif ($clear === FALSE) {
2196 // Switch color if called from loadTemplate()
2197 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2198 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2201 // Return CSS class name
2202 if ($return === TRUE) {
2203 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2204 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2208 // Helper function for extension registration link
2209 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2210 // Default is all non-productive
2211 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2213 // Is the given extension non-productive?
2214 if (isExtensionDeprecated($ext_name)) {
2216 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2217 } elseif (isExtensionProductive($ext_name)) {
2219 $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>';
2226 // Helper function to create bonus mail admin links
2227 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2228 // Call the inner function
2229 return generateAdminMailLinks('bonus', $bonusId);
2232 // Helper function to create member mail admin links
2233 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2234 // Call the inner function
2235 return generateAdminMailLinks('normal', $mailId);
2238 // Helper function to create a selection box for YES/NO configuration entries
2239 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2240 // Default is a "missing entry" warning
2241 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2243 // Generate the HTML code
2244 if (isConfigEntrySet($configEntry)) {
2245 // Configuration entry is found
2246 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2247 {%config,generateYesNoOptions=' . $configEntry . '%}
2255 // Helper function to create a selection box for YES/NO form fields
2256 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2257 // Generate the HTML code
2258 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2259 {%pipe,generateYesNoOptions%}
2266 // Helper function to create a selection box for YES/NO form fields, by NO is default
2267 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2268 // Generate the HTML code
2269 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2270 {%pipe,generateYesNoOptions=N%}
2277 // Helper function to add extra content for guest area (module=index and others)
2278 function doTemplateGuestFooterExtras ($templateName, $clear) {
2280 $filterData = array(
2281 // Name of used template
2282 'template' => $templateName,
2283 // Target array for gathered data
2285 // Where the HTML output will go
2289 // Run the filter chain
2290 $filterData = runFilterChain('guest_footer_extras', $filterData);
2293 return $filterData['__output'];
2296 // Helper function to add extra content for member area (module=login)
2297 function doTemplateMemberFooterExtras ($templateName, $clear) {
2298 // Is a member logged in?
2300 // This shall not happen
2301 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2305 $filterData = array(
2306 // Current user's id number
2307 'userid' => getMemberId(),
2308 // Name of used template
2309 'template' => $templateName,
2310 // Target array for gathered data
2312 // Where the HTML output will go
2316 // Run the filter chain
2317 $filterData = runFilterChain('member_footer_extras', $filterData);
2320 return $filterData['__output'];
2324 * Helper function to determine whether current userid is set, if none is set,
2325 * return a zero, else an EL code is being returned as of this function is used
2326 * only in templates.
2328 * @param $templateName Name of template (unused)
2329 * @param $clear Wether to clear something (unused)
2330 * @return $userId Wether zero or EL code snippet
2332 function doTemplateUserId ($templateName, $clear) {
2333 // By default no userid is set
2336 // Is there a user id currently set?
2337 if (isCurrentUserIdSet()) {
2338 // Then get the current user id
2339 $userId = getCurrentUserId();
2346 // Template helper function to generate "Terms&Conditions" link (EL code again)
2347 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2349 * Use default link by default ;-) This link, however, will become
2350 * deprecated once ext-terms is rolled out.
2352 $linkCode = '{%url=modules.php?module=index&what=agb%}';
2354 // Is ext-terms installed?
2355 if (isExtensionInstalled('terms')) {
2356 // Then use that link (only 'what' has changed)
2357 $linkCode = '{%url=modules.php?module=index&what=terms%}';
2360 // Return link (EL) code
2364 // Template helper function to create selection box for "locked points mode"
2365 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2367 $lockedModes = array(
2368 0 => array('mode' => 'LOCKED'),
2369 1 => array('mode' => 'UNLOCKED'),
2372 // Handle it over to generateSelectionBoxFromArray()
2373 $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2375 // Return prepared content
2379 // Template helper function to create selection box for payment method
2380 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2382 $paymentMethods = array(
2383 0 => array('method' => 'DIRECT'),
2384 1 => array('method' => 'REFERRAL'),
2387 // Handle it over to generateSelectionBoxFromArray()
2388 $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2390 // Return prepared content
2394 // Template helper function to create a deferrer code if URL is not empty
2395 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2396 // Is the URL not NULL and not empty?
2397 if ((!is_null($url)) && (!empty($url))) {
2398 // Set HTML with EL code
2399 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2402 // Return URL (or content) or dashes if empty
2403 return fixEmptyContentToDashes($url);
2406 // Load another template and return its content
2407 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = []) {
2408 // Load "the" template
2409 return loadTemplate($theTemplate, TRUE, $content);
2412 // Output HTML code for favicon.ico, if found
2413 function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
2414 // Default is not found
2417 // Check all common extensions
2418 foreach (array('ico', 'gif', 'png') as $extension) {
2419 // Is the file there?
2420 if (isFileReadable(getPath() . 'favicon.' . $extension)) {
2421 // Then use this and abort
2422 $out = '<link rel="shortcut icon" href="{%url=favicon.' . $extension . '%}" type="image/' . $extension . '" />';
2431 // Helper function to display referral id or hide it depending on settings
2432 function doTemplateDisplayReferralIdContent ($template, $clear = FALSE) {
2433 // Ddisplay the refid or make it editable?
2434 if (isDisplayRefidEnabled()) {
2435 // Load "hide" form template
2436 $out = loadTemplate('guest_register_refid_hide', TRUE);
2438 // Load template to enter it
2439 $out = loadTemplate('guest_register_refid', TRUE);
2446 // "Getter" for template base path
2447 function getTemplateBasePath ($part) {
2449 if (!isset($GLOBALS[__FUNCTION__][$part])) {
2451 $GLOBALS[__FUNCTION__][$part] = sprintf('%stemplates/%s/%s', getPath(), getLanguage(), $part);
2455 return $GLOBALS[__FUNCTION__][$part];
2458 // Removes comments with @DEPRECATED
2459 function removeDeprecatedComment ($output) {
2460 // Explode it into pieces ... ;)
2461 $lines = explode(chr(10), $output);
2465 foreach ($lines as $line) {
2466 // Is there a @DEPRECATED?
2467 if (isInString('@DEPRECATED', $line)) {
2473 $return .= $line . chr(13);
2476 // Returned cleaned content
2480 // Generates a selection box suitable for e.g. birthdays: day, month and year
2481 function generateDayMonthYearSelectionBox ($day, $month, $year) {
2482 // This depends on selected language
2483 switch (getLanguage()) {
2484 case 'de': // German date format
2485 $content = addSelectionBox('da', $day) . addSelectionBox('mo', $month) . addSelectionBox('ye', $year);
2488 default: // Default is the US date format... :)
2489 $content = addSelectionBox('mo', $month) . addSelectionBox('da', $day) . addSelectionBox('ye', $year);
2497 // Loads page header
2498 function loadPageHeader () {
2500 $GLOBALS['__page_header'] = '';
2502 // Is the header already sent?
2503 if (($GLOBALS['__header_sent'] != 1) && ($GLOBALS['__header_sent'] != 2)) {
2504 // Set default HTTP status to "200 OK"
2505 setHttpStatus('200 OK');
2507 // If not in CSS mode generate the header
2508 if ((!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode())) {
2509 // Prepare the header for HTML output
2514 if ($GLOBALS['__header_sent'] == '0') {
2515 $GLOBALS['__header_sent'] = 1;
2519 // Add BODY tag or not?
2520 // @TODO Find a way to not use direct module comparison
2521 if ((!isCssOutputMode()) && (!isRawOutputMode()) && ($GLOBALS['__header_sent'] == 1) && (getModule() != 'frametester') && (!isFramesetModeEnabled())) {
2522 loadTemplate('page_body');
2523 $GLOBALS['__header_sent'] = 2;
2527 // Loads page footer and calls doShutdown()
2528 function loadPageFooter () {
2530 $GLOBALS['__page_footer'] = '';
2532 // Footer disabled (e.g. CSS/AJAX/image output) or already sent?
2533 // 1234 5 54 45 5 5 543 3 443 3 443 3 44321
2534 if ((((!isset($GLOBALS['__footer_sent'])) || (($GLOBALS['__footer_sent'] != 1) && ($GLOBALS['__footer_sent'] != 2))) && (!isCssOutputMode()) && (!isAjaxOutputMode()) && (!isImageOutputMode()))) {
2535 // Run the filter, sweet huh?
2536 runFilterChain('page_footer');
2539 $GLOBALS['__page_footer'] .= loadTemplate('page_footer', TRUE);
2542 // Footer has been reached
2543 $GLOBALS['__footer_sent'] = 1;