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, $template = '', $compiled = FALSE, $full = TRUE, $overwrite = FALSE) {
45 return compileCode($code, FALSE, TRUE, $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, $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 (!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(chr(10));
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'] .= chr(10);
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(chr(10));
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 // Add page header and footer
184 addPageHeaderFooter();
185 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__output(length)=' . strlen($GLOBALS['__output']) . ' - After addPageHeaderFooter() call.');
187 // Do the final (general) compilation
188 $GLOBALS['__output'] = doFinalCompilation($GLOBALS['__output']);
190 // Is the output mode not HTML?
191 if (!isHtmlOutputMode()) {
192 // Then remove entities
193 $GLOBALS['__output'] = compileUriCode($GLOBALS['__output']);
196 // Extension 'rewrite' installed?
197 if ((isExtensionActive('rewrite')) && (!isCssOutputMode())) {
198 $GLOBALS['__output'] = rewriteLinksInCode($GLOBALS['__output']);
203 * @TODO On some pages this is buggy
204 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
205 // Compress it for HTTP gzip
206 $GLOBALS['__output'] = gzencode($GLOBALS['__output'], 9);
209 addHttpHeader('Content-Encoding: gzip');
210 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (isInStringIgnoreCase('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']))) {
211 // Compress it for HTTP deflate
212 $GLOBALS['__output'] = gzcompress($GLOBALS['__output'], 9);
215 addHttpHeader('Content-Encoding: deflate');
220 addHttpHeader('Content-Length: ' . strlen($GLOBALS['__output']));
226 // Main compilation loop
227 function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE) {
228 // Insert comments? (Only valid with HTML templates, of course)
229 enableTemplateHtml($insertComments);
235 while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($count < 7)) {
236 // Init common variables
241 //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
242 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), FALSE, TRUE, $enableCodes)) . '";';
243 //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
245 //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
246 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
248 // Was that eval okay?
249 if (empty($newContent)) {
250 // Something went wrong!
251 reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', FALSE);
257 // Compile the final code if insertComments is true
258 if ($insertComments == TRUE) {
259 // ... because SQL queries shall keep OPEN_CONFIG and such in
260 $code = compileRawCode($code);
267 // Add debugging data in HTML code, if mode is enabled
268 if ((isDebugModeEnabled()) && ($insertComments === TRUE) && ((isHtmlOutputMode()) || (isCssOutputMode()))) {
270 $code .= '<!-- Total compilation loop=' . $count . ' //-->';
273 // Return the compiled code
277 // Output the raw HTML code
278 function outputRawCode ($htmlCode) {
279 // Output stripped HTML code to avoid broken JavaScript code, etc.
280 print(str_replace('{BACK}', chr(92), $htmlCode));
282 // Flush the output if only getPhpCaching() is not 'on'
283 if (getPhpCaching() != 'on') {
289 // Load a template file and return it's content (only it's name; do not use ' or ")
290 function loadTemplate ($template, $return = FALSE, $content = array(), $compileCode = TRUE) {
291 // @TODO Remove these sanity checks if all is fine
292 if (!is_bool($return)) {
293 // $return has to be boolean
294 reportBug(__FUNCTION__, __LINE__, 'return[] is not bool (' . gettype($return) . ')');
295 } elseif (!is_string($template)) {
296 // $template has to be string
297 reportBug(__FUNCTION__, __LINE__, 'template[] is not string (' . gettype($template) . ')');
300 // Init returned content
303 // Set current template
304 $GLOBALS['current_template'] = $template;
307 if ((!isDebuggingTemplateCache()) && (isTemplateCached('html', $template))) {
308 // Evaluate the cache
309 eval(readTemplateCache('html', $template));
310 } elseif (!isset($GLOBALS['template_eval']['html'][$template])) {
311 // Make all template names lowercase
312 $template = strtolower($template);
315 $basePath = sprintf("%stemplates/%s/html/", getPath(), getLanguage());
316 $extraPath = detectExtraTemplatePath('html', $template);
319 $FQFN = $basePath . $extraPath . $template . '.tpl';
320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Template ' . $template . ' is solved to FQFN=' . $FQFN);
322 // Does the special template exists?
323 if (!isFileReadable($FQFN)) {
324 // Reset to default template
325 $FQFN = $basePath . $template . '.tpl';
328 // Now does the final template exists?
329 if (isFileReadable($FQFN)) {
330 // Count the template load
331 incrementConfigEntry('num_templates');
333 // The local file does exists so we load it. :)
334 $GLOBALS['template_content']['html'][$template] = readFromFile($FQFN);
336 // Is there to compile the code?
337 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]))) {
338 // Normal HTML output?
339 if ((isHtmlOutputMode()) && (substr($template, 0, 3) != 'js_')) {
340 // Add surrounding HTML comments to help finding bugs faster
341 $code = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
343 // Prepare eval() command
344 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
345 $GLOBALS['template_eval']['html'][$template] = '$ret = "' . getColorSwitchCode($template) . compileCode(escapeQuotes($code), FALSE, TRUE, TRUE, $compileCode) . '";';
346 } elseif (substr($template, 0, 3) == 'js_') {
347 // JavaScripts don't like entities, dollar signs and timings
348 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
349 $GLOBALS['template_eval']['html'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), FALSE, TRUE, TRUE, $compileCode) . '");';
351 // Prepare eval() command, other output doesn't like entities, maybe
352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
353 $GLOBALS['template_eval']['html'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['html'][$template]), FALSE, TRUE, TRUE, $compileCode) . '");';
355 } elseif (isHtmlOutputMode()) {
356 // Add surrounding HTML comments to help finding bugs faster
357 $ret = '<!-- Template ' . $template . ' - Start //-->' . $GLOBALS['template_content']['html'][$template] . '<!-- Template ' . $template . ' - End //-->';
358 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
359 $GLOBALS['template_eval']['html'][$template] = '$ret = "' . getColorSwitchCode($template) . compileRawCode(escapeQuotes($ret), FALSE, TRUE, TRUE, $compileCode) . '";';
362 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Reached!');
363 $GLOBALS['template_eval']['html'][$template] = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['template_content']['html'][$template]), FALSE, TRUE, TRUE, $compileCode) . '");';
365 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
366 // Only admins shall see this warning or when installation mode is active
367 $ret = '<div class="para">
374 {--TEMPLATE_CONTENT--}:
375 <pre>' . print_r($content, TRUE) . '</pre>
379 $GLOBALS['template_eval']['html'][$template] = '404';
384 if ((isset($GLOBALS['template_eval']['html'][$template])) && ($GLOBALS['template_eval']['html'][$template] != '404')) {
386 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
387 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['html'][$template]).'</pre>');
388 eval($GLOBALS['template_eval']['html'][$template]);
389 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
392 // Is there some content to output or return?
394 // Not empty so let's put it out! ;)
395 if ($return === TRUE) {
396 // Return the HTML code
402 } elseif (isDebugModeEnabled()) {
403 // Warning, empty output!
404 return 'E:' . $template . ',content=<pre>' . print_r($content, TRUE) . '</pre>';
408 // Detects the extra template path from given template name
409 function detectExtraTemplatePath ($prefix, $template) {
414 if (!isset($GLOBALS['extra_path'][$prefix][$template])) {
415 // Check for admin/guest/member/etc. templates
416 if (substr($template, 0, 6) == 'admin_') {
417 // Admin template found
418 $extraPath = 'admin/';
419 } elseif (substr($template, 0, 6) == 'guest_') {
420 // Guest template found
421 $extraPath = 'guest/';
422 } elseif (substr($template, 0, 7) == 'member_') {
423 // Member template found
424 $extraPath = 'member/';
425 } elseif (substr($template, 0, 7) == 'select_') {
426 // Selection template found
427 $extraPath = 'select/';
428 } elseif (substr($template, 0, 8) == 'install_') {
429 // Installation template found
430 $extraPath = 'install/';
431 } elseif (substr($template, 0, 4) == 'ext_') {
432 // Extension template found
434 } elseif (substr($template, 0, 3) == 'la_') {
435 // 'Logical-area' template found
437 } elseif (substr($template, 0, 3) == 'js_') {
438 // JavaScript template found
440 } elseif (substr($template, 0, 5) == 'menu_') {
441 // Menu template found
442 $extraPath = 'menu/';
444 // Test for extension
445 $test = substr($template, 0, strpos($template, '_'));
447 // Probe for valid extension name
448 if (isExtensionNameValid($test)) {
449 // Set extra path to extension's name
450 $extraPath = $test . '/';
455 $GLOBALS['extra_path'][$prefix][$template] = $extraPath;
459 return $GLOBALS['extra_path'][$prefix][$template];
462 // Loads an email template and compiles it
463 function loadEmailTemplate ($template, $content = array(), $userid = NULL, $loadUserData = TRUE) {
464 // Make sure all template names are lowercase!
465 $template = strtolower($template);
467 // Set current template
468 $GLOBALS['current_template'] = $template;
470 // Is content an array?
471 if (is_array($content)) {
472 // Add expiration to array
473 if ((isConfigEntrySet('auto_purge')) && (getAutoPurge() == '0')) {
474 // Will never expire!
475 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
476 } elseif (isConfigEntrySet('auto_purge')) {
477 // Create nice date string
478 $content['expiration'] = '{%config,createFancyTime=auto_purge%}';
481 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
486 if ((!isDebuggingTemplateCache()) && (isTemplateCached('email', $template))) {
487 // Evaluate the cache
488 eval(readTemplateCache('email', $template));
489 } elseif (!isset($GLOBALS['template_eval']['email'][$template])) {
491 $basePath = sprintf("%stemplates/%s/emails/", getPath(), getLanguage());
494 $extraPath = detectExtraTemplatePath('email', $template);
496 // Generate full FQFN
497 $FQFN = $basePath . $extraPath . $template . '.tpl';
499 // Does the special template exists?
500 if (!isFileReadable($FQFN)) {
501 // Reset to default template
502 $FQFN = $basePath . $template . '.tpl';
505 // Now does the final template exists?
507 if (isFileReadable($FQFN)) {
508 // The local file does exists so we load it. :)
509 $GLOBALS['template_content']['email'][$template] = readFromFile($FQFN);
512 $GLOBALS['template_eval']['email'][$template] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['template_content']['email'][$template])) . '");';
513 } elseif (!empty($template)) {
514 // Template file not found
515 $newContent = '<div class="para">
516 {--TEMPLATE_404--}: ' . $template . '
519 {--TEMPLATE_CONTENT--}:
520 <pre>' . print_r($content, TRUE) . '</pre>
523 // Don't cache this, as there is no template to cache
524 $GLOBALS['template_eval']['email'][$template] = '404';
526 // Debug mode not active? Then remove the HTML tags
527 if (!isDebugModeEnabled()) {
529 $newContent = secureString($newContent);
532 // No template name supplied!
533 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
534 $GLOBALS['template_eval']['email'][$template] = '404';
538 // Is there something to eval?
539 if ((isset($GLOBALS['template_eval']['email'][$template])) && ($GLOBALS['template_eval']['email'][$template] != '404')) {
541 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - BEFORE EVAL');
542 ///* DEBUG: */ print('<pre>'.htmlentities($GLOBALS['template_eval']['email'][$template]).'</pre>');
543 eval($GLOBALS['template_eval']['email'][$template]);
544 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'template=' . $template . ' - AFTER EVAL');
547 // Are there some content?
548 if (empty($newContent)) {
550 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['template_eval']['email'][$template];
552 // Add last error if the required function exists
553 if (function_exists('error_get_last')) {
554 // Add last error and some lines for better overview
555 $newContent .= "\n--------------------------------------\nDebug:\n" . print_r(error_get_last(), TRUE) . "--------------------------------------\nPlease don't alter these informations!\nThanx.";
559 // Remove content and data
566 // "Getter" for menu CSS classes, mainly used in templates
567 function getMenuCssClasses ($data) {
568 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data=' . $data);
571 if (!isset($GLOBALS[__FUNCTION__][$data])) {
572 // $data needs to be converted into an array
573 $content = explode('|', $data);
575 // Non-existent index 2 will happen in menu blocks
576 if (!isset($content[2])) {
580 // Re-construct the array: 0=visible,1=locked,2=prefix
581 $content['visible'] = $content[0];
582 $content['locked'] = $content[1];
584 // Call our "translator" function
585 $content = translateMenuVisibleLocked($content, $content[2]);
588 $GLOBALS[__FUNCTION__][$data] = ($content['visible_css'] . ' ' . $content['locked_css']);
592 return $GLOBALS[__FUNCTION__][$data];
595 // Generate XHTML code for the CAPTCHA
596 function generateCaptchaCode ($code, $type, $urlId, $userid) {
597 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $urlId . '&do=img&code=' . $code . '%}" />';
600 // Compiles the given HTML/mail code
601 function compileCode ($code, $simple = FALSE, $constants = TRUE, $full = TRUE, $compileCode = TRUE) {
602 // Is the code a string or should we not compile?
603 if ((!is_string($code)) || ($compileCode === FALSE)) {
604 // Silently return it
609 $startCompile = microtime(TRUE);
612 $code = compileRawCode($code, $simple, $constants, $full);
615 $compilationTime = $startCompile - microtime(TRUE);
617 // Add timing if enabled
618 if (isTemplateHtml()) {
619 // Add timing, this should be disabled in
620 $code .= '<!-- Compilation time: ' . ($compilationTime * 1000). 'ms //-->';
623 // Return compiled code
628 // @TODO $simple/$constants are deprecated
629 function compileRawCode ($code, $simple = FALSE, $constants = TRUE, $full = TRUE, $compileCode = TRUE) {
630 // Is the code a string or shall we not compile?
631 if ((!is_string($code)) || ($compileCode === FALSE)) {
632 // Silently return it
636 // Init replacement-array with smaller set of security characters
637 $secChars = $GLOBALS['url_chars'];
639 // Select full set of chars to replace when we e.g. want to compile URLs
640 if ($full === TRUE) {
641 $secChars = $GLOBALS['security_chars'];
644 // Compile more through a filter
645 $code = runFilterChain('compile_code', $code);
647 // First compile these chars
648 array_unshift($secChars['to'] , '{--' , '--}');
649 array_unshift($secChars['from'], '{%message,', '%}' );
651 // Compile QUOT and other non-HTML codes
652 $code = str_replace($secChars['to'], $secChars['from'], $code);
654 // Find $content[bla][blub] entries
655 preg_match_all('/\$content((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
656 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Second regex gave ' . count($matches[0]) . ' matches.');
658 // Are some matches found?
659 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
660 // Replace all matches
661 $matchesFound = array();
662 foreach ($matches[0] as $key => $match) {
663 // Fuzzy look has failed by default
666 // Fuzzy look on match if already found
667 foreach ($matchesFound as $found => $set) {
669 $test = substr($found, 0, strlen($match));
671 // Does this entry exist?
672 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'found=' . $found . ',match=' . $match . ',set=' . $set);
673 if ($test == $match) {
675 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'fuzzyFound!');
682 if ($fuzzyFound === TRUE) {
686 // Take all string elements
687 if ((is_string($matches[3][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[3][$key]]))) {
688 // Replace it in the code, replace dollar sign so it won't be detected by next regex (see there)
689 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',match=' . $match);
690 $newMatch = str_replace(array('[', ']', '$'), array("['", "']", '{COMPILE_DOLLAR}'), $match);
691 $code = str_replace($match, '".' . $newMatch . '."', $code);
692 $matchesFound[$key . '_' . $matches[3][$key]] = 1;
693 $matchesFound[$match] = TRUE;
694 } elseif (!isset($matchesFound[$match])) {
696 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
697 $code = str_replace($match, '".' . $match . '."', $code);
698 $matchesFound[$match] = 1;
700 // Everthing else should be a least logged
701 logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ',key=' . $key);
707 * Find $foobar, $foo_bar and $fooBar entries. This regex would also find
708 * $content[foo_bar] which would result in {DOLLAR}content[foo_bar] and
709 * therefore the variable's value won't be inserted. This is why
710 * {COMPILE_DOLLAR} is being used in above loop and at the end of this
711 * function being replace with the original dollar sign again.
713 preg_match_all('/\$([a-z_A-Z\[\]]){0,}/', $code, $matches);
715 // Are some matches found?
716 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
717 // Scan all matches for not $content
718 foreach ($matches[0] as $match) {
720 $match = trim($match);
723 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match);
725 // Is the first part not $content/$userid and not empty?
726 // @TODO $userid is deprecated and should be removed from loadEmailTemplate() and replaced with $content[userid] in all templates
727 if ((!empty($match)) && (substr($match, 0, 8) != '$content') && ($match != '$userid')) {
728 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'match=' . $match . ' - SECURED!');
729 // Then replace $ with {DOLLAR}
730 $matchSecured = str_replace('$', '{DOLLAR}', $match);
732 // And in $code as well
733 $code = str_replace($match, $matchSecured, $code);
738 // Replace {COMPILE_DOLLAR} back to dollar sign
739 $code = str_replace('{COMPILE_DOLLAR}', '$', $code);
746 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'form_select') {
750 // This is a yes/no selection only!
751 if ($id > 0) $prefix .= '[' . $id . ']';
752 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
754 // Begin with regular selection box here
755 if (!empty($prefix)) $prefix .= '_';
757 if ($id > 0) $type2 .= '[' . $id . ']';
758 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
763 for ($idx = 1; $idx < 32; $idx++) {
764 $OUT .= '<option value="' . $idx . '"';
765 if ($default == $idx) $OUT .= ' selected="selected"';
766 $OUT .= '>' . $idx . '</option>';
770 case 'month': // Month
771 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
772 $OUT .= '<option value="' . $idx . '"';
773 if ($default == $idx) $OUT .= ' selected="selected"';
774 $OUT .= '>' . $descr . '</option>';
782 // Use configured min age or fixed?
783 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
785 $startYear = $year - getConfig('min_age');
788 $startYear = $year - 16;
791 // Calculate earliest year (100 years old people can still enter Internet???)
792 $minYear = $year - 100;
794 // Check if the default value is larger than minimum and bigger than actual year
795 if (($default > $minYear) && ($default >= $year)) {
796 for ($idx = $year; $idx < ($year + 11); $idx++) {
797 $OUT .= '<option value="' . $idx . '"';
798 if ($default == $idx) $OUT .= ' selected="selected"';
799 $OUT .= '>' . $idx . '</option>';
801 } elseif ($default == -1) {
802 // Current year minus 1
803 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
804 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
807 // Get current year and subtract the configured minimum age
808 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
809 // Calculate earliest year depending on extension version
810 if (isExtensionInstalledAndNewer('other', '0.2.1')) {
811 // Use configured minimum age
812 $year = getYear() - getConfig('min_age');
814 // Use fixed 16 years age
815 $year = getYear() - 16;
818 // Construct year selection list
819 for ($idx = $minYear; $idx <= $year; $idx++) {
820 $OUT .= '<option value="' . $idx . '"';
821 if ($default == $idx) $OUT .= ' selected="selected"';
822 $OUT .= '>' . $idx . '</option>';
829 for ($idx = 0; $idx < 60; $idx+=5) {
830 if (strlen($idx) == 1) $idx = 0 . $idx;
831 $OUT .= '<option value="' . $idx . '"';
832 if ($default == $idx) $OUT .= ' selected="selected"';
833 $OUT .= '>' . $idx . '</option>';
838 for ($idx = 0; $idx < 24; $idx++) {
839 if (strlen($idx) == 1) $idx = 0 . $idx;
840 $OUT .= '<option value="' . $idx . '"';
841 if ($default == $idx) $OUT .= ' selected="selected"';
842 $OUT .= '>' . $idx . '</option>';
847 $OUT .= '<option value="Y"';
848 if ($default == 'Y') $OUT .= ' selected="selected"';
849 $OUT .= '>{--YES--}</option><option value="N"';
850 if ($default != 'Y') $OUT .= ' selected="selected"';
851 $OUT .= '>{--NO--}</option>';
858 // Insert the code in $img_code into jpeg or PNG image
859 function generateImageOrCode ($img_code, $headerSent = TRUE) {
860 // Is the code size oversized or shouldn't we display it?
861 if ((strlen($img_code) > 6) || (empty($img_code)) || (getCodeLength() == '0')) {
862 // Stop execution of function here because of over-sized code length
863 reportBug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code(length)=' . strlen($img_code) . ' code_length=' . getCodeLength());
864 } elseif ($headerSent === FALSE) {
865 // Return an HTML code here
866 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
870 $img = sprintf("%s/theme/%s/images/code_bg.%s",
877 if (isFileReadable($img)) {
879 switch (getImgType()) {
880 case 'jpg': // Okay, load image and hide all errors
881 $image = imagecreatefromjpeg($img);
884 case 'png': // Okay, load image and hide all errors
885 $image = imagecreatefrompng($img);
889 // Silently log the error
890 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image-type %s in theme %s not found.", getImgType(), getCurrentTheme()));
894 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
895 $text_color = imagecolorallocate($image, 0, 0, 0);
897 // Insert code into image
898 imagestring($image, 5, 14, 2, $img_code, $text_color);
901 setContentType('image/' . getImgType());
903 // Output image with matching image factory
904 switch (getImgType()) {
905 case 'jpg': imagejpeg($image); break;
906 case 'png': imagepng($image); break;
909 // Remove image from memory
910 imagedestroy($image);
913 // Create selection box or array of splitted timestamp
914 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $asArray = FALSE) {
915 // Do not continue if ONE_DAY is absend
916 if (!isConfigEntrySet('ONE_DAY')) {
918 reportBug(__FUNCTION__, __LINE__, 'Configuration entry ONE_DAY is absend. timestamp=' . $timestamp . ',prefix=' . $prefix . ',align=' . $align . ',asArray=' . intval($asArray));
921 // Calculate 2-seconds timestamp
922 $stamp = round($timestamp);
923 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
925 // Is there a leap year?
927 $TEST = getYear() / 4;
929 $M2 = getMonth(time() + $timestamp);
931 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
932 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) {
933 $SWITCH = getOneDay();
936 // First of all years...
937 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
938 //* DEBUG: */ debugOutput('Y=' . $Y);
940 $M = abs(floor($timestamp / 2628000 - $Y * 12));
941 //* DEBUG: */ debugOutput('M=' . $M);
943 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getOneDay()) / 7) - ($M / 12 * (365 + $SWITCH / getOneDay()) / 7)));
944 //* DEBUG: */ debugOutput('W=' . $W);
946 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getOneDay()) - ($M / 12 * (365 + $SWITCH / getOneDay())) - $W * 7));
947 //* DEBUG: */ debugOutput('D=' . $D);
949 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getOneDay()) * 24 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24) - $W * 7 * 24 - $D * 24));
950 //* DEBUG: */ debugOutput('h=' . $h);
952 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getOneDay()) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
953 //* DEBUG: */ debugOutput('m=' . $m);
954 // And at last seconds...
955 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getOneDay()) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getOneDay()) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
956 //* DEBUG: */ debugOutput('s=' . $s);
958 // Is seconds zero and time is < 60 seconds?
959 if (($s == '0') && ($timestamp < 60)) {
961 $s = round($timestamp);
965 // Now we convert them in seconds...
967 if ($asArray === TRUE) {
968 // Just put all data in an array for later use
980 $OUT = '<div align="' . $align . '">';
981 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
984 if (isInString('Y', $display) || (empty($display))) {
985 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_YEAR--}</strong></td>';
988 if (isInString('M', $display) || (empty($display))) {
989 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MONTH--}</strong></td>';
992 if (isInString('W', $display) || (empty($display))) {
993 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_WEEK--}</strong></td>';
996 if (isInString('D', $display) || (empty($display))) {
997 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_DAY--}</strong></td>';
1000 if (isInString('h', $display) || (empty($display))) {
1001 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_HOUR--}</strong></td>';
1004 if (isInString('m', $display) || (empty($display))) {
1005 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_MINUTE--}</strong></td>';
1008 if (isInString('s', $display) || (empty($display))) {
1009 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--TIME_UNIT_SECOND--}</strong></td>';
1015 if (isInString('Y', $display) || (empty($display))) {
1016 // Generate year selection
1017 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1018 for ($idx = 0; $idx <= 10; $idx++) {
1019 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1020 if ($idx == $Y) $OUT .= ' selected="selected"';
1021 $OUT .= '>' . $idx . '</option>';
1023 $OUT .= '</select></td>';
1025 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1028 if (isInString('M', $display) || (empty($display))) {
1029 // Generate month selection
1030 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1031 for ($idx = 0; $idx <= 11; $idx++) {
1032 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1033 if ($idx == $M) $OUT .= ' selected="selected"';
1034 $OUT .= '>' . $idx . '</option>';
1036 $OUT .= '</select></td>';
1038 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1041 if (isInString('W', $display) || (empty($display))) {
1042 // Generate week selection
1043 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1044 for ($idx = 0; $idx <= 4; $idx++) {
1045 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1046 if ($idx == $W) $OUT .= ' selected="selected"';
1047 $OUT .= '>' . $idx . '</option>';
1049 $OUT .= '</select></td>';
1051 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1054 if (isInString('D', $display) || (empty($display))) {
1055 // Generate day selection
1056 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1057 for ($idx = 0; $idx <= 31; $idx++) {
1058 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1059 if ($idx == $D) $OUT .= ' selected="selected"';
1060 $OUT .= '>' . $idx . '</option>';
1062 $OUT .= '</select></td>';
1064 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1067 if (isInString('h', $display) || (empty($display))) {
1068 // Generate hour selection
1069 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1070 for ($idx = 0; $idx <= 23; $idx++) {
1071 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1072 if ($idx == $h) $OUT .= ' selected="selected"';
1073 $OUT .= '>' . $idx . '</option>';
1075 $OUT .= '</select></td>';
1077 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1080 if (isInString('m', $display) || (empty($display))) {
1081 // Generate minute selection
1082 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1083 for ($idx = 0; $idx <= 59; $idx++) {
1084 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1085 if ($idx == $m) $OUT .= ' selected="selected"';
1086 $OUT .= '>' . $idx . '</option>';
1088 $OUT .= '</select></td>';
1090 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1093 if (isInString('s', $display) || (empty($display))) {
1094 // Generate second selection
1095 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1096 for ($idx = 0; $idx <= 59; $idx++) {
1097 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1098 if ($idx == $s) $OUT .= ' selected="selected"';
1099 $OUT .= '>' . $idx . '</option>';
1101 $OUT .= '</select></td>';
1103 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1110 // Return generated HTML code
1114 // Generate a list of administrative links to a given userid
1115 function generateMemberAdminActionLinks ($userid) {
1116 // Make sure userid is a number
1117 if ($userid != bigintval($userid)) {
1118 reportBug(__FUNCTION__, __LINE__, 'userid is not a number!');
1121 // Define all main targets
1122 $targetArray = runFilterChain('member_admin_actions', array('del_user', 'edit_user', 'lock_user', 'list_refs', 'list_links', 'add_points', 'sub_points'));
1125 $status = getFetchedUserData('userid', $userid, 'status');
1127 // Begin of navigation links
1130 foreach ($targetArray as $target) {
1131 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $target . '&userid=' . $userid . '%}" title="{--ADMIN_USER_ACTION_LINK_';
1132 //* DEBUG: */ debugOutput('*' . $target.'/' . $status.'*');
1133 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1134 // Locked accounts shall be unlocked
1135 $OUT .= 'UNLOCK_USER';
1136 } elseif ($target == 'del_user') {
1137 // @TODO Deprecate this thing
1138 $OUT .= 'DELETE_USER';
1140 // All other status is fine
1141 $OUT .= strtoupper($target);
1143 $OUT .= '_TITLE--}">{--ADMIN_USER_ACTION_LINK_';
1144 if (($target == 'lock_user') && ($status == 'LOCKED')) {
1145 // Locked accounts shall be unlocked
1146 $OUT .= 'UNLOCK_USER';
1147 } elseif ($target == 'del_user') {
1148 // @TODO Deprecate this thing
1149 $OUT .= 'DELETE_USER';
1151 // All other status is fine
1152 $OUT .= strtoupper($target);
1154 $OUT .= '--}</a></span>|';
1157 // Add special link, in case of the account is unconfirmed
1158 if ($status == 'UNCONFIRMED') {
1160 $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>|';
1163 // Finish navigation link
1164 $OUT = substr($OUT, 0, -1) . ']';
1170 // Generate an email link
1171 function generateEmailLink ($email, $table = 'admins') {
1172 // Default email link (INSECURE! Spammer can read this by harvester programs)
1173 $EMAIL = 'mailto:' . $email;
1175 // Check for several extensions
1176 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1177 // Create email link for contacting admin in guest area
1178 $EMAIL = generateAdminEmailLink($email);
1179 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
1180 // Create email link for contacting a member within admin area (or later in other areas, too?)
1181 $EMAIL = generateUserEmailLink($email);
1182 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1183 // Create email link to contact sponsor within admin area (or like the link above?)
1184 $EMAIL = generateSponsorEmailLink($email);
1187 // Return email link
1192 * Outputs an error message in a "fashioned way" to the user, by putting it into
1193 * a nice looking web page, if one of HTML or CSS output mode is active.
1195 * Please use reportBug() instead of this function. reportBug() has more helpful
1196 * functionality like logging and admin notification (which you can configure
1197 * through your admin area).
1199 * @param $F Function or file basename where the error came from
1200 * @param $L Line number where the error came from
1201 * @param $message Message which shall be output to web
1204 function app_exit ($F, $L, $message) {
1205 // Check if Script is already dieing and not let it kill itself another 1000 times
1206 if (isset($GLOBALS['app_died'])) {
1207 // Script tried to kill itself twice
1208 die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
1211 // Make sure, that the script realy realy diese here and now
1212 $GLOBALS['app_died'] = TRUE;
1214 // Set content type as text/html
1215 setContentType('text/html');
1218 loadIncludeOnce('inc/header.php');
1220 // Rewrite message for output
1222 getMessage('MAILER_HAS_DIED'),
1228 // Load the message template
1229 loadTemplate('app_exit_message', FALSE, $message);
1232 loadIncludeOnce('inc/footer.php');
1235 // Display parsing time and number of SQL queries in footer
1236 function displayParsingTime () {
1237 // Is the timer started?
1238 if (!isset($GLOBALS['__start_time'])) {
1244 $endTime = microtime(TRUE);
1246 // "Explode" both times
1247 $start = explode(' ', $GLOBALS['__start_time']);
1248 $end = explode(' ', $endTime);
1249 $runTime = $end[0] - $start[0];
1255 // @TODO This can be easily moved out after the merge from EL branch to this is complete
1257 'run_time' => $runTime,
1258 'sql_time' => (getConfig('sql_time') * 1000),
1261 // Load the template
1262 $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
1266 * Outputs an error message and backtrace to the user, by default a mail with
1267 * all relevant data is being mailed to the configured administrators.
1269 * This function shall be used "publicly" because of logging, admin notification
1270 * and double-call prevention (see first if() block) instead of app_exit().
1271 * app_exit() is more a "private" function and will only output a bug message to
1272 * the user, no email and no logging.
1274 * @param $F Function or file basename where the error came from
1275 * @param $L Line number where the error came from
1276 * @param $sendEmail Wether to send an email to all configured administrators
1279 function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
1280 // Is this already called?
1281 if (isset($GLOBALS[__FUNCTION__])) {
1283 print '[' . $F . ':' . $L . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
1284 debug_print_backtrace();
1288 // Set HTTP status to 500 (e.g. for AJAX requests)
1289 setHttpStatus('500 Internal Server Error');
1291 // Mark this function as called
1292 $GLOBALS[__FUNCTION__] = TRUE;
1297 // Is the optional message set?
1298 if (!empty($message)) {
1300 $debug = sprintf("Note: %s<br />\n",
1304 // @TODO Add a little more infos here
1305 logDebugMessage($F, $L, strip_tags($message));
1309 $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>';
1310 $debug .= debug_get_printable_backtrace();
1312 $debug .= '<div class="para">Request-URI: ' . getRequestUri() . '</div>';
1313 $debug .= '<div class="para">Thank you for finding bugs.</div>';
1315 // Send an email? (e.g. not wanted for evaluation errors)
1316 if (($sendEmail === TRUE) && (!isInstallationPhase())) {
1319 'message' => trim($message),
1320 'backtrace' => trim(debug_get_mailable_backtrace())
1323 // Send email to webmaster
1324 sendAdminNotification('{--REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
1327 // Is there HTML/CSS/AJAX mode?
1328 if ((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode())) {
1330 app_exit($F, $L, $debug);
1332 // Raw/image output mode and all other modes doesn't work well with text ...
1337 // Compile characters which are allowed in URLs
1338 function compileUriCode ($code, $simple = TRUE) {
1340 $test = trim($code);
1344 // Then abort here and return the original code
1348 // Compile these by default
1349 $charsCompile = array(
1374 // Compile constants
1375 if ($simple === FALSE) {
1377 array_unshift($charsCompile['from'], '{--', '--}');
1380 array_unshift($charsCompile['to'], '".', '."');
1383 // Compile QUOT and other non-HTML codes
1384 $code = str_replace($charsCompile['from'], $charsCompile['to'], decodeEntities($code));
1385 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'code=' . $code);
1387 // Return compiled code
1391 // Handle message codes from URL
1392 function handleCodeMessage () {
1394 if (isGetRequestElementSet('code')) {
1395 // Default extension is 'unknown'
1398 // Is extension given?
1399 if (isGetRequestElementSet('ext')) {
1400 $ext = getRequestElement('ext');
1403 // Convert the 'code' parameter from URL to a human-readable message
1404 $message = getMessageFromErrorCode(getRequestElement('code'));
1406 // Load message template
1407 loadTemplate('message', FALSE, $message);
1411 // Generates a 'extension foo out-dated' message
1412 function generateExtensionOutdatedMessage ($ext_name, $ext_ver) {
1413 // Is the extension empty?
1414 if (empty($ext_name)) {
1415 // This should not happen
1416 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1420 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_OUTDATED=' . $ext_name . '%}';
1422 // Is an admin logged in?
1424 // Then output admin message
1425 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE'), $ext_name, $ext_name, $ext_ver);
1428 // Return prepared message
1432 // Generates a 'extension foo inactive' message
1433 function generateExtensionInactiveMessage ($ext_name) {
1434 // Is the extension empty?
1435 if (empty($ext_name)) {
1436 // This should not happen
1437 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1441 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1443 // Is an admin logged in?
1445 // Then output admin message
1446 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_INACTIVE=' . $ext_name . '%}';
1449 // Return prepared message
1453 // Generates a 'extension foo not installed' message
1454 function generateExtensionNotInstalledMessage ($ext_name) {
1455 // Is the extension empty?
1456 if (empty($ext_name)) {
1457 // This should not happen
1458 reportBug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
1462 $message = '{%message,EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1464 // Is an admin logged in?
1466 // Then output admin message
1467 $message = '{%message,ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED=' . $ext_name . '%}';
1470 // Return prepared message
1474 // Generates a message depending on if the extension is not installed or not
1476 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
1480 // Is the extension not installed or just deactivated?
1481 switch (isExtensionInstalled($ext_name)) {
1482 case true; // Deactivated!
1483 $message = generateExtensionInactiveMessage($ext_name);
1486 case false; // Not installed!
1487 $message = generateExtensionNotInstalledMessage($ext_name);
1490 default: // Should not happen!
1491 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
1492 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
1496 // Return the message
1500 // Print code with line numbers
1501 function linenumberCode ($code) {
1502 // By default copy the code
1505 if (!is_array($code)) {
1506 // We need an array, so try it with the new-line character
1507 $codeE = explode(chr(10), $code);
1510 $count_lines = count($codeE);
1512 $r = 'Line | Code:<br />';
1513 foreach ($codeE as $line => $c) {
1514 $r .= '<div class="line"><span class="linenum">';
1515 if ($count_lines == 1) {
1518 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
1523 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
1526 return '<div class="code">' . $r . '</div>';
1529 // Determines the right page title
1530 function determinePageTitle () {
1534 // Config and database connection valid?
1535 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1536 // Title decoration enabled?
1537 if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
1538 $pageTitle .= '{%config,trim=title_left%} ';
1541 // Is there an extra title?
1542 if (isExtraTitleSet()) {
1544 $pageTitle .= '{%pipe,getExtraTitle%} by ';
1548 $pageTitle .= '{?MAIN_TITLE?}';
1550 // Add title of module? (middle decoration will also be added!)
1551 if ((isModuleTitleEnabled()) || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
1552 $pageTitle .= ' {%config,trim=title_middle%} {DQUOTE} . getModuleTitle(getModule()) . {DQUOTE}';
1555 // Add title from what file
1557 if (getModule() == 'login') {
1558 $menuMode = 'member';
1559 } elseif (getModule() == 'index') {
1560 $menuMode = 'guest';
1561 } elseif (getModule() == 'admin') {
1562 $menuMode = 'admin';
1563 } elseif (getModule() == 'sponsor') {
1564 $menuMode = 'sponsor';
1567 // Add middle part (always in admin area!)
1568 if ((!empty($menuMode)) && ((isWhatTitleEnabled()) || ($menuMode == 'admin'))) {
1569 $pageTitle .= ' {%config,trim=title_middle%} ' . getTitleFromMenu($menuMode, getWhat());
1572 // Add title decorations? (right)
1573 if ((isTitleDecorationEnabled()) && (getTitleRight() != '')) {
1574 $pageTitle .= ' {%config,trim=title_right%}';
1576 } elseif ((isInstalled()) && (isAdminRegistered())) {
1577 // Installed, admin registered but no ext-sql_patches
1578 $pageTitle = '[-- {?MAIN_TITLE?} - {%pipe,getModule,getModuleTitle%} --]';
1579 } elseif ((isInstalled()) && (!isAdminRegistered())) {
1580 // Installed but no admin registered
1581 $pageTitle = '{--INSTALLER_OF_MAILER_NO_ADMIN--}';
1582 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
1583 // Installation mode
1584 $pageTitle = '{--INSTALLER_OF_MAILER--}';
1586 // Configuration not found
1587 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
1589 // Do not add the fatal message in installation mode
1590 if ((!isInstalling()) && (!isConfigurationLoaded())) {
1591 // Please report this
1592 reportBug(__FUNCTION__, __LINE__, 'No configuration data found!');
1597 return decodeEntities($pageTitle);
1600 // Checks whethere there is a cache file there. This function is cached.
1601 function isTemplateCached ($prefix, $template) {
1602 // Is there cached this result?
1603 if (!isset($GLOBALS['template_cache'][$prefix][$template])) {
1605 $FQFN = generateCacheFqfn($prefix, $template);
1608 $GLOBALS['template_cache'][$prefix][$template] = isFileReadable($FQFN);
1612 return $GLOBALS['template_cache'][$prefix][$template];
1615 // Flushes non-flushed template cache to disk
1616 function flushTemplateCache ($prefix, $template, $eval) {
1617 // Is this cache flushed?
1618 if ((isDebuggingTemplateCache() === FALSE) && (isTemplateCached($prefix, $template) === FALSE) && ($eval != '404')) {
1620 $FQFN = generateCacheFqfn($prefix, $template);
1622 // Is this a XML template?
1623 if ($prefix == 'xml') {
1624 // Compact only XML templates as emails needs new-line characters and HTML may contain required "comments"
1625 $eval = compactContent($eval);
1629 writeToFile($FQFN, $eval, TRUE);
1633 // Reads a template cache
1634 function readTemplateCache ($prefix, $template) {
1636 if ((isDebuggingTemplateCache()) || (!isTemplateCached($prefix, $template))) {
1637 // This should not happen
1638 reportBug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
1642 if (!isset($GLOBALS['template_eval'][$prefix][$template])) {
1644 $FQFN = generateCacheFqfn($prefix, $template);
1647 $GLOBALS['template_eval'][$prefix][$template] = readFromFile($FQFN);
1651 return $GLOBALS['template_eval'][$prefix][$template];
1654 // Escapes quotes (default is only double-quotes)
1655 function escapeQuotes ($str, $single = FALSE) {
1656 // Should we escape all?
1657 if ($single === TRUE) {
1658 // Escape all (including null)
1659 $str = addslashes($str);
1661 // Replace all chars at once
1662 $str = str_replace(array("\\'", '"', "\\\\"), array(chr(39), "\\\"", chr(92)), $str);
1665 // Return the escape'd string
1669 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
1670 function escapeJavaScriptQuotes ($str) {
1671 // Replace all double-quotes and secure back-ticks
1672 $str = str_replace(array(chr(92), '"'), array('{BACK}', '\"'), $str);
1678 // Send out mails depending on the 'mod/modes' combination
1679 // @TODO Lame description for this function
1680 function sendModeMails ($mod, $modes) {
1682 $content = array ();
1685 if (fetchUserData(getMemberId())) {
1686 // Extract salt from cookie
1687 $salt = substr(getSession('u_hash'), 0, -40);
1689 // Now let's compare passwords
1690 $hash = encodeHashForCookie(getUserData('password'));
1692 // Does the hash match or should we change it?
1693 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
1695 $content = getUserDataArray();
1697 // Clear/init the content variable
1698 $content['message'] = '';
1701 // @TODO Move this in a filter
1704 foreach ($modes as $mode) {
1706 case 'normal': break; // Do not add any special lines
1707 case 'email': // Email was changed!
1708 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestElement('old_email') . chr(10);
1711 case 'password': // Password was changed
1712 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . chr(10);
1716 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
1717 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
1722 if (isExtensionActive('country')) {
1723 // Replace code with description
1724 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
1727 // Merge content with data from POST
1728 $content = merge_array($content, postRequestArray());
1731 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
1733 if (isAdminNotificationEnabled()) {
1734 // The admin needs to be notified about a profile change
1735 $message_admin = 'admin_mydata_notify';
1736 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
1739 $message_admin = '';
1743 // Set subject lines
1744 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
1746 // Output success message
1747 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1750 default: // Unsupported module!
1751 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
1752 $content['message'] = '<span class="bad">{--UNKNOWN_MODULE--}</span>';
1756 // Passwords mismatch
1757 $content['message'] = '<span class="bad">{--MEMBER_PASSWORD_ERROR--}</span>';
1760 // Could not load profile
1761 $content['message'] = '<span class="bad">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
1764 // Send email to user if required
1765 if ((!empty($sub_mem)) && (!empty($message)) && (!empty($content['userid']))) {
1767 sendEmail($content['userid'], $sub_mem, $message);
1770 // Send only if no other error has occured
1771 if ((!empty($sub_adm)) && (!empty($message_admin)) && (isAdminNotificationEnabled())) {
1773 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
1774 } elseif (isAdminNotificationEnabled()) {
1775 // Cannot send mails to admin!
1776 $content['message'] = '{--CANNOT_SEND_ADMIN_MAILS--}';
1779 $content['message'] = '<span class="message">{--MEMBER_MYDATA_MAIL_SENT--}</span>';
1783 displayMessage($content['message']);
1786 // Generates a 'selection box' from given array
1787 function generateSelectionBoxFromArray ($options, $name, $optionKey, $optionContent = '', $extraName = '', $templateName = '', $default = NULL, $nameElement = '', $allowNone = FALSE, $useDefaultAsArray = FALSE) {
1791 // Use default value as array key?
1792 if ($useDefaultAsArray === TRUE) {
1794 $addKey = '[' . convertNullToZero($default) . ']';
1798 $OUT = '<select name="' . $name . $addKey . '" size="1" class="form_select">
1799 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
1802 if ($allowNone === TRUE) {
1804 $OUT .= '<option value="0">{--SELECT_NONE--}</option>';
1807 // Walk through all options
1808 foreach ($options as $option) {
1809 // Default 'default' is not set
1810 $option['default'] = '';
1812 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'name=' . $name . ',default[' . gettype($default) . ']=' . $default . ',optionKey[' . gettype($optionKey) . ']=' . $optionKey);
1813 // Is default value same as given value?
1814 if ((!is_null($default)) && (isset($option[$optionKey])) && ($default == $option[$optionKey])) {
1816 $option['default'] = ' selected="selected"';
1819 // Is 'nameElement' set?
1820 if ((!empty($nameElement)) && (isset($option[$nameElement]))) {
1821 // Then set this as extraName, but lower-case
1822 $extraName = '_' . strtolower($option[$nameElement]);
1825 // Add the <option> entry from ...
1826 if (empty($optionContent)) {
1827 // Is a template name given?
1828 if (empty($templateName)) {
1829 // ... $name template
1830 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', TRUE, $option);
1832 // ... $templateName template
1833 $OUT .= loadTemplate('select_' . $templateName . $extraName . '_option', TRUE, $option);
1836 // ... direct HTML code
1837 $OUT .= '<option value="' . $option[$optionKey] . '">' . $option[$optionContent] . '</option>';
1841 // Finish selection box
1842 $OUT .= '</select>';
1846 'selection_box' => $OUT,
1849 // Load template and return it
1850 if (empty($templateName)) {
1851 // Use name from $name + $extraName
1852 return loadTemplate('select_' . $name . $extraName . '_box', TRUE, $content);
1854 // Use name from $templateName + $extraName
1855 return loadTemplate('select_' . $templateName . $extraName . '_box', TRUE, $content);
1859 // Prepares the header for HTML output
1860 function loadHtmlHeader () {
1863 * 1.) pre_page_header (mainly loads the page_header template and includes
1866 runFilterChain('pre_page_header');
1869 * Here can be something be added, but normally one of the two filters
1870 * around this line should do the job for you.
1874 * 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
1875 * to close the head-tag)
1876 * Include more header data here
1878 runFilterChain('post_page_header');
1881 // Adds page header and footer to output array element
1882 function addPageHeaderFooter () {
1886 // Add them all together. This is maybe to simple
1887 foreach (array('__page_header', '__output', '__page_footer') as $pagePart) {
1888 // Add page part if set
1889 if (isset($GLOBALS[$pagePart])) {
1890 $OUT .= $GLOBALS[$pagePart];
1894 // Transfer $OUT to '__output'
1895 $GLOBALS['__output'] = $OUT;
1898 // Generates meta description for current module and 'what' value
1899 function generateMetaDescriptionCode () {
1900 // Only include from guest area and if ext-sql_patches has correct version
1901 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
1902 // Output it directly
1903 $GLOBALS['__page_header'] .= '<meta name="description" content="' . '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat()) . '" />';
1906 // Initialize referral system
1907 initReferralSystem();
1910 // Generates an FQFN for template cache from the given template name
1911 function generateCacheFqfn ($prefix, $template) {
1913 if (!isset($GLOBALS['template_cache_fqfn'][$prefix][$template])) {
1914 // Generate the FQFN
1915 $GLOBALS['template_cache_fqfn'][$prefix][$template] = sprintf(
1916 "%s_compiled/%s/%s.tpl.cache",
1924 return $GLOBALS['template_cache_fqfn'][$prefix][$template];
1927 // "Fixes" null or empty string to count of dashes
1928 function fixNullEmptyToDashes ($str, $num) {
1929 // Use str as default
1933 if ((is_null($str)) || (trim($str) == '')) {
1935 $return = str_repeat('-', $num);
1938 // Return final string
1942 // Translates the "pool type" into human-readable
1943 function translatePoolType ($type) {
1944 // Return "translation"
1945 return sprintf("{--POOL_TYPE_%s--}", strtoupper($type));
1948 // "Translates" given time unit
1949 function translateTimeUnit ($unit) {
1950 // Default is unknown
1951 $message = '{%message,TIME_UNIT_UNKNOWN=' . $unit . '%}';
1954 if (!isset($GLOBALS['time_units'][$unit])) {
1956 logDebugMessage(__FUNCTION__, __LINE__, 'Unknown time unit ' . $unit . ' detected.');
1958 // Translate it with generic function
1959 $message = translateGeneric('TIME_UNIT' , $GLOBALS['time_units'][$unit]);
1966 // Displays given message in admin_settings_saved template
1967 function displayMessage ($message, $return = FALSE) {
1968 // Load the template
1969 return loadTemplate('admin_settings_saved', $return, $message);
1972 // Generates a selection box for (maybe) given gender
1973 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
1974 // Start the HTML code
1975 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
1978 $out .= generateOptions(
1993 $out .= '</select>';
1999 // Generates a selection box for given default value
2000 function generateTimeUnitSelectionBox ($defaultUnit, $fieldName, $unitArray) {
2002 $messageIds = array();
2004 // Generate message id array
2005 foreach ($unitArray as $unit) {
2007 array_push($messageIds, '{%pipe,translateTimeUnit=' . $unit . '%}');
2010 // Start the HTML code
2011 $out = '<select name="' . $fieldName . '" size="1" class="form_select">';
2014 $out .= generateOptions('/ARRAY/', $unitArray, $messageIds, $defaultUnit);
2017 $out .= '</select>';
2023 // Function to add style tag (whether display:none/block)
2024 function addStyleMenuContent ($menuMode, $mainAction, $action) {
2025 // Is there foo_menu_javascript enabled?
2026 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2027 // Silently abort here, not enabled
2031 // Is action=mainAction?
2032 if ($action == $mainAction) {
2033 // Add "menu open" style
2034 return ' style="display:block"';
2036 return ' style="display:none"';
2040 // Function to add onclick attribute
2041 function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
2042 // Is there foo_menu_javascript enabled?
2043 if ((!isConfigEntrySet($menuMode . '_menu_javascript')) || (getConfig($menuMode . '_menu_javascript') == 'N')) {
2044 // Silently abort here, not enabled
2049 $OUT = ' onclick="return changeMenuFoldState(' . $menuMode . ', ' . $mainAction . ', ' . $action . ', ' . $what . ')';
2055 //-----------------------------------------------------------------------------
2056 // Template helper functions for EL code
2057 //-----------------------------------------------------------------------------
2059 // Color-switch helper function
2060 function doTemplateColorSwitch ($templateName, $clear = FALSE, $return = TRUE) {
2062 if (!isset($GLOBALS['color_switch'][$templateName])) {
2064 initTemplateColorSwitch($templateName);
2065 } elseif ($clear === FALSE) {
2066 // Switch color if called from loadTemplate()
2067 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SWITCH:' . $templateName);
2068 $GLOBALS['color_switch'][$templateName] = 3 - $GLOBALS['color_switch'][$templateName];
2071 // Return CSS class name
2072 if ($return === TRUE) {
2073 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'RETURN:' . $templateName . '=' . $GLOBALS['color_switch'][$templateName]);
2074 return 'switch_sw' . $GLOBALS['color_switch'][$templateName];
2078 // Helper function for extension registration link
2079 function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name) {
2080 // Default is all non-productive
2081 $OUT = '<div style="cursor:help" title="{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK_TITLE=' . $ext_name . '%}">{--ADMIN_EXTENSION_IS_NON_PRODUCTIVE_LINK--}</div>';
2083 // Is the given extension non-productive?
2084 if (isExtensionDeprecated($ext_name)) {
2086 $OUT = '<span title="{--ADMIN_EXTENSION_IS_DEPRECATED_TITLE--}">---</span>';
2087 } elseif (isExtensionProductive($ext_name)) {
2089 $OUT = '<a title="{--ADMIN_REGISTER_EXTENSION_TITLE--}" href="{%url=modules.php?module=admin&what=extensions&register_ext=' . $ext_name . '%}">{--ADMIN_REGISTER_EXTENSION--}</a>';
2096 // Helper function to create bonus mail admin links
2097 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
2098 // Call the inner function
2099 return generateAdminMailLinks('bid', $bonusId);
2102 // Helper function to create member mail admin links
2103 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
2104 // Call the inner function
2105 return generateAdminMailLinks('mid', $mailId);
2108 // Helper function to create a selection box for YES/NO configuration entries
2109 function doTemplateConfigurationYesNoSelectionBox ($templateName, $clear, $configEntry) {
2110 // Default is a "missing entry" warning
2111 $OUT = '<div class="bad" style="cursor:help" title="{%message,ADMIN_CONFIG_ENTRY_MISSING=' . $configEntry . '%}">!' . $configEntry . '!</div>';
2113 // Generate the HTML code
2114 if (isConfigEntrySet($configEntry)) {
2115 // Configuration entry is found
2116 $OUT = '<select name="' . $configEntry . '" class="form_select" size="1">
2117 {%config,generateYesNoOptions=' . $configEntry . '%}
2125 // Helper function to create a selection box for YES/NO form fields
2126 function doTemplateYesNoSelectionBox ($templateName, $clear, $formField) {
2127 // Generate the HTML code
2128 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2129 {%pipe,generateYesNoOptions%}
2136 // Helper function to create a selection box for YES/NO form fields, by NO is default
2137 function doTemplateNoYesSelectionBox ($templateName, $clear, $formField) {
2138 // Generate the HTML code
2139 $OUT = '<select name="' . $formField . '" class="form_select" size="1">
2140 {%pipe,generateYesNoOptions=N%}
2147 // Helper function to add extra content for member area (module=login)
2148 function doTemplateMemberFooterExtras ($templateName, $clear) {
2149 // Is a member logged in?
2151 // This shall not happen
2152 reportBug(__FUNCTION__, __LINE__, 'Please use this template helper only for logged-in members.');
2156 $filterData = array(
2157 // Current user's id number
2158 'userid' => getMemberId(),
2159 // Name of used template
2160 'template' => $templateName,
2161 // Target array for gathered data
2162 '__data' => array(),
2163 // Where the HTML output will go
2167 // Run the filter chain
2168 $filterData = runFilterChain('member_footer_extras', $filterData);
2171 return $filterData['__output'];
2175 * Helper function to determine whether current userid is set, if none is set,
2176 * return a zero, else an EL code is being returned as of this function is used
2177 * only in templates.
2179 * @param $templateName Name of template (unused)
2180 * @param $clear Wether to clear something (unused)
2181 * @return $userId Wether zero or EL code snippet
2183 function doTemplateUserId ($templateName, $clear) {
2184 // By default no userid is set
2187 // Is there a user id currently set?
2188 if (isCurrentUserIdSet()) {
2189 // Then get the current user id
2190 $userId = getCurrentUserId();
2197 // Template helper function to generate "Terms&Conditions" link (EL code again)
2198 function doTemplateGetTermsConditionsLink ($templateName, $clear) {
2200 * Use default link by default ;-) This link, however, will become
2201 * deprecated once ext-terms is rolled out.
2203 $linkCode = '{%url=modules.php?module=index&what=agb%}';
2205 // Is ext-terms installed?
2206 if (isExtensionInstalled('terms')) {
2207 // Then use that link (only 'what' has changed)
2208 $linkCode = '{%url=modules.php?module=index&what=terms%}';
2211 // Return link (EL) code
2215 // Template helper function to create selection box for "locked points mode"
2216 function doTemplatePointsLockedModeSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2218 $lockedModes = array(
2219 0 => array('mode' => 'LOCKED'),
2220 1 => array('mode' => 'UNLOCKED'),
2223 // Handle it over to generateSelectionBoxFromArray()
2224 $content = generateSelectionBoxFromArray($lockedModes, 'points_locked_mode', 'mode', '', '', '', $default);
2226 // Return prepared content
2230 // Template helper function to create selection box for payment method
2231 function doTemplatePointsPaymentMethodSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2233 $paymentMethods = array(
2234 0 => array('method' => 'DIRECT'),
2235 1 => array('method' => 'REFERRAL'),
2238 // Handle it over to generateSelectionBoxFromArray()
2239 $content = generateSelectionBoxFromArray($paymentMethods, 'points_payment_method', 'method', '', '', '', $default);
2241 // Return prepared content
2245 // Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
2246 function anonymizeSensitiveData ($data) {
2248 $data = trim($data);
2252 // Then add three dashes
2254 } elseif (isUrlValid($data)) {
2255 // Is a referrer, so is it black-listed?
2257 // Is admin, has always priority
2258 $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
2259 } elseif (isUrlBlacklisted($data)) {
2260 // Yes, so replace it with text
2261 $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
2263 // A member is viewing this referral URL
2264 $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
2266 } elseif (isIp4AddressValid($data)) {
2267 // Is an IPv4 address
2268 $ipArray = explode('.', $data);
2270 // Only display first 2 octets
2271 $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
2274 $data = '<em>{--DATA_IS_HIDDEN--}</em>';
2277 // Return it (hopefully) anonymized
2282 * Removes all commentd, tabs and new-line characters to compact the content
2284 * @param $uncompactedContent The uncompacted content
2285 * @return $compactedContent The compacted content
2287 function compactContent ($uncompactedContent) {
2288 // First, remove all tab/new-line/revert characters
2289 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
2291 // Then regex all comments like <!-- //--> away
2292 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
2294 // Do we have entries?
2295 if (isset($matches[0][0])) {
2297 foreach ($matches[0] as $match) {
2299 $compactedContent = str_replace($match, '', $compactedContent);
2303 // Set the content again
2304 // @TODO Is this needed for e.g. $GLOBALS['template_content'] ? $this->setRawTemplateData($compactedContent);
2306 // Return compacted content
2307 return $compactedContent;