More fixes for redirect vs. regular output, thanks to wernisman
[mailer.git] / inc / functions.php
index 4df8f56b0d712e981ab6df255419c174142611e6..95d143c2a33e1dcde41e965dd93ac032694a99c5 100644 (file)
@@ -85,16 +85,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                                app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
                                break;
                } // END - switch
-       } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
-               // Headers already sent?
-               if (headers_sent()) {
-                       // Log this error
-                       logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
-
-                       // Trigger an user error
-                       debug_report_bug('Headers are already sent!');
-               } // END - if
-
+       } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
                // Output cached HTML code
                $GLOBALS['output'] = ob_get_contents();
 
@@ -108,12 +99,12 @@ function outputHtml ($htmlCode, $newLine = true) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
-               // Compile and run finished rendered HTML code
-               compileFinalOutput();
-
                // Send all HTTP headers
                sendHttpHeaders();
 
+               // Compile and run finished rendered HTML code
+               compileFinalOutput();
+
                // Output code here, DO NOT REMOVE! ;-)
                outputRawCode($GLOBALS['output']);
        } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
@@ -122,14 +113,17 @@ function outputHtml ($htmlCode, $newLine = true) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
-               // Compile and run finished rendered HTML code
-               compileFinalOutput();
-
                // Send all HTTP headers
                sendHttpHeaders();
 
+               // Compile and run finished rendered HTML code
+               compileFinalOutput();
+
                // Output code here, DO NOT REMOVE! ;-)
                outputRawCode($GLOBALS['output']);
+       } else {
+               // And flush all headers
+               flushHeaders();
        }
 }
 
@@ -142,7 +136,7 @@ function sendHttpHeaders () {
        sendHeader('HTTP/1.1 200');
 
        // General headers for no caching
-       sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
+       sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
        sendHeader('Last-Modified: ' . $now);
        sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
        sendHeader('Pragma: no-cache'); // HTTP/1.0
@@ -177,8 +171,26 @@ function compileFinalOutput () {
                $cnt++;
        } // END - while
 
+       // Compress it?
+       if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+               // Compress it for HTTP gzip
+               $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
+
+               // Add header
+               sendHeader('Content-Encoding: gzip');
+       } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+               // Compress it for HTTP deflate
+               $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
+
+               // Add header
+               sendHeader('Content-Encoding: deflate');
+       }
+
        // Add final length
        sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
+
+       // Flush all headers
+       flushHeaders();
 }
 
 // Output the raw HTML code
@@ -918,28 +930,19 @@ function redirectToUrl ($URL) {
                $rel = '';
        } // END - if
 
-       // Get output buffer
-       $GLOBALS['output'] = ob_get_contents();
-
-       // Clear it only if there is content
-       if (!empty($GLOBALS['output'])) {
-               clearOutputBuffer();
-       } // END - if
-
        // Three different ways to debug...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
        //* DEBUG: */ die($URL);
 
        // Simple probe for bots/spiders from search engines
-       if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
+       if (isSpider()) {
                // Secure the URL against bad things such als HTML insertions and so on...
                $URL = secureString($URL);
 
                // Output new location link as anchor
                outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
        } elseif (!headers_sent()) {
-               //* DEBUG: */ debug_report_bug("URL={$URL}");
                // Clear own output buffer
                $GLOBALS['output'] = '';
 
@@ -1824,19 +1827,19 @@ function sendRawRequest ($host, $request) {
        // Do we use proxy?
        if ($useProxy === true) {
                // Generate CONNECT request header
-               $proxyTunnel  = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
-               $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
+               $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
+               $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
 
                // Use login data to proxy? (username at least!)
                if (getConfig('proxy_username') != '') {
                        // Add it as well
                        $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
-                       $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
+                       $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
                } // END - if
 
                // Add last new-line
                $proxyTunnel .= getConfig('HTTP_EOL');
-               //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
+               //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
 
                // Write request
                fputs($fp, $proxyTunnel);
@@ -1883,7 +1886,7 @@ function sendRawRequest ($host, $request) {
                }
        } // END - foreach
 
-       //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
+       //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
 
        // Proxy agent found?
        if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
@@ -1947,11 +1950,11 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
        $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
 
        // Begin of navigation links
-       $OUT = "[&nbsp;";
+       $OUT = '[&nbsp;';
 
        foreach ($targetArray as $tar) {
-               $OUT .= "<span class=\"admin_user_link\"><a href=\"{%url=modules.php?module=admin&amp;what=" . $tar . "&amp;userid=" . $userid . "%}\" title=\"{--ADMIN_LINK_";
-               //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
+               $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_LINK_';
+               //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
                if (($tar == 'lock_user') && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
                        $OUT .= 'UNLOCK_USER';
@@ -1959,7 +1962,7 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
                        // All other status is fine
                        $OUT .= strtoupper($tar);
                }
-               $OUT .= "_TITLE--}\">{--ADMIN_";
+               $OUT .= '_TITLE--}">{--ADMIN_';
                if (($tar == 'lock_user') && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
                        $OUT .= 'UNLOCK_USER';
@@ -1967,7 +1970,7 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
                        // All other status is fine
                        $OUT .= strtoupper($tar);
                }
-               $OUT .= "--}</a></span>&nbsp;|&nbsp;";
+               $OUT .= '--}</a></span>&nbsp;|&nbsp;';
        }
 
        // Finish navigation link
@@ -2031,15 +2034,15 @@ function generateHash ($plainText, $salt = '') {
 
                // Generate SHA1 sum from modula of number and the prime number
                $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
-               //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
+               //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
                $sha1 = scrambleString($sha1);
-               //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
+               //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
                //* DEBUG: */ $sha1b = descrambleString($sha1);
-               //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
+               //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
 
                // Generate the password salt string
                $salt = substr($sha1, 0, getConfig('salt_length'));
-               //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
+               //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
        } else {
                // Use given salt
                //* DEBUG: */ print 'salt=' . $salt . '<br />';
@@ -2075,7 +2078,7 @@ function scrambleString($str) {
        }
 
        // Scramble string here
-       //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
+       //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
        for ($idx = '0'; $idx < strlen($str); $idx++) {
                // Get char on scrambled position
                $char = substr($str, $scrambleNums[$idx], 1);
@@ -2085,7 +2088,7 @@ function scrambleString($str) {
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
+       //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
        return $scrambled;
 }
 
@@ -2102,14 +2105,14 @@ function descrambleString($str) {
 
        // Begin descrambling
        $orig = str_repeat(' ', 40);
-       //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
+       //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
        for ($idx = '0'; $idx < 40; $idx++) {
                $char = substr($str, $idx, 1);
                $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
+       //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
        return $orig;
 }
 
@@ -2598,34 +2601,33 @@ function getMessageFromErrorCode ($code) {
        $message = '';
        switch ($code) {
                case '': break;
-               case getCode('LOGOUT_DONE')      : $message = getMessage('LOGOUT_DONE'); break;
-               case getCode('LOGOUT_FAILED')    : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
-               case getCode('DATA_INVALID')     : $message = getMessage('MAIL_DATA_INVALID'); break;
-               case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
-               case getCode('ACCOUNT_LOCKED')   : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
-               case getCode('USER_404')         : $message = getMessage('USER_404'); break;
-               case getCode('STATS_404')        : $message = getMessage('MAIL_STATS_404'); break;
-               case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
-               case getCode('WRONG_PASS')       : $message = getMessage('LOGIN_WRONG_PASS'); break;
-               case getCode('WRONG_ID')         : $message = getMessage('LOGIN_WRONG_ID'); break;
-               case getCode('ID_LOCKED')        : $message = getMessage('LOGIN_ID_LOCKED'); break;
-               case getCode('ID_UNCONFIRMED')   : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
-               case getCode('ID_GUEST')         : $message = getMessage('LOGIN_ID_GUEST'); break;
-               case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
-               case getCode('BEG_SAME_AS_OWN')  : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
-               case getCode('LOGIN_FAILED')     : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
-               case getCode('MODULE_MEM_ONLY')  : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
-               case getCode('OVERLENGTH')       : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
-               case getCode('URL_FOUND')        : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
-               case getCode('SUBJ_URL')         : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
-               case getCode('BLIST_URL')        : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
-               case getCode('NO_RECS_LEFT')     : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
-               case getCode('INVALID_TAGS')     : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
-               case getCode('MORE_POINTS')      : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
-               case getCode('MORE_RECEIVERS1')  : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
-               case getCode('MORE_RECEIVERS2')  : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
-               case getCode('MORE_RECEIVERS3')  : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
-               case getCode('INVALID_URL')      : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
+               case getCode('LOGOUT_DONE')       : $message = getMessage('LOGOUT_DONE'); break;
+               case getCode('LOGOUT_FAILED')     : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
+               case getCode('DATA_INVALID')      : $message = getMessage('MAIL_DATA_INVALID'); break;
+               case getCode('POSSIBLE_INVALID')  : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
+               case getCode('ACCOUNT_LOCKED')    : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
+               case getCode('USER_404')          : $message = getMessage('USER_404'); break;
+               case getCode('STATS_404')         : $message = getMessage('MAIL_STATS_404'); break;
+               case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+               case getCode('WRONG_PASS')        : $message = getMessage('LOGIN_WRONG_PASS'); break;
+               case getCode('WRONG_ID')          : $message = getMessage('LOGIN_WRONG_ID'); break;
+               case getCode('STATUS_LOCKED')     : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
+               case getCode('STATUS_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
+               case getCode('COOKIES_DISABLED')  : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
+               case getCode('BEG_SAME_AS_OWN')   : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
+               case getCode('LOGIN_FAILED')      : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
+               case getCode('MODULE_MEM_ONLY')   : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
+               case getCode('OVERLENGTH')        : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
+               case getCode('URL_FOUND')         : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
+               case getCode('SUBJ_URL')          : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
+               case getCode('BLIST_URL')         : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
+               case getCode('NO_RECS_LEFT')      : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
+               case getCode('INVALID_TAGS')      : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
+               case getCode('MORE_POINTS')       : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
+               case getCode('MORE_RECEIVERS1')   : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
+               case getCode('MORE_RECEIVERS2')   : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
+               case getCode('MORE_RECEIVERS3')   : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
+               case getCode('INVALID_URL')       : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
 
                case getCode('ERROR_MAILID'):
                        if (isExtensionActive('mailid', true)) {
@@ -2847,7 +2849,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 }
 // Send notification to admin
 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
-       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
+       if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
                // Send new way
                sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
@@ -3835,7 +3837,7 @@ function encodeUrl ($url, $outputMode = '0') {
        } // END - if
 
        // Add {?URL?} ?
-       if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}')) {
+       if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
                // Add it
                $url = '{?URL?}/' . $url;
        } // END - if
@@ -3846,8 +3848,14 @@ function encodeUrl ($url, $outputMode = '0') {
 
 // Simple check for spider
 function isSpider () {
+       // Get the UA
+       $userAgent = strtolower(detectUserAgent(true));
+
+       // It should not be empty, if so it is better a spider/bot
+       if (empty($userAgent)) return true;
+
        // Is it a spider?
-       return ((strpos('spider', strtolower(detectUserAgent(true))) !== false) || (strpos('bot', strtolower(detectUserAgent(true))) !== false));
+       return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
 }
 
 //////////////////////////////////////////////////