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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2012 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Wrapper until we merged to the EL branch
44 function preCompileCode ($code, $full = TRUE) {
45 return compileCode($code, $full);
48 // Setter for 'is_template_html'
49 function enableTemplateHtml ($enable = TRUE) {
50 $GLOBALS['is_template_html'] = (bool) $enable;
53 // Checks whether the template is HTML or not by previously set flag
55 function isTemplateHtml () {
56 // Is the output_mode other than 0 (HTML), then no comments are enabled
57 if (!isHtmlOutputMode()) {
62 return $GLOBALS['is_template_html'];
66 // Wrapper for writing debug informations to the browser
67 function debugOutput ($message) {
68 outputHtml('<div class="debug_message">' . $message . '</div>');
71 // "Fixes" an empty string into three dashes (use for templates)
72 function fixEmptyContentToDashes ($str) {
73 // Call inner function
74 $str = fixNullEmptyToDashes($str, 3);
81 function initTemplateColorSwitch ($template) {
82 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'INIT:' . $template);
83 $GLOBALS['color_switch'][$template] = 2;
86 // "Getter" for color switch code
87 function getColorSwitchCode ($template) {
89 $code = "{DQUOTE} . doTemplateColorSwitch('" . $template . "', FALSE, FALSE) . {DQUOTE}";
95 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
96 function outputHtml ($htmlCode = NULL, $newLine = TRUE) {
98 if (!isset($GLOBALS['__output'])) {
99 $GLOBALS['__output'] = '';
102 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getOutputMode()=' . getOutputMode() . ',htmlCode(length)=' . strlen($htmlCode) . ',output(length)=' . strlen($GLOBALS['__output']));
103 // Is there HTML-Code here?
104 if ((!is_null($htmlCode)) && (!empty($htmlCode))) {
105 // Yes, so we handle it as you have configured
106 switch (getOutputMode()) {
108 // But if PHP is caching, then we don't need to do that
109 if (getPhpCaching() == 'on') {
110 // Output into PHP's internal buffer
111 outputRawCode($htmlCode);
113 // That's why you don't need any \n at the end of your HTML code... :-)
114 if ($newLine === TRUE) {
115 outputRawCode(PHP_EOL);
118 // Render mode for old or lame servers...
119 $GLOBALS['__output'] .= $htmlCode;
121 // That's why you don't need any \n at the end of your HTML code... :-)
122 if ($newLine === TRUE) {
123 $GLOBALS['__output'] .= PHP_EOL;
129 // If we are switching from 'render' to 'direct' mode, all data in '__output' must be flushed and cleared
130 if ((!empty($GLOBALS['__output'])) && (getPhpCaching() != 'on')) {
131 outputRawCode($GLOBALS['__output']);
132 $GLOBALS['__output'] = '';
135 // The same as above... ^
136 outputRawCode($htmlCode);
137 if ($newLine === TRUE) {
138 outputRawCode(PHP_EOL);
143 // Huh, something goes wrong or maybe you have edited config.php ???
144 reportBug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--NO_RENDER_DIRECT--}');
147 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['http_header'])) || (count($GLOBALS['http_header']) == 0)) && (!isRawOutputMode())) {
148 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getPhpCaching()=' . getPhpCaching() . ',isset(http_header)=' . intval(isset($GLOBALS['http_header'])) . ',getScriptOutputMode()=' . getScriptOutputMode() . '');
149 // Output cached HTML code
150 $GLOBALS['__output'] = ob_get_contents();
152 // Clear output buffer for later output if output is found
153 if (!empty($GLOBALS['__output'])) {
157 // Send all HTTP headers
160 // Compile and run finished rendered HTML code
161 compileFinalOutput();
163 // Output code here, DO NOT REMOVE! ;-)
164 outputRawCode($GLOBALS['__output']);
165 } elseif ((getOutputMode() == 'render') && (!empty($GLOBALS['__output'])) && (!isRawOutputMode())) {
166 // Send all HTTP headers
169 // Compile and run finished rendered HTML code
170 compileFinalOutput();
172 // Output code here, DO NOT REMOVE! ;-)
173 outputRawCode($GLOBALS['__output']);
175 // And flush all headers
180 // Compiles the final output
181 function compileFinalOutput () {
182 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ',getScriptOutputMode()=' . getScriptOutputMode() . ' - ENTERED!');
183 // Is this function called?
184 if (isset($GLOBALS[__FUNCTION__])) {
186 reportBug(__FUNCTION__, __LINE__, 'Double call of ' . __FUNCTION__ . ' causes problems with sent headers.');
189 // Mark this function as called
190 $GLOBALS[__FUNCTION__] = TRUE;
192 // Add page header and footer
193 addPageHeaderFooter();
194 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ' - After addPageHeaderFooter() call.');
196 // Do the final (general) compilation
197 $GLOBALS['__output'] = doFinalCompilation($GLOBALS['__output']);
199 // Compile any other things out
200 $GLOBALS['__output'] = compileUriCode($GLOBALS['__output']);
202 // Extension 'rewrite' installed?
203 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
204 $GLOBALS['__output'] = rewriteLinksInCode($GLOBALS['__output']);
209 * @TODO On some pages this is buggy
210 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
211 // Compress it for HTTP gzip
212 $GLOBALS['__output'] = gzencode($GLOBALS['__output'], 9);
215 addHttpHeader('Content-Encoding: gzip');
216 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
217 // Compress it for HTTP deflate
218 $GLOBALS['__output'] = gzcompress($GLOBALS['__output'], 9);
221 addHttpHeader('Content-Encoding: deflate');
226 addHttpHeader('Content-Length: ' . strlen($GLOBALS['__output']));
232 // Main compilation loop
233 function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE) {
234 // Insert comments? (Only valid with HTML templates, of course)
235 enableTemplateHtml($insertComments);
241 while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($count < 7)) {
242 // Init common variables
247 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
248 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), $enableCodes)) . '";';
249 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
251 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
252 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
254 // Was that eval okay?
255 if (empty($newContent)) {
256 // Something went wrong!
257 reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', FALSE);
263 // Compile the final code if insertComments is true
264 if ($insertComments == TRUE) {
265 // ... because SQL queries shall keep OPEN_CONFIG and such in
266 $code = compileRawCode($code);
273 // Add debugging data in HTML code, if mode is enabled
274 if ((isDebugModeEnabled()) && ($insertComments === TRUE) && (isHtmlOutputMode())) {
276 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isDebugModeEnabled()=' . intval(isDebugModeEnabled()) . ',insertComments=' . intval($insertComments) . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()));
277 $code .= '<!-- Total compilation loop=' . $count . ' //-->';
280 // Return the compiled code
284 // Output the raw HTML code
285 function outputRawCode ($htmlCode) {
286 // Output stripped HTML code to avoid broken JavaScript code, etc.
287 print(str_replace('{BACK}', chr(92), $htmlCode));
289 // Flush the output if only getPhpCaching() is not 'on'
290 if (getPhpCaching() != 'on') {
296 // Load a template file and return it's content (only it's name; do not use ' or ")
297 function loadTemplate ($template, $return = FALSE, $content = array(), $compileCode = TRUE) {
298 // @TODO Remove these sanity checks if all is fine
299 if (!is_bool($return)) {
300 // $return has to be boolean
301 reportBug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
302 } elseif (!is_string($template)) {
303 // $template has to be string
304 reportBug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
307 // Init returned content
310 // Set current template
311 $GLOBALS['current_template'] = $template;
314 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('html', $template))) {
315 // Evaluate the cache
316 $templateContent = readTemplateCache('html', $template, $content);
318 // Better remove array element which is only needed in uncached mode
319 unset($GLOBALS['template_eval']['html'][$template]);
320 } elseif (!isset($GLOBALS['template_eval']['html'][$template])) {
321 // Make all template names lowercase
322 $template = strtolower($template);
325 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
326 $extraPath = detectExtraTemplatePath('html', $template);
329 $FQFN = $basePath . $extraPath . $template . '.tpl';
330 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Template ' . $template . ' is solved to FQFN=' . $FQFN);
332 // Does the special template exists?
333 if (!isFileReadable($FQFN)) {
334 // Reset to default template
335 $FQFN = $basePath . $template . '.tpl';
338 // Now does the final template exists?
339 if (isFileReadable($FQFN)) {
340 // Count the template load
341 incrementConfigEntry('num_templates');
343 // The local file does exists so we load it. :)
344 $GLOBALS['template_content']['html'][$template] = readFromFile($FQFN);
346 // Is there to compile the code?
347 if ((isInString('$', $GLOBALS['template_content']['html'][$template])) || (isInString('{--', $GLOBALS['template_content']['html'][$template])) || (isInString('{?', $GLOBALS['template_content']['html'][$template])) || (isInString('{%', $GLOBALS['template_content']['html'][$template]))) {
348 // Normal HTML output?
349 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
350 // Add surrounding HTML comments to help finding bugs faster
351 $code = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
353 // Prepare eval() command
354 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
355 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($code), TRUE, $compileCode) . '";';
356 } elseif (substr($template, 0, 3) == 'js_') {
357 // JavaScripts don't like entities, dollar signs and timings
358 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
359 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
360 } elseif (isAjaxOutputMode()) {
361 // AJAX (JSON content)
362 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
363 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '";';
365 // Prepare eval() command, other output doesn't like entities, maybe
366 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
367 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
369 } elseif (isHtmlOutputMode()) {
370 // Add surrounding HTML comments to help finding bugs faster
371 $templateContent = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
373 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($templateContent), TRUE, $compileCode) . '";';
374 } elseif (isAjaxOutputMode()) {
375 // AJAX (JSON content)
376 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
377 $GLOBALS['template_eval']['html'][$template] = '$templateContent = "' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '";';
380 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
381 $GLOBALS['template_eval']['html'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), TRUE, $compileCode) . '");';
383 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
384 // Only admins shall see this warning or when installation mode is active
385 $templateContent = '<div class="para">
392 {--TEMPLATE_CONTENT--}:
393 <pre>' . print_r($content, TRUE) . '</pre>
397 $GLOBALS['template_eval']['html'][$template] = '404';
402 if ((isset($GLOBALS['template_eval']['html'][$template])) && ($GLOBALS['template_eval']['html'][$template] != '404')) {
404 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
405 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['html'][$template]).'</pre>');
406 eval($GLOBALS['template_eval']['html'][$template]);
407 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
410 // Is there some content to output or return?
411 if ((empty($templateContent)) && (isDebugModeEnabled())) {
412 // Warning, empty output!
413 return 'E:' . $template . ',content=<pre>' . print_r($content, TRUE) . '</pre>';
416 // Not empty so let's put it out! ;)
417 if ($return === TRUE) {
418 // Return the HTML code
419 return $templateContent;
422 outputHtml($templateContent);
426 // Detects the extra template path from given template name
427 function detectExtraTemplatePath ($prefix, $template) {
432 if (!isset($GLOBALS['extra_path'][$prefix][$template])) {
433 // Check for admin/guest/member/etc. templates
434 if (substr($template, 0, 6) == 'admin_') {
435 // Admin template found
436 $extraPath = 'admin/';
437 } elseif (substr($template, 0, 6) == 'guest_') {
438 // Guest template found
439 $extraPath = 'guest/';
440 } elseif (substr($template, 0, 7) == 'member_') {
441 // Member template found
442 $extraPath = 'member/';
443 } elseif (substr($template, 0, 7) == 'select_') {
444 // Selection template found
445 $extraPath = 'select/';
446 } elseif (substr($template, 0, 8) == 'install_') {
447 // Installation template found
448 $extraPath = 'install/';
449 } elseif (substr($template, 0, 4) == 'ext_') {
450 // Extension template found
452 } elseif (substr($template, 0, 3) == 'la_') {
453 // 'Logical-area' template found
455 } elseif (substr($template, 0, 3) == 'js_') {
456 // JavaScript template found
458 } elseif (substr($template, 0, 5) == 'menu_') {
459 // Menu template found
460 $extraPath = 'menu/';
462 // Test for extension
463 $test = substr($template, 0, strpos($template, '_'));
465 // Probe for valid extension name
466 if (isExtensionNameValid($test)) {
467 // Set extra path to extension's name
468 $extraPath = $test . '/';
473 $GLOBALS['extra_path'][$prefix][$template] = $extraPath;
477 return $GLOBALS['extra_path'][$prefix][$template];
480 // Loads an email template and compiles it
481 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = TRUE) {
482 // Make sure all template names are lowercase!
483 $template = strtolower($template);
485 // Set current template
486 $GLOBALS['current_template'] = $template;
488 // Is content an array?
489 if (is_array($content)) {
490 // Add expiration to array
491 if ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
492 // Will never expire!
493 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
494 } elseif ((isExtensionInstalled('autopurge')) && (isConfigEntrySet('auto_purge'))) {
495 // Create nice date string
496 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
499 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
504 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('email', $template))) {
505 // Evaluate the cache
506 $templateContent = readTemplateCache('email', $template, $content);
508 // Better remove array element which is need only in uncached mode
509 unset($GLOBALS['template_eval']['email'][$template]);
510 } elseif (!isset($GLOBALS['template_eval']['email'][$template])) {
512 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
515 $extraPath = detectExtraTemplatePath('email', $template);
517 // Generate full FQFN
518 $FQFN = $basePath . $extraPath . $template . '.tpl';
520 // Does the special template exists?
521 if (!isFileReadable($FQFN)) {
522 // Reset to default template
523 $FQFN = $basePath . $template . '.tpl';
526 // Now does the final template exists?
527 $templateContent = '';
528 if (isFileReadable($FQFN)) {
529 // The local file does exists so we load it. :)
530 $GLOBALS['template_content']['email'][$template] = readFromFile($FQFN);
533 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
534 $GLOBALS['template_eval']['email'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['email'][$template])) . '");';
535 } elseif (!empty($template)) {
536 // Template file not found
537 $templateContent = '<div class="para">
538 {--TEMPLATE_404--}: ' . $template . '
541 {--TEMPLATE_CONTENT--}:
542 <pre>' . print_r($content, TRUE) . '</pre>
545 // Don't cache this, as there is no template to cache
546 $GLOBALS['template_eval']['email'][$template] = '404';
548 // Debug mode not active? Then remove the HTML tags
549 if (!isDebugModeEnabled()) {
551 $templateContent = secureString($templateContent);
554 // No template name supplied!
555 $templateContent = '{--NO_TEMPLATE_SUPPLIED--}';
556 $GLOBALS['template_eval']['email'][$template] = '404';
560 // Is there something to eval?
561 if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
563 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
564 //* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
565 eval($GLOBALS['template_eval']['email'][$template]);
566 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
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 // Is the code a string or shall we not compile?
652 if ((!is_string($code)) || ($compileCode === FALSE)) {
653 // Silently return it
657 // Init replacement-array with smaller set of security characters
658 $secChars = $GLOBALS['url_chars'];
660 // Select full set of chars to replace when we e.g. want to compile URLs
661 if ($full === TRUE) {
662 $secChars = $GLOBALS['security_chars'];
665 // Compile more through a filter
666 $code = runFilterChain('compile_code', $code);
668 // First compile these chars
669 array_unshift($secChars['to'] , '{--' , '--}');
670 array_unshift($secChars['from'], '{%message,', '%}' );
672 // Compile QUOT and other non-HTML codes
673 $code = str_replace($secChars['to'], $secChars['from'], $code);
675 // Find $content[bla][blub] entries
676 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
677 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
679 // Are some matches found?
680 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
681 // Replace all matches
682 $matchesFound = array();
683 foreach ($matches[0] as $key => $match) {
684 // Fuzzy look has failed by default
687 // Fuzzy look on match if already found
688 foreach ($matchesFound as $found => $set) {
690 $test = substr($found, 0, strlen($match));
692 // Does this entry exist?
693 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
694 if ($test == $match) {
696 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
703 if ($fuzzyFound === TRUE) {
707 // Take all string elements
708 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
709 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
710 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
711 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
712 $code = str_replace($match, '".' . $newMatch . '."', $code);
713 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
714 $matchesFound[$match] = TRUE;
715 } elseif (!isset($matchesFound[$match])) {
717 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
718 $code = str_replace($match, '".' . $match . '."', $code);
719 $matchesFound[$match] = 1;
721 // Everthing else should be a least logged
722 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
728 * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
729 * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
730 * therefore the variable's value won't be inserted. This is why
731 * {COMPILE_DOLLAR} is being used in above loop and at the end of this
732 * function being replace with the original dollar sign again.
734 preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
736 // Are some matches found?
737 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
738 // Scan all matches for not $content
739 foreach ($matches[0] as $match) {
741 $match = trim($match);
744 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
746 // Is the first part not $content/$userid and not empty?
747 // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
748 if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
749 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
750 // Then replace $ with {DOLLAR}
751 $matchSecured = str_replace('$', '{DOLLAR}', $match);
753 // And in $code as well
754 $code = str_replace($match, $matchSecured, $code);
759 // Replace {COMPILE_DOLLAR} back to dollar sign
760 $code = str_replace('{COMPILE_DOLLAR}', '$', $code);
767 function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'form_select') {
771 // This is a yes/no selection only!
772 if (isValidId($id)) $prefix .= '[' . $id . ']';
773 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
775 // Begin with regular selection box here
776 if (!empty($prefix)) $prefix .= '_';
778 if (isValidId($id)) $type2 .= '[' . $id . ']';
779 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
787 // Use configured min age or fixed?
788 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
790 $startYear = $year - getConfig('min_age');
793 $startYear = $year - 16;
796 // Calculate earliest year (100 years old people can still enter Internet???)
797 $minYear = $year - 100;
799 // Check if the default value is larger than minimum and bigger than actual year
800 if (($default > $minYear) && ($default >= $year)) {
801 for ($idx = $year; $idx < ($year + 11); $idx++) {
802 $OUT .= '<option value="' . $idx . '"';
803 if ($default == $idx) $OUT .= ' selected="selected"';
804 $OUT .= '>' . $idx . '</option>';
806 } elseif ($default == -1) {
807 // Current year minus 1
808 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
809 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
812 // Get current year and subtract the configured minimum age
813 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
815 // Construct year selection list
816 for ($idx = $minYear; $idx <= $startYear; $idx++) {
817 $OUT .= '<option value="' . $idx . '"';
818 if ($default == $idx) $OUT .= ' selected="selected"';
819 $OUT .= '>' . $idx . '</option>';
825 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
826 $OUT .= '<option value="' . $idx . '"';
827 if ($default == $idx) $OUT .= ' selected="selected"';
828 $OUT .= '>' . $descr . '</option>';
832 case 'mn': // Months, numeric
833 for ($idx = 0; $idx <= 12; $idx++) {
834 $OUT .= '<option value="' . $idx . '"';
835 if ($default == $idx) $OUT .= ' selected="selected"';
836 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
841 for ($idx = 0; $idx <= 4; $idx++) {
842 $OUT .= ' <option value="' . $idx . '"';
843 if ($default == $idx) $OUT .= ' selected="selected"';
844 $OUT .= '>' . $idx . '</option>';
849 for ($idx = 0; $idx <= 31; $idx++) {
850 $OUT .= '<option value="' . $idx . '"';
851 if ($default == $idx) $OUT .= ' selected="selected"';
852 $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
857 for ($idx = 0; $idx <= 23; $idx++) {
858 if (strlen($idx) == 1) $idx = 0 . $idx;
859 $OUT .= '<option value="' . $idx . '"';
860 if ($default == $idx) $OUT .= ' selected="selected"';
861 $OUT .= '>' . $idx . '</option>';
865 case 'mi': // Minutes
866 case 'se': // Seconds
867 for ($idx = 0; $idx <= 59; $idx+=5) {
868 if (strlen($idx) == 1) $idx = 0 . $idx;
869 $OUT .= '<option value="' . $idx . '"';
870 if ($default == $idx) $OUT .= ' selected="selected"';
871 $OUT .= '>' . $idx . '</option>';
876 $OUT .= '<option value="Y"';
877 if ($default == 'Y') $OUT .= ' selected="selected"';
878 $OUT .= '>{--YES--}</option><option value="N"';
879 if ($default != 'Y') $OUT .= ' selected="selected"';
880 $OUT .= '>{--NO--}</option>';
883 default: // Not detected
884 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ',default=' . $default . ',prefix=' . $prefix . ',id[' . gettype($id) . ']=' . $id . ',class=' . $class . ' - is not supported.');
891 // Insert the code in $img_code into jpeg or PNG image
892 function generateImageOrCode ($img_code, $headerSent = TRUE) {
893 // Is the code size oversized or shouldn't we display it?
894 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
895 // Stop execution of function here because of over-sized code length
896 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
897 } elseif ($headerSent === FALSE) {
898 // Return an HTML code here
899 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
903 $img = sprintf("%s/theme/%s/images/code_bg.%s",
910 if (isFileReadable($img)) {
912 switch (getImgType()) {
913 case 'jpg': // Okay, load image and hide all errors
914 $image = imagecreatefromjpeg($img);
917 case 'png': // Okay, load image and hide all errors
918 $image = imagecreatefrompng($img);
922 // Silently log the error
923 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
927 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
928 $text_color = imagecolorallocate($image, 0, 0, 0);
930 // Insert code into image
931 imagestring($image, 5, 14, 2, $img_code, $text_color);
934 setContentType('image/' . getImgType());
936 // Output image with matching image factory
937 switch (getImgType()) {
938 case 'jpg': imagejpeg($image); break;
939 case 'png': imagepng($image); break;
942 // Remove image from memory
943 imagedestroy($image);
946 // Create selection box or array of splitted timestamp
947 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE) {
948 // Do not continue if ONE_DAY is absend
949 if (!isConfigEntrySet('ONE_DAY')) {
951 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
954 // Calculate 2-seconds timestamp
955 $stamp = round($timestamp);
956 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
958 // Is there a leap year?
960 $TEST = getYear() / 4;
962 $M2 = getMonth(time() + $timestamp);
964 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
965 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
966 $SWITCH = getOneDay();
969 // First of all years...
970 $year = abs(floor($timestamp / (31536000 + $SWITCH)));
971 //* DEBUG: */ debugOutput('year=' . $year);
973 $month = abs(floor($timestamp / 2628000 - $year * 12));
974 //* DEBUG: */ debugOutput('month=' . $month);
976 $week = abs(floor($timestamp / 604800 - $year * ((365 + $SWITCH / getOneDay()) / 7) - ($month / 12 * (365 + $SWITCH / getOneDay()) / 7)));
977 //* DEBUG: */ debugOutput('week=' . $week);
979 $day = abs(floor($timestamp / 86400 - $year * (365 + $SWITCH / getOneDay()) - ($month / 12 * (365 + $SWITCH / getOneDay())) - $week * 7));
980 //* DEBUG: */ debugOutput('day=' . $day);
982 $hour = abs(floor($timestamp / 3600 - $year * (365 + $SWITCH / getOneDay()) * 24 - ($month / 12 * (365 + $SWITCH / getOneDay()) * 24) - $week * 7 * 24 - $day * 24));
983 //* DEBUG: */ debugOutput('hour=' . $hour);
985 $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));
986 //* DEBUG: */ debugOutput('minute=' . $minute);
987 // And at last seconds...
988 $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));
989 //* DEBUG: */ debugOutput('second=' . $second);
991 // Is seconds zero and time is < 60 seconds?
992 if (($second < 1) && ($timestamp < 60)) {
994 $second = round($timestamp);
997 // Put all calculated values in array
1009 // Now we convert them in seconds...
1011 if ($asArray === TRUE) {
1012 // Just put data array out
1017 // Time unit -> field name
1018 'unit_field' => array(
1027 // Time unit -> label
1028 'unit_label' => array(
1040 $OUT = '<div align="' . $align . '">';
1041 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1044 // "Walk" through all units
1045 foreach ($units['unit_field'] as $unit => $field) {
1046 // Is this displayed or zero?
1047 if (isInString($unit, $display) || (empty($display))) {
1048 // @TODO <label for="' . $prefix . '_' . $field . '"></<label> not working here
1049 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_' . $units['unit_label'][$unit] . '--}</div></td>';
1053 // Close table row and open new one
1057 // "Walk" through all units again
1058 foreach ($units['unit_field'] as $unit => $field) {
1060 if (isInString($unit, $display) || (empty($display))) {
1061 // Generate year selection
1062 $OUT .= '<td align="center">';
1063 $OUT .= addSelectionBox($field, $data[$unit], $prefix, NULL, 'mini_select');
1066 $OUT .= '<input type="hidden" name="' . $prefix . '_' . $field . '" value="0" />';
1076 // Return generated HTML code or data array
1080 // Generate a list of administrative links to a given userid
1081 function generateMemberAdminActionLinks ($userid) {
1082 // Make sure userid is a number
1083 if ($userid != bigintval($userid)) {
1084 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1087 // Define all main targets
1088 $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1091 $status = getFetchedUserData('userid', $userid, 'status');
1093 // Begin of navigation links
1096 foreach ($targetArray as $target) {
1097 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $target . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1098 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1099 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1100 // Locked accounts shall be unlocked
1101 $OUT .= 'UNLOCK_USER';
1102 } elseif ($target == 'del_user') {
1103 // @TODO Deprecate this thing
1104 $OUT .= 'DELETE_USER';
1106 // All other status is fine
1107 $OUT .= strtoupper($target);
1109 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1110 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1111 // Locked accounts shall be unlocked
1112 $OUT .= 'UNLOCK_USER';
1113 } elseif ($target == 'del_user') {
1114 // @TODO Deprecate this thing
1115 $OUT .= 'DELETE_USER';
1117 // All other status is fine
1118 $OUT .= strtoupper($target);
1120 $OUT .= '--}</a></span>|';
1123 // Add special link, in case of the account is unconfirmed
1124 if ($status == 'UNCONFIRMED') {
1126 $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>|';
1129 // Finish navigation link
1130 $OUT = substr($OUT, 0, -1) . ']';
1136 // Generate an email link
1137 function generateEmailLink ($email, $table = 'admins') {
1138 // Default email link (INSECURE! Spammer can read this by harvester programs)
1139 $EMAIL = 'mailto:' . $email;
1141 // Check for several extensions
1142 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1143 // Create email link for contacting admin in guest area
1144 $EMAIL = generateAdminEmailLink($email);
1145 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1146 // Create email link for contacting a member within admin area (or later in other areas, too?)
1147 $EMAIL = generateUserEmailLink($email);
1148 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1149 // Create email link to contact sponsor within admin area (or like the link above?)
1150 $EMAIL = generateSponsorEmailLink($email);
1153 // Return email link
1158 * Outputs an error message in a "fashioned way" to the user, by putting it into
1159 * a nice looking web page, if one of HTML or CSS output mode is active.
1161 * Please use reportBug() instead of this function. reportBug() has more helpful
1162 * functionality like logging and admin notification (which you can configure
1163 * through your admin area).
1165 * @param $F Function or file basename where the error came from
1166 * @param $L Line number where the error came from
1167 * @param $message Message which shall be output to web
1170 function app_exit ($F, $L, $message) {
1171 // Check if Script is already dieing and not let it kill itself another 1000 times
1172 if (isset($GLOBALS['app_died'])) {
1173 // Script tried to kill itself twice
1174 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1177 // Make sure, that the script realy realy diese here and now
1178 $GLOBALS['app_died'] = TRUE;
1180 // Is this AJAX mode?
1181 if (isAjaxOutputMode()) {
1182 // Set content type as application/json
1183 setContentType('application/json');
1185 // Set content type as text/html
1186 setContentType('text/html');
1190 loadIncludeOnce('inc/header.php');
1192 // Rewrite message for output
1194 getMessage('MAILER_HAS_DIED'),
1200 // Is this AJAX mode again
1201 if (isAjaxOutputMode()) {
1202 // Load the message template
1203 $OUT = loadTemplate('ajax_app_exit_message', TRUE, $message);
1205 // Output it as JSON encoded
1206 outputHtml(encodeJson(array('reply_content' => urlencode(doFinalCompilation($OUT)))));
1208 // Load the message template
1209 loadTemplate('app_exit_message', FALSE, $message);
1213 loadIncludeOnce('inc/footer.php');
1216 // Display parsing time and number of SQL queries in footer
1217 function displayParsingTime () {
1218 // Is the timer started?
1219 if (!isset($GLOBALS['__start_time'])) {
1225 $endTime = microtime(TRUE);
1227 // "Explode" both times
1228 $start = explode(' ', $GLOBALS['__start_time']);
1229 $end = explode(' ', $endTime);
1230 $runTime = $end[0] - $start[0];
1236 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1238 'run_time' => $runTime,
1239 'sql_time' => (getConfig('sql_time') * 1000),
1242 // Load the template
1243 $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1247 * Outputs an error message and backtrace to the user, by default a mail with
1248 * all relevant data is being mailed to the configured administrators.
1250 * This function shall be used "publicly" because of logging, admin notification
1251 * and double-call prevention (see first if() block) instead of app_exit().
1252 * app_exit() is more a "private" function and will only output a bug message to
1253 * the user, no email and no logging.
1255 * @param $F Function or file basename where the error came from
1256 * @param $L Line number where the error came from
1257 * @param $sendEmail Wether to send an email to all configured administrators
1260 function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
1261 // Is this already called?
1262 if (isset($GLOBALS[__FUNCTION__])) {
1264 print '[' . $F . ':' . $L . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
1265 debug_print_backtrace();
1269 // Set HTTP status to 500 (e.g. for AJAX requests)
1270 setHttpStatus('500 Internal Server Error');
1272 // Mark this function as called
1273 $GLOBALS[__FUNCTION__] = TRUE;
1278 // Is the optional message set?
1279 if (!empty($message)) {
1281 $debug = sprintf("Note: %s<br />\n",
1285 // @TODO Add a little more infos here
1286 logDebugMessage($F, $L, strip_tags($message));
1290 $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>';
1291 $debug .= debug_get_printable_backtrace();
1293 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1294 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1296 // Send an email? (e.g. not wanted for evaluation errors)
1297 if (($sendEmail === TRUE) && (!isInstallationPhase())) {
1300 'message' => trim($message),
1301 'backtrace' => trim(debug_get_mailable_backtrace())
1304 // Send email to webmaster
1305 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1308 // Is there HTML/CSS/AJAX mode?
1309 if (((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode())) && (isDebugModeEnabled())) {
1311 app_exit($F, $L, $debug);
1313 // Raw/image output mode and all other modes doesn't work well with text ...
1318 // Compile characters which are allowed in URLs
1319 function compileUriCode ($code, $simple = TRUE) {
1321 $test = trim($code);
1325 // Then abort here and return the original code
1329 // Compile these by default
1330 $charsCompile = array(
1355 // Compile constants
1356 if ($simple === FALSE) {
1358 array_unshift($charsCompile['from'], '{--', '--}');
1361 array_unshift($charsCompile['to'], '".', '."');
1364 // Compile QUOT and other non-HTML codes
1365 $code = str_replace($charsCompile['from'], $charsCompile['to'], $code);
1366 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1368 // Return compiled code
1372 // Handle message codes from URL
1373 function handleCodeMessage () {
1375 if (isGetRequestElementSet('code')) {
1376 // Default extension is 'unknown'
1379 // Is extension given?
1380 if (isGetRequestElementSet('ext')) {
1381 $ext = getRequestElement('ext');
1384 // Convert the 'code' parameter from URL to a human-readable message
1385 $message = getMessageFromErrorCode(getRequestElement('code'));
1387 // Load message template
1388 loadTemplate('message', FALSE, $message);
1392 // Generates a 'extension foo out-dated' message
1393 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1394 // Is the extension empty?
1395 if (empty($ext_name)) {
1396 // This should not happen
1397 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1401 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1403 // Is an admin logged in?
1405 // Then output admin message
1406 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1409 // Return prepared message
1413 // Generates a 'extension foo inactive' message
1414 function generateExtensionInactiveMessage ($ext_name) {
1415 // Is the extension empty?
1416 if (empty($ext_name)) {
1417 // This should not happen
1418 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1422 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1424 // Is an admin logged in?
1426 // Then output admin message
1427 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1430 // Return prepared message
1434 // Generates a 'extension foo not installed' message
1435 function generateExtensionNotInstalledMessage ($ext_name) {
1436 // Is the extension empty?
1437 if (empty($ext_name)) {
1438 // This should not happen
1439 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1443 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1445 // Is an admin logged in?
1447 // Then output admin message
1448 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1451 // Return prepared message
1455 // Generates a message depending on if the extension is not installed or not
1457 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1461 // Is the extension not installed or just deactivated?
1462 switch (isExtensionInstalled($ext_name)) {
1463 case TRUE; // Deactivated!
1464 $message = generateExtensionInactiveMessage($ext_name);
1467 case FALSE; // Not installed!
1468 $message = generateExtensionNotInstalledMessage($ext_name);
1471 default: // Should not happen!
1472 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1473 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1477 // Return the message
1481 // Print code with line numbers
1482 function linenumberCode ($code) {
1483 // By default copy the code
1486 if (!is_array($code)) {
1487 // We need an array, so try it with the new-line character
1488 $codeE = explode(PHP_EOL, $code);
1491 $count_lines = count($codeE);
1493 $r = 'Line | Code:<br />';
1494 foreach ($codeE as $line => $c) {
1495 $r .= '<div class="line"><span class="linenum">';
1496 if ($count_lines == 1) {
1499 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1504 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1507 return '<div class="code">' . $r . '</div>';
1510 // Determines the right page title
1511 function determinePageTitle () {
1515 // Config and database connection valid?
1516 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1517 // Title decoration enabled?
1518 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1519 $pageTitle .= '{%config,trim=title_left%} ';
1522 // Is there an extra title?
1523 if (isExtraTitleSet()) {
1525 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1529 $pageTitle .= '{?MAIN_TITLE?}';
1531 // Add title of module? (middle decoration will also be added!)
1532 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1533 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1536 // Get menu mode from module
1537 $menuMode = getMenuModeFromModule();
1539 // Add middle part (always in admin area!)
1540 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1541 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1544 // Add title decorations? (right)
1545 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1546 $pageTitle .= ' {%config,trim=title_right%}';
1548 } elseif ((isInstalled()) && (isAdminRegistered())) {
1549 // Installed, admin registered but no ext-sql_patches
1550 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1551 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1552 // Installed but no admin registered
1553 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1554 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1555 // Installation mode
1556 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1558 // Configuration not found
1559 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1561 // Do not add the fatal message in installation mode
1562 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1563 // Please report this
1564 reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1569 return decodeEntities($pageTitle);
1572 // Checks whethere there is a cache file there. This function is cached.
1573 function isTemplateCached ($prefix, $template) {
1574 // Is there cached this result?
1575 if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1577 $FQFN = generateCacheFqfn($prefix, $template);
1580 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1584 return $GLOBALS['template_cache'][$prefix][$template];
1587 // Flushes non-flushed template cache to disk
1588 function flushTemplateCache ($prefix, $template, $eval) {
1589 // Is this cache flushed?
1590 if ((isDebugTemplateCacheEnabled() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1592 $FQFN = generateCacheFqfn($prefix, $template);
1594 // Compile code another round for better performance and preserve $ signs
1595 $eval = str_replace(array(chr(92), '{DOLLAR}', '{BACK}', '{CONTENT}'), array('', '$', chr(92), '$content'), compileCode(str_replace(array('$content', chr(92)), array('{CONTENT}', '{BACK}'), $eval)));
1597 // Is this a XML template?
1598 if ($prefix == 'xml') {
1599 // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1600 $eval = compactContent($eval);
1604 writeToFile($FQFN, '<?php ' . $eval . ' ?>', TRUE);
1608 // Reads a template cache
1609 function readTemplateCache ($prefix, $template, $content) {
1611 if ((isDebugTemplateCacheEnabled()) || (!isTemplateCached($prefix, $template))) {
1612 // This should not happen
1613 reportBug(__FUNCTION__, __LINE__, 'Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1617 if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1619 $FQFN = generateCacheFqfn($prefix, $template);
1624 * WARNING: Do not replace this include() call with loadInclude() as it
1625 * would hide local variables away which is here required to make this
1630 // Is the template cache valid?
1631 if (!isset($templateContent)) {
1632 // Please clear your cache!
1633 reportBug(__FUNCTION__, __LINE__, 'Template ' . $template . ' uses old structure. Please delete all template cache files and reload.');
1638 return $templateContent;
1641 // Escapes quotes (default is only double-quotes)
1642 function escapeQuotes ($str, $single = FALSE) {
1643 // Should we escape all?
1644 if ($single === TRUE) {
1645 // Escape all (including null)
1646 $str = addslashes($str);
1648 // Replace all chars at once
1649 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1652 // Return the escape'd string
1656 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1657 function escapeJavaScriptQuotes ($str) {
1658 // Replace all double-quotes and secure back-ticks
1659 $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1665 // Send out mails depending on the 'mod/modes' combination
1666 // @TODO Lame description for this function
1667 function sendModeMails ($mod, $modes) {
1669 $content = array ();
1672 if (fetchUserData(getMemberId())) {
1673 // Extract salt from cookie
1674 $salt = substr(getSession('u_hash'), 0, -40);
1676 // Now let's compare passwords
1677 $hash = encodeHashForCookie(getUserData('password'));
1679 // Does the hash match or should we change it?
1680 if (($hash == getSession('u_hash')) || (postRequestElement('password1') == postRequestElement('password2'))) {
1682 $content = getUserDataArray();
1684 // Clear/init the content variable
1685 $content['message'] = '';
1688 // @TODO Move this in a filter
1691 foreach ($modes as $mode) {
1693 case 'normal': break; // Do not add any special lines
1694 case 'email': // Email was changed!
1695 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . PHP_EOL;
1698 case 'password': // Password was changed
1699 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . PHP_EOL;
1703 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1704 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . PHP_EOL . PHP_EOL;
1709 if (isExtensionActive('country')) {
1710 // Replace code with description
1711 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1714 // Merge content with data from POST
1715 $content = merge_array($content, postRequestArray());
1718 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1720 if (isAdminNotificationEnabled()) {
1721 // The admin needs to be notified about a profile change
1722 $message_admin = 'admin_mydata_notify';
1723 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1726 $message_admin = '';
1730 // Set subject lines
1731 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1733 // Output success message
1734 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1737 default: // Unsupported module!
1738 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1739 $content['message'] = '<span class="bad">{--UNKNOWN_MODULE--}</span>';
1743 // Passwords mismatch
1744 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1747 // Could not load profile
1748 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1751 // Send email to user if required
1752 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1754 sendEmail($content['userid'], $sub_mem, $message);
1757 // Send only if no other error has occured
1758 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1760 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1761 } elseif (isAdminNotificationEnabled()) {
1762 // Cannot send mails to admin!
1763 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1766 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1770 displayMessage($content['message']);
1773 // Generates a 'selection box' from given array
1774 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1778 // Use default value as array key?
1779 if ($useDefaultAsArray === TRUE) {
1781 $addKey = '[' . convertNullToZero($default) . ']';
1785 $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1786 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1789 if ($allowNone === TRUE) {
1791 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1794 // Walk through all options
1795 foreach ($options as $option) {
1796 // Default 'default' is not set
1797 $option['default'] = '';
1799 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1800 // Is default value same as given value?
1801 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1803 $option['default'] = ' selected="selected"';
1806 // Is 'nameElement' set?
1807 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1808 // Then set this as extraName, but lower-case
1809 $extraName = '_' . strtolower($option[$nameElement]);
1812 // Add the <option> entry from ...
1813 if (empty($optionContent)) {
1814 // Is a template name given?
1815 if (empty($templateName)) {
1816 // ... $name template
1817 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1819 // ... $templateName template
1820 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1823 // ... direct HTML code
1824 $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1828 // Finish selection box
1829 $OUT .= '</select>';
1833 'selection_box' => $OUT,
1836 // Load template and return it
1837 if (empty($templateName)) {
1838 // Use name from $name + $extraName
1839 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1841 // Use name from $templateName + $extraName
1842 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1846 // Prepares the header for HTML output
1847 function loadHtmlHeader () {
1850 * 1.) pre_page_header (mainly loads the page_header template and includes
1853 runFilterChain('pre_page_header');
1856 * Here can be something be added, but normally one of the two filters
1857 * around this line should do the job for you.
1861 * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1862 * to close the head-tag)
1863 * Include more header data here
1865 runFilterChain('post_page_header');
1868 // Adds page header and footer to output array element
1869 function addPageHeaderFooter () {
1873 // Add them all together. This is maybe to simple
1874 foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1875 // Add page part if set
1876 if (isset($GLOBALS[$pagePart])) {
1877 $OUT .= $GLOBALS[$pagePart];
1881 // Transfer $OUT to '__output'
1882 $GLOBALS['__output'] = $OUT;
1885 // Generates meta description for current module and 'what' value
1886 function generateMetaDescriptionCode () {
1887 // Only include from guest area and if ext-sql_patches has correct version
1888 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1889 // Output it directly
1890 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1893 // Initialize referral system
1894 initReferralSystem();
1897 // Generates an FQFN for template cache from the given template name
1898 function generateCacheFqfn ($prefix, $template) {
1900 if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1901 // Generate the FQFN
1902 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1903 '%s_compiled/%s/%s.tpl.cache',
1911 return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1914 // "Fixes" null or empty string to count of dashes
1915 function fixNullEmptyToDashes ($str, $num) {
1916 // Use str as default
1920 if ((is_null($str)) || (trim($str) == '')) {
1922 $return = str_repeat('-', $num);
1925 // Return final string
1929 // Translates the "pool type" into human-readable
1930 function translatePoolType ($type) {
1931 // Return "translation"
1932 return sprintf('{--POOL_TYPE_%s--}', strtoupper($type));
1935 // "Translates" given time unit
1936 function translateTimeUnit ($unit) {
1937 // Default is unknown
1938 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1941 if (!isset($GLOBALS['time_units'][$unit])) {
1943 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1945 // Translate it with generic function
1946 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1953 // Displays given message in admin_settings_saved template
1954 function displayMessage ($message, $return = FALSE) {
1955 // Load the template
1956 return loadTemplate('admin_settings_saved', $return, $message);
1959 // Displays given error message in admin_settings_saved template
1960 function displayErrorMessage ($message, $return = FALSE) {
1961 // Load the template
1962 return loadTemplate('admin_settings_unsaved', $return, $message);
1965 // Generates a selection box for (maybe) given gender
1966 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
1967 // Start the HTML code
1968 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
1971 $out .= generateOptions(
1986 $out .= '</select>';
1992 // Generates a selection box for given default value
1993 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
1995 $messageIds = array();
1997 // Generate message id array
1998 foreach ($unitArray as $unit) {
2000 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2003 // Start the HTML code
2004 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2007 $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2010 $out .= '</select>';
2016 // Function to add style tag (whether display:none/block)
2017 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2018 // Is there foo_menu_javascript enabled?
2019 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2020 // Silently abort here, not enabled
2024 // Is action=mainAction?
2025 if ($action == $mainAction) {
2026 // Add "menu open" style
2027 return ' style="display:block"';
2029 return ' style="display:none"';
2033 // Function to add onclick attribute
2034 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2035 // Is there foo_menu_javascript enabled?
2036 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2037 // Silently abort here, not enabled
2042 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2048 //-----------------------------------------------------------------------------
2049 // Template helper functions for EL code
2050 //-----------------------------------------------------------------------------
2052 // Color-switch helper function
2053 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2055 if (!isset($GLOBALS['color_switch'][$templateName])) {
2057 initTemplateColorSwitch($templateName);
2058 } elseif ($clear === FALSE) {
2059 // Switch color if called from loadTemplate()
2060 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2061 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2064 // Return CSS class name
2065 if ($return === TRUE) {
2066 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2067 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2071 // Helper function for extension registration link
2072 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2073 // Default is all non-productive
2074 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2076 // Is the given extension non-productive?
2077 if (isExtensionDeprecated($ext_name)) {
2079 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2080 } elseif (isExtensionProductive($ext_name)) {
2082 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&register_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
2089 // Helper function to create bonus mail admin links
2090 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2091 // Call the inner function
2092 return generateAdminMailLinks('bonus', $bonusId);
2095 // Helper function to create member mail admin links
2096 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2097 // Call the inner function
2098 return generateAdminMailLinks('normal', $mailId);
2101 // Helper function to create a selection box for YES/NO configuration entries
2102 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2103 // Default is a "missing entry" warning
2104 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2106 // Generate the HTML code
2107 if (isConfigEntrySet($configEntry)) {
2108 // Configuration entry is found
2109 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2110 {%config,generateYesNoOptions=' . $configEntry . '%}
2118 // Helper function to create a selection box for YES/NO form fields
2119 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2120 // Generate the HTML code
2121 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2122 {%pipe,generateYesNoOptions%}
2129 // Helper function to create a selection box for YES/NO form fields, by NO is default
2130 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2131 // Generate the HTML code
2132 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2133 {%pipe,generateYesNoOptions=N%}
2140 // Helper function to add extra content for guest area (module=index and others)
2141 function doTemplateGuestFooterExtras ($templateName, $clear) {
2143 $filterData = array(
2144 // Name of used template
2145 'template' => $templateName,
2146 // Target array for gathered data
2147 '__data' => array(),
2148 // Where the HTML output will go
2152 // Run the filter chain
2153 $filterData = runFilterChain('guest_footer_extras', $filterData);
2156 return $filterData['__output'];
2159 // Helper function to add extra content for member area (module=login)
2160 function doTemplateMemberFooterExtras ($templateName, $clear) {
2161 // Is a member logged in?
2163 // This shall not happen
2164 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2168 $filterData = array(
2169 // Current user's id number
2170 'userid' => getMemberId(),
2171 // Name of used template
2172 'template' => $templateName,
2173 // Target array for gathered data
2174 '__data' => array(),
2175 // Where the HTML output will go
2179 // Run the filter chain
2180 $filterData = runFilterChain('member_footer_extras', $filterData);
2183 return $filterData['__output'];
2187 * Helper function to determine whether current userid is set, if none is set,
2188 * return a zero, else an EL code is being returned as of this function is used
2189 * only in templates.
2191 * @param $templateName Name of template (unused)
2192 * @param $clear Wether to clear something (unused)
2193 * @return $userId Wether zero or EL code snippet
2195 function doTemplateUserId ($templateName, $clear) {
2196 // By default no userid is set
2199 // Is there a user id currently set?
2200 if (isCurrentUserIdSet()) {
2201 // Then get the current user id
2202 $userId = getCurrentUserId();
2209 // Template helper function to generate "Terms&Conditions" link (EL code again)
2210 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2212 * Use default link by default ;-) This link, however, will become
2213 * deprecated once ext-terms is rolled out.
2215 $linkCode = '{%url=modules.php?module=index&what=agb%}';
2217 // Is ext-terms installed?
2218 if (isExtensionInstalled('terms')) {
2219 // Then use that link (only 'what' has changed)
2220 $linkCode = '{%url=modules.php?module=index&what=terms%}';
2223 // Return link (EL) code
2227 // Template helper function to create selection box for "locked points mode"
2228 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2230 $lockedModes = array(
2231 0 => array('mode' => 'LOCKED'),
2232 1 => array('mode' => 'UNLOCKED'),
2235 // Handle it over to generateSelectionBoxFromArray()
2236 $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2238 // Return prepared content
2242 // Template helper function to create selection box for payment method
2243 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2245 $paymentMethods = array(
2246 0 => array('method' => 'DIRECT'),
2247 1 => array('method' => 'REFERRAL'),
2250 // Handle it over to generateSelectionBoxFromArray()
2251 $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2253 // Return prepared content
2257 // Template helper function to create a deferrer code if URL is not empty
2258 function doTemplateDereferrerUrl ($templateName, $clear = FALSE, $url = NULL) {
2259 // Is the URL not NULL and not empty?
2260 if ((!is_null($url)) && (!empty($url))) {
2261 // Set HTML with EL code
2262 $url = '<a href="{%pipe,generateDereferrerUrl=' . $url . '%}" rel="external" target="_blank">{--ADMIN_TEST_URL--}</a>';
2265 // Return URL (or content) or dashes if empty
2266 return fixEmptyContentToDashes($url);
2269 // Load another template and return its content
2270 function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $content = array()) {
2271 // Load "the" template
2272 return loadTemplate($theTemplate, TRUE, $content);
2275 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2276 function anonymizeSensitiveData ($data) {
2278 $data = trim($data);
2282 // Then add three dashes
2284 } elseif (isUrlValid($data)) {
2285 // Is a referrer, so is it black-listed?
2287 // Is admin, has always priority
2288 $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2289 } elseif (isUrlBlacklisted($data)) {
2290 // Yes, so replace it with text
2291 $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2293 // A member is viewing this referral URL
2294 $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2296 } elseif (isIp4AddressValid($data)) {
2297 // Is an IPv4 address
2298 $ipArray = explode('.', $data);
2300 // Only display first 2 octets
2301 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2304 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2307 // Return it (hopefully) anonymized
2312 * Removes all comments, tabs and new-line characters to compact the content
2314 * @param $uncompactedContent The uncompacted content
2315 * @return $compactedContent The compacted content
2317 function compactContent ($uncompactedContent) {
2318 // First, remove all tab/new-line/revert characters
2319 $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
2321 // Make a space after >
2322 $compactedContent = str_replace(array('>', ' '), array('> ', ' '), $compactedContent);
2324 // Then regex all comments like <!-- //--> away
2325 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2327 // Do we have entries?
2328 if (isset($matches[0][0])) {
2330 foreach ($matches[0] as $match) {
2332 $compactedContent = str_replace($match, '', $compactedContent);
2336 // Return compacted content
2337 return $compactedContent;