Compilation time added, some compileCode() calles removed, ADMIN_WHAT_404 added
[mailer.git] / inc / functions.php
index 21938e565e2ac5a512350e0895d0abcc89252f25..c9d530034735a1d88b48db113107bd8082ac0f42 100644 (file)
@@ -226,7 +226,10 @@ function loadTemplate ($template, $return=false, $content=array()) {
        global $DATA;
 
        // Do we have cache?
-       if (!isset($GLOBALS['template_eval'][$template])) {
+       if (isTemplateCached($template)) {
+               // Evaluate the cache
+               eval(readTemplateCache($template));
+       } elseif (!isset($GLOBALS['template_eval'][$template])) {
                // Add more variables which you want to use in your template files
                $username = getUsername();
 
@@ -240,40 +243,6 @@ function loadTemplate ($template, $return=false, $content=array()) {
                $ret = '';
                if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
 
-               // Generate date/time string
-               $date_time = generateDateTime(time(), 1);
-
-               // Is content an array
-               if (is_array($content)) $content['date_time'] = $date_time;
-
-               // @DEPRECATED Try to rewrite the if() condition
-               if ($template == 'member_support_form') {
-                       // Support request of a member
-                       $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(getUserId()), __FUNCTION__, __LINE__);
-
-                       // Is content an array?
-                       if (is_array($content)) {
-                               // Merge data
-                               $content = merge_array($content, SQL_FETCHARRAY($result));
-
-                               // Translate gender
-                               $content['gender'] = translateGender($content['gender']);
-                       } else {
-                               // @DEPRECATED
-                               // @TODO Find all templates which are using these direct variables and rewrite them.
-                               // @TODO After this step is done, this else-block is history
-                               list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
-
-                               // Translate gender
-                               $gender = translateGender($gender);
-                               logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
-                       }
-
-                       // Free result
-                       SQL_FREERESULT($result);
-               } // END - if
-
                // Base directory
                $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
                $mode = '';
@@ -358,7 +327,7 @@ function loadTemplate ($template, $return=false, $content=array()) {
                                        $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
 
                                        // Prepare eval() command
-                                       $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
+                                       $eval = '$ret = "' . compileCode(smartAddSlashes($ret)) . '";';
                                } else {
                                        // Prepare eval() command
                                        $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
@@ -461,25 +430,22 @@ function loadEmailTemplate ($template, $content = array(), $UID = 0) {
        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
        if (($UID > 0) && (is_array($content))) {
                // If nickname extension is installed, fetch nickname as well
-               if (isExtensionActive('nickname')) {
+               if (isNicknameUsed($UID)) {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
-                       // Load nickname
-                       $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       // Load by nickname
+                       fetchUserData($UID, 'nickname');
                } else {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
-                       /// Load normal data
-                       $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       /// Load by userid
+                       fetchUserData($UID);
                }
 
-               // Fetch and merge data
+               // Merge data if valid
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
-               $content = merge_array($content, SQL_FETCHARRAY($result));
+               if (isUserDataValid()) {
+                       $content = merge_array($content, getUserDataArray());
+               } // END - if
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
-
-               // Free result
-               SQL_FREERESULT($result);
        } // END - if
 
        // Translate M to male or F to female if present
@@ -582,22 +548,14 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
                        ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
                        return;
                } else {
-                       // Load email address
-                       $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($toEmail)), __FUNCTION__, __LINE__);
-                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email).'<br />');
-
                        // Does the user exist?
-                       if (SQL_NUMROWS($result_email)) {
-                               // Load email address
-                               list($toEmail) = SQL_FETCHROW($result_email);
+                       if (fetchUserData($toEmail)) {
+                               // Get the email
+                               $toEmail = getUserData('email');
                        } else {
                                // Set webmaster
                                $toEmail = getConfig('WEBMASTER');
                        }
-
-                       // Free result
-                       SQL_FREERESULT($result_email);
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
@@ -962,8 +920,8 @@ function makeTime ($hours, $minutes, $seconds, $stamp) {
 
 // Redirects to an URL and if neccessarry extends it with own base URL
 function redirectToUrl ($URL) {
-       // Compile out URI codes
-       $URL = compileUriCode($URL);
+       // Compile out codes
+       eval('$URL = "' . compileCode($URL) . '";');
 
        // Check if http(s):// is there
        if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
@@ -973,7 +931,7 @@ function redirectToUrl ($URL) {
 
        // Three different debug ways...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
        //* DEBUG: */ die($URL);
 
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
@@ -1038,6 +996,9 @@ function compileCode ($code, $simple = false, $constants = true, $full = true) {
                return $code;
        } // END - if
 
+       // Start couting
+       $startCompile = explode(' ', microtime());
+
        // Init replacement-array with full security characters
        $secChars = $GLOBALS['security_chars'];
 
@@ -1113,6 +1074,12 @@ function compileCode ($code, $simple = false, $constants = true, $full = true) {
                } // END - foreach
        } // END - if
 
+       // Get timing
+       $compiled = explode(' ', microtime());
+
+       // Add timing
+       $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
+
        // Return compiled code
        return $code;
 }
@@ -1794,9 +1761,6 @@ function sendPostRequest ($script, $postData) {
                return array('', '', '');
        } // END - if
 
-       // Compile the script name
-       $script = compileCode($script);
-
        // Extract host name from script
        $host = extractHostnameFromUrl($script);
 
@@ -1937,9 +1901,6 @@ function sendRawRequest ($host, $request) {
 
 // Taken from www.php.net eregi() user comments
 function isEmailValid ($email) {
-       // Compile email
-       $email = compileCode($email);
-
        // Check first part of email address
        $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
 
@@ -2405,11 +2366,11 @@ function getThemeId ($name) {
 }
 
 // Generates an error code from given account status
-function generateErrorCodeFromUserStatus ($status) {
-       // @TODO The status should never be empty
-       if (empty($status)) {
-               // Something really bad happend here
-               debug_report_bug(__FUNCTION__ . ': status is empty.');
+function generateErrorCodeFromUserStatus ($status='') {
+       // If no status is provided, use the default, cached
+       if ((empty($status)) && (isMember())) {
+               // Get user status
+               $status = getUserData('status');
        } // END - if
 
        // Default error code if unknown account status
@@ -2958,7 +2919,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 }
 // Send notification to admin
 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
-       if (getExtensionVersion('admins') >= '0.4.1') {
+       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
                // Send new way
                sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
@@ -3193,8 +3154,8 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
 
 // Determines referal id and sets it
 function determineReferalId () {
-       // Skip this in non-html-mode
-       if (getOutputMode() != 0) return false;
+       // Skip this in non-html-mode and outside ref.php
+       if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
 
        // Check if refid is set
        if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
@@ -3221,12 +3182,30 @@ function determineReferalId () {
                // Set default refid as refid in URL
                $GLOBALS['refid'] = getConfig('def_refid');
        } else {
-               // No default ID when sql_patches is not installed or none set
+               // No default id when sql_patches is not installed or none set
                $GLOBALS['refid'] = 0;
        }
 
        // Set cookie when default refid > 0
        if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+               // Default is not found
+               $found = false;
+
+               // Do we have nickname or userid set?
+               if (isNicknameUsed($GLOBALS['refid'])) {
+                       // Nickname in URL, so load the id
+                       $found = fetchUserData($GLOBALS['refid'], 'nickname');
+               } elseif ($GLOBALS['refid'] > 0) {
+                       // Direct userid entered
+                       $found = fetchUserData($GLOBALS['refid']);
+               }
+
+               // Is the record valid?
+               if (($found === false) || (!isUserDataValid())) {
+                       // No, then reset referal id
+                       $GLOBALS['refid'] = getConfig('def_refid');
+               } // END - if
+
                // Set cookie
                setSession('refid', $GLOBALS['refid']);
        } // END - if
@@ -3263,6 +3242,10 @@ function shutdown () {
 
 // Setter for userid
 function setUserId ($userid) {
+       // We should not set userid to zero
+       if ($userid == 0) debug_report_bug('Userid should not be set zero.');
+
+       // Set it secured
        $GLOBALS['userid'] = bigintval($userid);
 }
 
@@ -3603,6 +3586,107 @@ function convertReceivers ($old) {
        return str_replace(';', ', ', $old);
 }
 
+// Determines the right page title
+function determinePageTitle () {
+       // Config and database connection valid?
+       if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+               // Init title
+               $TITLE = '';
+
+               // Title decoration enabled?
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
+
+               // Do we have some extra title?
+               if (isExtraTitleSet()) {
+                       // Then prepent it
+                       $TITLE .= getExtraTitle() . ' by ';
+               } // END - if
+
+               // Add main title
+               $TITLE .= getConfig('MAIN_TITLE');
+
+               // Add title of module? (middle decoration will also be added!)
+               if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+                       $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+               } // END - if
+
+               // Add title from what file
+               $mode = '';
+               if (getModule() == 'login') $mode = 'member';
+               elseif (getModule() == 'index') $mode = 'guest';
+               if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
+
+               // Add title decorations? (right)
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
+
+               // Remember title in constant for the template
+               $pageTitle = $TITLE;
+       } elseif ((isInstalled()) && (isAdminRegistered())) {
+               // Installed, admin registered but no ext-sql_patches
+               $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
+       } elseif ((isInstalled()) && (!isAdminRegistered())) {
+               // Installed but no admin registered
+               $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+       } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+               // Installation mode
+               $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
+       } else {
+               // Configuration not found!
+               $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
+
+               // Do not add the fatal message in installation mode
+               if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
+       }
+
+       // Return title
+       return $pageTitle;
+}
+
+// Checks wethere there is a cache file there. This function is cached.
+function isTemplateCached ($template) {
+       // Do we have cached this result?
+       if (!isset($GLOBALS['template_cache'][$template])) {
+               // Generate FQFN
+               $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // Is it there?
+               $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
+       } // END - if
+
+       // Return it
+       return $GLOBALS['template_cache'][$template];
+}
+
+// Flushes non-flushed template cache to disk
+function flushTemplateCache ($template, $eval) {
+       // Is this cache flushed?
+       if (!isTemplateCached($template)) {
+               // Generate FQFN
+               $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // Replace username with a call
+               $eval = str_replace('$username', '".getUsername()."', $eval);
+
+               // And flush it
+               writeToFile($FQFN, $eval, true);
+       } // END - if
+}
+
+// Reads a template cache
+function readTemplateCache ($template) {
+       // Check it again
+       if (isTemplateCached($template)) {
+               // Generate FQFN
+               $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // And read from it
+               $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
+       } // END - if
+
+       // And return it
+       return $GLOBALS['template_eval'][$template];
+}
+
 //////////////////////////////////////////////////
 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
 //////////////////////////////////////////////////