Support all extensions in link, too
[mailer.git] / inc / template-functions.php
index a9de28da56482b5a006b42690b6be9a031b1436c..4b6420a59f013706ed0e545a6329842f5762200a 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -235,26 +235,26 @@ function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE)
        enableTemplateHtml($insertComments);
 
        // Init counter
-       $count = 0;
+       $totalCompilations = 0;
 
        // Compile all out
-       while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($count < 7)) {
+       while (((isInString('{--', $code)) || (isInString('{DQUOTE}', $code)) || (isInString('{?', $code)) || (isInString('{%', $code) !== FALSE)) && ($totalCompilations < 7)) {
                // Init common variables
                $content = array();
                $newContent = '';
 
                // Compile it
-               //* DEBUG: */ debugOutput('<pre>'.linenumberCode($code).'</pre>');
+               //* DEBUG: */ debugOutput('<pre>'.lineNumberCode($code).'</pre>');
                $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code), $enableCodes)) . '";';
-               //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.linenumberCode($eval).'</pre>');
+               //* DEBUG: */ if (!$insertComments) print('EVAL=<pre>'.lineNumberCode($eval).'</pre>');
                eval($eval);
-               //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.linenumberCode($newContent).'</pre>');
+               //* DEBUG: */ if (!$insertComments) print('NEW=<pre>'.lineNumberCode($newContent).'</pre>');
                //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
 
                // Was that eval okay?
                if (empty($newContent)) {
                        // Something went wrong!
-                       reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', FALSE);
+                       reportBug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . lineNumberCode($eval) . '</pre>', FALSE);
                } // END - if
 
                // Use it again
@@ -267,14 +267,14 @@ function doFinalCompilation ($code, $insertComments = TRUE, $enableCodes = TRUE)
                } // END - if
 
                // Count round
-               $count++;
+               $totalCompilations++;
        } // END - while
 
        // Add debugging data in HTML code, if mode is enabled
        if ((isDebugModeEnabled()) && ($insertComments === TRUE) && (isHtmlOutputMode())) {
                // Add loop count
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isDebugModeEnabled()=' . intval(isDebugModeEnabled()) . ',insertComments=' . intval($insertComments) . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()));
-               $code .= '<!-- Total compilation loop=' . $count . ' //-->';
+               $code .= '<!-- Total compilation loop=' . $totalCompilations . ' //-->';
        } // END - if
 
        // Return the compiled code
@@ -616,7 +616,7 @@ function getMenuCssClasses ($data) {
 
 // Generate XHTML code for the CAPTCHA
 function generateCaptchaCode ($code, $type, $urlId, $userid) {
-       return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $urlId . '&amp;do=img&amp;code=' . $code . '%}" />';
+       return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid.php?userid=' . $userid . '&amp;' . $type . '=' . $urlId . '&amp;do=img&amp;code=' . $code . '%}" />';
 }
 
 // Compiles the given HTML/mail code
@@ -787,7 +787,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'f
                        // Use configured min age or fixed?
                        if (isExtensionInstalledAndNewer('other', '0.2.1')) {
                                // Configured
-                               $startYear = $year - getConfig('min_age');
+                               $startYear = $year - getMinAge();
                        } else {
                                // Fixed 16 years
                                $startYear = $year - 16;
@@ -829,6 +829,14 @@ function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'f
                        } // END - for
                        break;
 
+               case 'mn': // Months, numeric
+                       for ($idx = 0; $idx <= 12; $idx++) {
+                               $OUT .= '<option value="' . $idx . '"';
+                               if ($default == $idx) $OUT .= ' selected="selected"';
+                               $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
+                       } // END - for
+                       break;
+
                case 'we': // Weeks
                        for ($idx = 0; $idx <= 4; $idx++) {
                                $OUT .= '  <option value="' . $idx . '"';
@@ -838,15 +846,15 @@ function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'f
                        break;
 
                case 'da': // Days
-                       for ($idx = 0; $idx < 32; $idx++) {
+                       for ($idx = 0; $idx <= 31; $idx++) {
                                $OUT .= '<option value="' . $idx . '"';
                                if ($default == $idx) $OUT .= ' selected="selected"';
-                               $OUT .= '>' .padLeftZero($idx) . '</option>';
+                               $OUT .= '>{%pipe,padLeftZero=' . $idx . '%}</option>';
                        } // END - for
                        break;
 
                case 'ho': // Hours
-                       for ($idx = 0; $idx < 24; $idx++) {
+                       for ($idx = 0; $idx <= 23; $idx++) {
                                if (strlen($idx) == 1) $idx = 0 . $idx;
                                $OUT .= '<option value="' . $idx . '"';
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -856,7 +864,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = NULL, $class = 'f
 
                case 'mi': // Minutes
                case 'se': // Seconds
-                       for ($idx = 0; $idx < 60; $idx+=5) {
+                       for ($idx = 0; $idx <= 59; $idx+=5) {
                                if (strlen($idx) == 1) $idx = 0 . $idx;
                                $OUT .= '<option value="' . $idx . '"';
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1009,7 +1017,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        // Time unit -> field name
                        'unit_field' => array(
                                'Y' => 'ye',
-                               'M' => 'mo',
+                               'M' => 'mn',
                                'W' => 'we',
                                'D' => 'da',
                                'h' => 'ho',
@@ -1154,16 +1162,16 @@ function generateEmailLink ($email, $table = 'admins') {
  * functionality like logging and admin notification (which you can configure
  * through your admin area).
  *
- * @param      $F                      Function or file basename where the error came from
- * @param      $L                      Line number where the error came from
+ * @param      $file           Function or file basename where the error came from
+ * @param      $line           Line number where the error came from
  * @param      $message        Message which shall be output to web
  * @return     void
  */
-function app_exit ($F, $L, $message) {
+function app_exit ($file, $line, $message) {
        // Check if Script is already dieing and not let it kill itself another 1000 times
        if (isset($GLOBALS['app_died'])) {
                // Script tried to kill itself twice
-               die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
+               die('[' . __FUNCTION__ . ':' . __LINE__ . ']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $file . ', line=' . $line);
        } // END - if
 
        // Make sure, that the script realy realy diese here and now
@@ -1184,8 +1192,8 @@ function app_exit ($F, $L, $message) {
        // Rewrite message for output
        $message = sprintf(
                getMessage('MAILER_HAS_DIED'),
-               basename($F),
-               $L,
+               basename($file),
+               $line,
                $message
        );
 
@@ -1233,6 +1241,12 @@ function displayParsingTime () {
 
        // Load the template
        $GLOBALS['__page_footer'] .= loadTemplate('show_timings', TRUE, $content);
+
+       // Is debug enabled?
+       if (isDebugModeEnabled()) {
+               // Log loading of total includes
+               //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loaded includes: ' . count($GLOBALS['inc_loaded']) . ', readable files: ' . count($GLOBALS['file_readable']));
+       } // END - if
 }
 
 /**
@@ -1244,16 +1258,16 @@ function displayParsingTime () {
  * app_exit() is more a "private" function and will only output a bug message to
  * the user, no email and no logging.
  *
- * @param      $F                      Function or file basename where the error came from
- * @param      $L                      Line number where the error came from
+ * @param      $file           Function or file basename where the error came from
+ * @param      $line           Line number where the error came from
  * @param      $sendEmail      Wether to send an email to all configured administrators
  * @return     void
  */
-function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
+function reportBug ($file, $line, $message = '', $sendEmail = TRUE) {
        // Is this already called?
        if (isset($GLOBALS[__FUNCTION__])) {
                // Other backtrace
-               print '[' . $F . ':' . $L . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
+               print '[' . $file . ':' . $line . ':] ' . __FUNCTION__ . ' has already died! Message:' . $message . '<br />Backtrace:<pre>';
                debug_print_backtrace();
                die('</pre>');
        } // END - if
@@ -1275,7 +1289,7 @@ function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
                );
 
                // @TODO Add a little more infos here
-               logDebugMessage($F, $L, strip_tags($message));
+               logDebugMessage($file, $line, strip_tags($message));
        } // END - if
 
        // Add output
@@ -1300,7 +1314,7 @@ function reportBug ($F, $L, $message = '', $sendEmail = TRUE) {
        // Is there HTML/CSS/AJAX mode?
        if (((isHtmlOutputMode()) || (isCssOutputMode()) || (isAjaxOutputMode())) && (isDebugModeEnabled())) {
                // And abort here
-               app_exit($F, $L, $debug);
+               app_exit($file, $line, $debug);
        } else {
                // Raw/image output mode and all other modes doesn't work well with text ...
                die();
@@ -1471,7 +1485,7 @@ function generateExtensionInactiveNotInstalledMessage ($ext_name) {
 }
 
 // Print code with line numbers
-function linenumberCode ($code)    {
+function lineNumberCode ($code)    {
        // By default copy the code
        $codeE = $code;
 
@@ -1505,7 +1519,7 @@ function determinePageTitle () {
        $pageTitle = '';
 
        // Config and database connection valid?
-       if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+       if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (isSqlLinkUp()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
                // Title decoration enabled?
                if ((isTitleDecorationEnabled()) && (getTitleLeft() != '')) {
                        $pageTitle .= '{%config,trim=title_left%} ';
@@ -1948,6 +1962,12 @@ function displayMessage ($message, $return = FALSE) {
        return loadTemplate('admin_settings_saved', $return, $message);
 }
 
+// Displays given error message in admin_settings_saved template
+function displayErrorMessage ($message, $return = FALSE) {
+       // Load the template
+       return loadTemplate('admin_settings_unsaved', $return, $message);
+}
+
 // Generates a selection box for (maybe) given gender
 function generateGenderSelectionBox ($selectedGender = '', $fieldName = 'gender') {
        // Start the HTML code
@@ -2031,6 +2051,71 @@ function addJavaScriptMenuContent ($menuMode, $mainAction, $action, $what) {
        return $OUT;
 }
 
+// Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
+function anonymizeSensitiveData ($data) {
+       // Trim it
+       $data = trim($data);
+
+       // Is it empty?
+       if (empty($data)) {
+               // Then add three dashes
+               $data = '---';
+       } elseif (isUrlValid($data)) {
+               // Is a referrer, so is it black-listed?
+               if (isAdmin()) {
+                       // Is admin, has always priority
+                       $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
+               } elseif ((isExtensionActive('blacklist')) && (isUrlBlacklisted($data))) {
+                       // Yes, so replace it with text
+                       $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
+               } else {
+                       // A  member is viewing this referral URL
+                       $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
+               }
+       } elseif (isIp4AddressValid($data)) {
+               // Is an IPv4 address
+               $ipArray = explode('.', $data);
+
+               // Only display first 2 octets
+               $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
+       } else {
+               // Generic data
+               $data = '<em>{--DATA_IS_HIDDEN--}</em>';
+       }
+
+       // Return it (hopefully) anonymized
+       return $data;
+}
+
+/**
+ * Removes all comments, tabs and new-line characters to compact the content
+ *
+ * @param      $uncompactedContent             The uncompacted content
+ * @return     $compactedContent               The compacted content
+ */
+function compactContent ($uncompactedContent) {
+       // First, remove all tab/new-line/revert characters
+       $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
+
+       // Make a space after >
+       $compactedContent = str_replace(array('>', '  '), array('> ', ' '), $compactedContent);
+
+       // Then regex all comments like <!-- //--> away
+       preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
+
+       // Do we have entries?
+       if (isset($matches[0][0])) {
+               // Remove all
+               foreach ($matches[0] as $match) {
+                       // Remove the match
+                       $compactedContent = str_replace($match, '', $compactedContent);
+               } // END - foreach
+       } // END - if
+
+       // Return compacted content
+       return $compactedContent;
+}
+
 //-----------------------------------------------------------------------------
 //                     Template helper functions for EL code
 //-----------------------------------------------------------------------------
@@ -2075,13 +2160,13 @@ function doTemplateExtensionRegistrationLink ($templateName, $clear, $ext_name)
 // Helper function to create bonus mail admin links
 function doTemplateAdminBonusMailLinks ($templateName, $clear, $bonusId) {
        // Call the inner function
-       return generateAdminMailLinks('bid', $bonusId);
+       return generateAdminMailLinks('bonus', $bonusId);
 }
 
 // Helper function to create member mail admin links
 function doTemplateAdminMemberMailLinks ($templateName, $clear, $mailId) {
        // Call the inner function
-       return generateAdminMailLinks('mid', $mailId);
+       return generateAdminMailLinks('normal', $mailId);
 }
 
 // Helper function to create a selection box for YES/NO configuration entries
@@ -2258,69 +2343,23 @@ function doTemplateLoadTemplate ($templateName, $clear = FALSE, $theTemplate, $c
        return loadTemplate($theTemplate, TRUE, $content);
 }
 
-// Tries to anonymize some sensitive data (e.g. IP address, user agent, referrer, etc.)
-function anonymizeSensitiveData ($data) {
-       // Trim it
-       $data = trim($data);
-
-       // Is it empty?
-       if (empty($data)) {
-               // Then add three dashes
-               $data = '---';
-       } elseif (isUrlValid($data)) {
-               // Is a referrer, so is it black-listed?
-               if (isAdmin()) {
-                       // Is admin, has always priority
-                       $data = '[<a href="{%pipe,generateFrametesterUrl=' . $data . '%}" target="_blank">{--ADMIN_TEST_URL--}</a>]';
-               } elseif (isUrlBlacklisted($data)) {
-                       // Yes, so replace it with text
-                       $data = '<em>{--URL_IS_BLACKLISTED--}</em>';
-               } else {
-                       // A  member is viewing this referral URL
-                       $data = '[<a href="{%pipe,generateDereferrerUrl=' . $data . '%}" target="_blank">{--MEMBER_TEST_URL--}</a>]';
-               }
-       } elseif (isIp4AddressValid($data)) {
-               // Is an IPv4 address
-               $ipArray = explode('.', $data);
-
-               // Only display first 2 octets
-               $data = $ipArray[0] . '.' . $ipArray[1] . '.?.?';
-       } else {
-               // Generic data
-               $data = '<em>{--DATA_IS_HIDDEN--}</em>';
-       }
-
-       // Return it (hopefully) anonymized
-       return $data;
-}
-
-/**
- * Removes all commentd, tabs and new-line characters to compact the content
- *
- * @param      $uncompactedContent             The uncompacted content
- * @return     $compactedContent               The compacted content
- */
-function compactContent ($uncompactedContent) {
-       // First, remove all tab/new-line/revert characters
-       $compactedContent = str_replace(chr(9), '', str_replace(PHP_EOL, '', str_replace(chr(13), '', $uncompactedContent)));
-
-       // Then regex all comments like <!-- //--> away
-       preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
+// Output HTML code for favicon.ico, if found
+function doTemplateMetaFavIcon ($templateName, $clear = FALSE) {
+       // Default is not found
+       $out = '';
 
-       // Do we have entries?
-       if (isset($matches[0][0])) {
-               // Remove all
-               foreach ($matches[0] as $match) {
-                       // Remove the match
-                       $compactedContent = str_replace($match, '', $compactedContent);
-               } // END - foreach
-       } // END - if
-
-       // Set the content again
-       // @TODO Is this needed for e.g. $GLOBALS['template_content'] ? $this->setRawTemplateData($compactedContent);
+       // Check all common extensions
+       foreach (array('ico', 'gif', 'png') as $extension) {
+               // Is the file there?
+               if (isFileReadable(getPath() . 'favicon.' . $extension)) {
+                       // Then use this and abort
+                       $out = '<link rel="shortcut icon" href="{%url=favicon.' . $extension . '%}" type="image/' . $extension . '" />';
+                       break;
+               } // END - if
+       } // END - while
 
-       // Return compacted content
-       return $compactedContent;
+       // Return code
+       return $out;
 }
 
 // [EOF]