xref: /dokuwiki/inc/HTTP/HTTPClient.php (revision 6c16a3a9aa602bb7e269fb6d5d18e1353e17f97f)
15a8d6e48SMichael Große<?php
25a8d6e48SMichael Große
35a8d6e48SMichael Großenamespace dokuwiki\HTTP;
45a8d6e48SMichael Große
55a8d6e48SMichael Großedefine('HTTP_NL', "\r\n");
65a8d6e48SMichael Große
75a8d6e48SMichael Große
85a8d6e48SMichael Große/**
95a8d6e48SMichael Große * This class implements a basic HTTP client
105a8d6e48SMichael Große *
115a8d6e48SMichael Große * It supports POST and GET, Proxy usage, basic authentication,
128a10b6f0SElan Ruusamäe * handles cookies and referrers. It is based upon the httpclient
135a8d6e48SMichael Große * function from the VideoDB project.
145a8d6e48SMichael Große *
158a10b6f0SElan Ruusamäe * @link   https://www.splitbrain.org/projects/videodb
165a8d6e48SMichael Große * @author Andreas Goetz <cpuidle@gmx.de>
175a8d6e48SMichael Große * @author Andreas Gohr <andi@splitbrain.org>
185a8d6e48SMichael Große * @author Tobias Sarnowski <sarnowski@new-thoughts.org>
195a8d6e48SMichael Große */
20a3b08db5SAndreas Gohrclass HTTPClient
21a3b08db5SAndreas Gohr{
225a8d6e48SMichael Große    //set these if you like
235a8d6e48SMichael Große    public $agent;         // User agent
24a3b08db5SAndreas Gohr    public $http = '1.0';          // HTTP version defaults to 1.0
25a3b08db5SAndreas Gohr    public $timeout = 15;       // read timeout (seconds)
26a3b08db5SAndreas Gohr    public $cookies = [];
27a3b08db5SAndreas Gohr    public $referer = '';
28a3b08db5SAndreas Gohr    public $max_redirect = 3;
29a3b08db5SAndreas Gohr    public $max_bodysize = 0;
305a8d6e48SMichael Große    public $max_bodysize_abort = true;  // if set, abort if the response body is bigger than max_bodysize
31a3b08db5SAndreas Gohr    public $header_regexp = ''; // if set this RE must match against the headers, else abort
32a3b08db5SAndreas Gohr    public $headers = [];
33a3b08db5SAndreas Gohr    public $debug = false;
345a8d6e48SMichael Große    public $start = 0.0; // for timings
355a8d6e48SMichael Große    public $keep_alive = true; // keep alive rocks
365a8d6e48SMichael Große
375a8d6e48SMichael Große    // don't set these, read on error
385a8d6e48SMichael Große    public $error;
39a3b08db5SAndreas Gohr    public $redirect_count = 0;
405a8d6e48SMichael Große
415a8d6e48SMichael Große    // read these after a successful request
42a3b08db5SAndreas Gohr    public $status = 0;
435a8d6e48SMichael Große    public $resp_body;
445a8d6e48SMichael Große    public $resp_headers;
455a8d6e48SMichael Große
465a8d6e48SMichael Große    // set these to do basic authentication
475a8d6e48SMichael Große    public $user;
485a8d6e48SMichael Große    public $pass;
495a8d6e48SMichael Große
505a8d6e48SMichael Große    // set these if you need to use a proxy
515a8d6e48SMichael Große    public $proxy_host;
525a8d6e48SMichael Große    public $proxy_port;
535a8d6e48SMichael Große    public $proxy_user;
545a8d6e48SMichael Große    public $proxy_pass;
555a8d6e48SMichael Große    public $proxy_ssl; //boolean set to true if your proxy needs SSL
565a8d6e48SMichael Große    public $proxy_except; // regexp of URLs to exclude from proxy
575a8d6e48SMichael Große
585a8d6e48SMichael Große    // list of kept alive connections
59a3b08db5SAndreas Gohr    protected static $connections = [];
605a8d6e48SMichael Große
615a8d6e48SMichael Große    // what we use as boundary on multipart/form-data posts
625a8d6e48SMichael Große    protected $boundary = '---DokuWikiHTTPClient--4523452351';
635a8d6e48SMichael Große
645a8d6e48SMichael Große    /**
655a8d6e48SMichael Große     * Constructor.
665a8d6e48SMichael Große     *
675a8d6e48SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
685a8d6e48SMichael Große     */
69a3b08db5SAndreas Gohr    public function __construct()
70a3b08db5SAndreas Gohr    {
715a8d6e48SMichael Große        $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; ' . PHP_OS . ')';
725a8d6e48SMichael Große        if (extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip';
735a8d6e48SMichael Große        $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,' .
745a8d6e48SMichael Große            'text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
755a8d6e48SMichael Große        $this->headers['Accept-Language'] = 'en-us';
765a8d6e48SMichael Große    }
775a8d6e48SMichael Große
785a8d6e48SMichael Große
795a8d6e48SMichael Große    /**
805a8d6e48SMichael Große     * Simple function to do a GET request
815a8d6e48SMichael Große     *
825a8d6e48SMichael Große     * Returns the wanted page or false on an error;
835a8d6e48SMichael Große     *
845a8d6e48SMichael Große     * @param string $url The URL to fetch
855a8d6e48SMichael Große     * @param bool $sloppy304 Return body on 304 not modified
865a8d6e48SMichael Große     * @return false|string  response body, false on error
875a8d6e48SMichael Große     *
885a8d6e48SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
895a8d6e48SMichael Große     */
90a3b08db5SAndreas Gohr    public function get($url, $sloppy304 = false)
91a3b08db5SAndreas Gohr    {
925a8d6e48SMichael Große        if (!$this->sendRequest($url)) return false;
935a8d6e48SMichael Große        if ($this->status == 304 && $sloppy304) return $this->resp_body;
945a8d6e48SMichael Große        if ($this->status < 200 || $this->status > 206) return false;
955a8d6e48SMichael Große        return $this->resp_body;
965a8d6e48SMichael Große    }
975a8d6e48SMichael Große
985a8d6e48SMichael Große    /**
995a8d6e48SMichael Große     * Simple function to do a GET request with given parameters
1005a8d6e48SMichael Große     *
1015a8d6e48SMichael Große     * Returns the wanted page or false on an error.
1025a8d6e48SMichael Große     *
1035a8d6e48SMichael Große     * This is a convenience wrapper around get(). The given parameters
1045a8d6e48SMichael Große     * will be correctly encoded and added to the given base URL.
1055a8d6e48SMichael Große     *
1065a8d6e48SMichael Große     * @param string $url The URL to fetch
1075a8d6e48SMichael Große     * @param array $data Associative array of parameters
1085a8d6e48SMichael Große     * @param bool $sloppy304 Return body on 304 not modified
1095a8d6e48SMichael Große     * @return false|string  response body, false on error
1105a8d6e48SMichael Große     *
1115a8d6e48SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
1125a8d6e48SMichael Große     */
113a3b08db5SAndreas Gohr    public function dget($url, $data, $sloppy304 = false)
114a3b08db5SAndreas Gohr    {
1155a8d6e48SMichael Große        if (strpos($url, '?')) {
1165a8d6e48SMichael Große            $url .= '&';
1175a8d6e48SMichael Große        } else {
1185a8d6e48SMichael Große            $url .= '?';
1195a8d6e48SMichael Große        }
1205a8d6e48SMichael Große        $url .= $this->postEncode($data);
1215a8d6e48SMichael Große        return $this->get($url, $sloppy304);
1225a8d6e48SMichael Große    }
1235a8d6e48SMichael Große
1245a8d6e48SMichael Große    /**
1255a8d6e48SMichael Große     * Simple function to do a POST request
1265a8d6e48SMichael Große     *
1275a8d6e48SMichael Große     * Returns the resulting page or false on an error;
1285a8d6e48SMichael Große     *
1295a8d6e48SMichael Große     * @param string $url The URL to fetch
1305a8d6e48SMichael Große     * @param array $data Associative array of parameters
1315a8d6e48SMichael Große     * @return false|string  response body, false on error
1325a8d6e48SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
1335a8d6e48SMichael Große     */
134a3b08db5SAndreas Gohr    public function post($url, $data)
135a3b08db5SAndreas Gohr    {
1365a8d6e48SMichael Große        if (!$this->sendRequest($url, $data, 'POST')) return false;
1375a8d6e48SMichael Große        if ($this->status < 200 || $this->status > 206) return false;
1385a8d6e48SMichael Große        return $this->resp_body;
1395a8d6e48SMichael Große    }
1405a8d6e48SMichael Große
1415a8d6e48SMichael Große    /**
1425a8d6e48SMichael Große     * Send an HTTP request
1435a8d6e48SMichael Große     *
1445a8d6e48SMichael Große     * This method handles the whole HTTP communication. It respects set proxy settings,
1455a8d6e48SMichael Große     * builds the request headers, follows redirects and parses the response.
1465a8d6e48SMichael Große     *
1475a8d6e48SMichael Große     * Post data should be passed as associative array. When passed as string it will be
1485a8d6e48SMichael Große     * sent as is. You will need to setup your own Content-Type header then.
1495a8d6e48SMichael Große     *
1505a8d6e48SMichael Große     * @param string $url - the complete URL
1515a8d6e48SMichael Große     * @param mixed $data - the post data either as array or raw data
1525a8d6e48SMichael Große     * @param string $method - HTTP Method usually GET or POST.
1535a8d6e48SMichael Große     * @return bool - true on success
1545a8d6e48SMichael Große     *
1555a8d6e48SMichael Große     * @author Andreas Goetz <cpuidle@gmx.de>
1565a8d6e48SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
1575a8d6e48SMichael Große     */
158a3b08db5SAndreas Gohr    public function sendRequest($url, $data = '', $method = 'GET')
159a3b08db5SAndreas Gohr    {
160e8b8bf8cSElan Ruusamäe        $this->start = microtime(true);
1615a8d6e48SMichael Große        $this->error = '';
1625a8d6e48SMichael Große        $this->status = 0;
1635a8d6e48SMichael Große        $this->resp_body = '';
164a3b08db5SAndreas Gohr        $this->resp_headers = [];
1655a8d6e48SMichael Große
16667600f75STom Kunze        // save unencoded data for recursive call
16767600f75STom Kunze        $unencodedData = $data;
16867600f75STom Kunze
1695a8d6e48SMichael Große        // don't accept gzip if truncated bodies might occur
1707d34963bSAndreas Gohr        if (
1717d34963bSAndreas Gohr            $this->max_bodysize &&
1725a8d6e48SMichael Große            !$this->max_bodysize_abort &&
173d9a7912aSAndreas Gohr            isset($this->headers['Accept-encoding']) &&
1747d34963bSAndreas Gohr            $this->headers['Accept-encoding'] == 'gzip'
1757d34963bSAndreas Gohr        ) {
1765a8d6e48SMichael Große            unset($this->headers['Accept-encoding']);
1775a8d6e48SMichael Große        }
1785a8d6e48SMichael Große
1795a8d6e48SMichael Große        // parse URL into bits
1805a8d6e48SMichael Große        $uri = parse_url($url);
1815a8d6e48SMichael Große        $server = $uri['host'];
182a3b08db5SAndreas Gohr        $path = empty($uri['path']) ? '/' : $uri['path'];
183a3b08db5SAndreas Gohr        $uriPort = empty($uri['port']) ? null : $uri['port'];
1845a8d6e48SMichael Große        if (!empty($uri['query'])) $path .= '?' . $uri['query'];
1855a8d6e48SMichael Große        if (isset($uri['user'])) $this->user = $uri['user'];
1865a8d6e48SMichael Große        if (isset($uri['pass'])) $this->pass = $uri['pass'];
1875a8d6e48SMichael Große
1885a8d6e48SMichael Große        // proxy setup
189980f9f38SAndreas Gohr        if ($this->useProxyForUrl($url)) {
1905a8d6e48SMichael Große            $request_url = $url;
1915a8d6e48SMichael Große            $server = $this->proxy_host;
1925a8d6e48SMichael Große            $port = $this->proxy_port;
1935a8d6e48SMichael Große            if (empty($port)) $port = 8080;
1945a8d6e48SMichael Große            $use_tls = $this->proxy_ssl;
1955a8d6e48SMichael Große        } else {
1965a8d6e48SMichael Große            $request_url = $path;
19766b64c2aSDamien Regad            $port = $uriPort ?: ($uri['scheme'] == 'https' ? 443 : 80);
1985a8d6e48SMichael Große            $use_tls = ($uri['scheme'] == 'https');
1995a8d6e48SMichael Große        }
2005a8d6e48SMichael Große
2015a8d6e48SMichael Große        // add SSL stream prefix if needed - needs SSL support in PHP
2025a8d6e48SMichael Große        if ($use_tls) {
2035a8d6e48SMichael Große            if (!in_array('ssl', stream_get_transports())) {
2045a8d6e48SMichael Große                $this->status = -200;
2055a8d6e48SMichael Große                $this->error = 'This PHP version does not support SSL - cannot connect to server';
2065a8d6e48SMichael Große            }
2075a8d6e48SMichael Große            $server = 'ssl://' . $server;
2085a8d6e48SMichael Große        }
2095a8d6e48SMichael Große
2105a8d6e48SMichael Große        // prepare headers
2115a8d6e48SMichael Große        $headers = $this->headers;
212056bf31fSDamien Regad        $headers['Host'] = $uri['host']
213056bf31fSDamien Regad            . ($uriPort ? ':' . $uriPort : '');
2145a8d6e48SMichael Große        $headers['User-Agent'] = $this->agent;
2155a8d6e48SMichael Große        $headers['Referer'] = $this->referer;
2165a8d6e48SMichael Große
2175a8d6e48SMichael Große        if ($method == 'POST') {
2185a8d6e48SMichael Große            if (is_array($data)) {
2195a8d6e48SMichael Große                if (empty($headers['Content-Type'])) {
2205a8d6e48SMichael Große                    $headers['Content-Type'] = null;
2215a8d6e48SMichael Große                }
222a3b08db5SAndreas Gohr                if ($headers['Content-Type'] == 'multipart/form-data') {
2235a8d6e48SMichael Große                    $headers['Content-Type'] = 'multipart/form-data; boundary=' . $this->boundary;
2245a8d6e48SMichael Große                    $data = $this->postMultipartEncode($data);
225a3b08db5SAndreas Gohr                } else {
2265a8d6e48SMichael Große                    $headers['Content-Type'] = 'application/x-www-form-urlencoded';
2275a8d6e48SMichael Große                    $data = $this->postEncode($data);
2285a8d6e48SMichael Große                }
2295a8d6e48SMichael Große            }
2305a8d6e48SMichael Große        } elseif ($method == 'GET') {
2315a8d6e48SMichael Große            $data = ''; //no data allowed on GET requests
2325a8d6e48SMichael Große        }
2335a8d6e48SMichael Große
2345a8d6e48SMichael Große        $contentlength = strlen($data);
2355a8d6e48SMichael Große        if ($contentlength) {
2365a8d6e48SMichael Große            $headers['Content-Length'] = $contentlength;
2375a8d6e48SMichael Große        }
2385a8d6e48SMichael Große
2395a8d6e48SMichael Große        if ($this->user) {
2405a8d6e48SMichael Große            $headers['Authorization'] = 'Basic ' . base64_encode($this->user . ':' . $this->pass);
2415a8d6e48SMichael Große        }
2425a8d6e48SMichael Große        if ($this->proxy_user) {
2435a8d6e48SMichael Große            $headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass);
2445a8d6e48SMichael Große        }
2455a8d6e48SMichael Große
2465a8d6e48SMichael Große        // already connected?
2475a8d6e48SMichael Große        $connectionId = $this->uniqueConnectionId($server, $port);
2485a8d6e48SMichael Große        $this->debug('connection pool', self::$connections);
2495a8d6e48SMichael Große        $socket = null;
2505a8d6e48SMichael Große        if (isset(self::$connections[$connectionId])) {
2515a8d6e48SMichael Große            $this->debug('reusing connection', $connectionId);
2525a8d6e48SMichael Große            $socket = self::$connections[$connectionId];
2535a8d6e48SMichael Große        }
2545a8d6e48SMichael Große        if (is_null($socket) || feof($socket)) {
2555a8d6e48SMichael Große            $this->debug('opening connection', $connectionId);
2565a8d6e48SMichael Große            // open socket
2575a8d6e48SMichael Große            $socket = @fsockopen($server, $port, $errno, $errstr, $this->timeout);
2585a8d6e48SMichael Große            if (!$socket) {
2595a8d6e48SMichael Große                $this->status = -100;
2605a8d6e48SMichael Große                $this->error = "Could not connect to $server:$port\n$errstr ($errno)";
2615a8d6e48SMichael Große                return false;
2625a8d6e48SMichael Große            }
2635a8d6e48SMichael Große
2648a10b6f0SElan Ruusamäe            // try to establish a CONNECT tunnel for SSL
2655a8d6e48SMichael Große            try {
2665a8d6e48SMichael Große                if ($this->ssltunnel($socket, $request_url)) {
2675a8d6e48SMichael Große                    // no keep alive for tunnels
2685a8d6e48SMichael Große                    $this->keep_alive = false;
2695a8d6e48SMichael Große                    // tunnel is authed already
2705a8d6e48SMichael Große                    if (isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']);
2715a8d6e48SMichael Große                }
2725a8d6e48SMichael Große            } catch (HTTPClientException $e) {
2735a8d6e48SMichael Große                $this->status = $e->getCode();
2745a8d6e48SMichael Große                $this->error = $e->getMessage();
2755a8d6e48SMichael Große                fclose($socket);
2765a8d6e48SMichael Große                return false;
2775a8d6e48SMichael Große            }
2785a8d6e48SMichael Große
2795a8d6e48SMichael Große            // keep alive?
2805a8d6e48SMichael Große            if ($this->keep_alive) {
2815a8d6e48SMichael Große                self::$connections[$connectionId] = $socket;
2825a8d6e48SMichael Große            } else {
2835a8d6e48SMichael Große                unset(self::$connections[$connectionId]);
2845a8d6e48SMichael Große            }
2855a8d6e48SMichael Große        }
2865a8d6e48SMichael Große
287980f9f38SAndreas Gohr        if ($this->keep_alive && !$this->useProxyForUrl($request_url)) {
2885a8d6e48SMichael Große            // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
2895a8d6e48SMichael Große            // connection token to a proxy server. We still do keep the connection the
2905a8d6e48SMichael Große            // proxy alive (well except for CONNECT tunnels)
2915a8d6e48SMichael Große            $headers['Connection'] = 'Keep-Alive';
2925a8d6e48SMichael Große        } else {
2935a8d6e48SMichael Große            $headers['Connection'] = 'Close';
2945a8d6e48SMichael Große        }
2955a8d6e48SMichael Große
2965a8d6e48SMichael Große        try {
2975a8d6e48SMichael Große            //set non-blocking
2985a8d6e48SMichael Große            stream_set_blocking($socket, 0);
2995a8d6e48SMichael Große
3005a8d6e48SMichael Große            // build request
3015a8d6e48SMichael Große            $request = "$method $request_url HTTP/" . $this->http . HTTP_NL;
3025a8d6e48SMichael Große            $request .= $this->buildHeaders($headers);
3035a8d6e48SMichael Große            $request .= $this->getCookies();
3045a8d6e48SMichael Große            $request .= HTTP_NL;
3055a8d6e48SMichael Große            $request .= $data;
3065a8d6e48SMichael Große
3075a8d6e48SMichael Große            $this->debug('request', $request);
3085a8d6e48SMichael Große            $this->sendData($socket, $request, 'request');
3095a8d6e48SMichael Große
3105a8d6e48SMichael Große            // read headers from socket
3115a8d6e48SMichael Große            $r_headers = '';
3125a8d6e48SMichael Große            do {
3135a8d6e48SMichael Große                $r_line = $this->readLine($socket, 'headers');
3145a8d6e48SMichael Große                $r_headers .= $r_line;
3155a8d6e48SMichael Große            } while ($r_line != "\r\n" && $r_line != "\n");
3165a8d6e48SMichael Große
3175a8d6e48SMichael Große            $this->debug('response headers', $r_headers);
3185a8d6e48SMichael Große
3195a8d6e48SMichael Große            // check if expected body size exceeds allowance
3205a8d6e48SMichael Große            if ($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i', $r_headers, $match)) {
3215a8d6e48SMichael Große                if ($match[1] > $this->max_bodysize) {
3225a8d6e48SMichael Große                    if ($this->max_bodysize_abort)
3235a8d6e48SMichael Große                        throw new HTTPClientException('Reported content length exceeds allowed response size');
324177d6836SAndreas Gohr                    else $this->error = 'Reported content length exceeds allowed response size';
3255a8d6e48SMichael Große                }
3265a8d6e48SMichael Große            }
3275a8d6e48SMichael Große
3285a8d6e48SMichael Große            // get Status
32903c2c428Sfiwswe            if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/s', $r_headers, $m))
3305a8d6e48SMichael Große                throw new HTTPClientException('Server returned bad answer ' . $r_headers);
3315a8d6e48SMichael Große
3325a8d6e48SMichael Große            $this->status = $m[2];
3335a8d6e48SMichael Große
3345a8d6e48SMichael Große            // handle headers and cookies
3355a8d6e48SMichael Große            $this->resp_headers = $this->parseHeaders($r_headers);
3365a8d6e48SMichael Große            if (isset($this->resp_headers['set-cookie'])) {
3375a8d6e48SMichael Große                foreach ((array)$this->resp_headers['set-cookie'] as $cookie) {
338a3b08db5SAndreas Gohr                    [$cookie] = sexplode(';', $cookie, 2, '');
339a3b08db5SAndreas Gohr                    [$key, $val] = sexplode('=', $cookie, 2, '');
3405a8d6e48SMichael Große                    $key = trim($key);
3415a8d6e48SMichael Große                    if ($val == 'deleted') {
3425a8d6e48SMichael Große                        if (isset($this->cookies[$key])) {
3435a8d6e48SMichael Große                            unset($this->cookies[$key]);
3445a8d6e48SMichael Große                        }
3455a8d6e48SMichael Große                    } elseif ($key) {
3465a8d6e48SMichael Große                        $this->cookies[$key] = $val;
3475a8d6e48SMichael Große                    }
3485a8d6e48SMichael Große                }
3495a8d6e48SMichael Große            }
3505a8d6e48SMichael Große
3515a8d6e48SMichael Große            $this->debug('Object headers', $this->resp_headers);
3525a8d6e48SMichael Große
3535a8d6e48SMichael Große            // check server status code to follow redirect
35467600f75STom Kunze            if (in_array($this->status, [301, 302, 303, 307, 308])) {
3555a8d6e48SMichael Große                if (empty($this->resp_headers['location'])) {
3565a8d6e48SMichael Große                    throw new HTTPClientException('Redirect but no Location Header found');
3575a8d6e48SMichael Große                } elseif ($this->redirect_count == $this->max_redirect) {
3585a8d6e48SMichael Große                    throw new HTTPClientException('Maximum number of redirects exceeded');
3595a8d6e48SMichael Große                } else {
3605a8d6e48SMichael Große                    // close the connection because we don't handle content retrieval here
3615a8d6e48SMichael Große                    // that's the easiest way to clean up the connection
3625a8d6e48SMichael Große                    fclose($socket);
3635a8d6e48SMichael Große                    unset(self::$connections[$connectionId]);
3645a8d6e48SMichael Große
3655a8d6e48SMichael Große                    $this->redirect_count++;
3665a8d6e48SMichael Große                    $this->referer = $url;
3675a8d6e48SMichael Große                    // handle non-RFC-compliant relative redirects
3685a8d6e48SMichael Große                    if (!preg_match('/^http/i', $this->resp_headers['location'])) {
3695a8d6e48SMichael Große                        if ($this->resp_headers['location'][0] != '/') {
370056bf31fSDamien Regad                            $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort .
371056bf31fSDamien Regad                                dirname($path) . '/' . $this->resp_headers['location'];
3725a8d6e48SMichael Große                        } else {
373056bf31fSDamien Regad                            $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort .
3745a8d6e48SMichael Große                                $this->resp_headers['location'];
3755a8d6e48SMichael Große                        }
3765a8d6e48SMichael Große                    }
37767600f75STom Kunze                    if ($this->status == 307 || $this->status == 308) {
37867600f75STom Kunze                        // perform redirected request, same method as before (required by RFC)
37967600f75STom Kunze                        return $this->sendRequest($this->resp_headers['location'], $unencodedData, $method);
38067600f75STom Kunze                    } else {
3815a8d6e48SMichael Große                        // perform redirected request, always via GET (required by RFC)
382a3b08db5SAndreas Gohr                        return $this->sendRequest($this->resp_headers['location'], [], 'GET');
3835a8d6e48SMichael Große                    }
3845a8d6e48SMichael Große                }
38567600f75STom Kunze            }
3865a8d6e48SMichael Große
3875a8d6e48SMichael Große            // check if headers are as expected
3885a8d6e48SMichael Große            if ($this->header_regexp && !preg_match($this->header_regexp, $r_headers))
3895a8d6e48SMichael Große                throw new HTTPClientException('The received headers did not match the given regexp');
3905a8d6e48SMichael Große
3915a8d6e48SMichael Große            //read body (with chunked encoding if needed)
3925a8d6e48SMichael Große            $r_body = '';
3935a8d6e48SMichael Große            if (
3945a8d6e48SMichael Große                (
3955a8d6e48SMichael Große                    isset($this->resp_headers['transfer-encoding']) &&
3965a8d6e48SMichael Große                    $this->resp_headers['transfer-encoding'] == 'chunked'
3975a8d6e48SMichael Große                ) || (
3985a8d6e48SMichael Große                    isset($this->resp_headers['transfer-coding']) &&
3995a8d6e48SMichael Große                    $this->resp_headers['transfer-coding'] == 'chunked'
4005a8d6e48SMichael Große                )
4015a8d6e48SMichael Große            ) {
4025a8d6e48SMichael Große                $abort = false;
4035a8d6e48SMichael Große                do {
4045a8d6e48SMichael Große                    $chunk_size = '';
4055a8d6e48SMichael Große                    while (preg_match('/^[a-zA-Z0-9]?$/', $byte = $this->readData($socket, 1, 'chunk'))) {
4065a8d6e48SMichael Große                        // read chunksize until \r
4075a8d6e48SMichael Große                        $chunk_size .= $byte;
4085a8d6e48SMichael Große                        if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks
4095a8d6e48SMichael Große                            throw new HTTPClientException('Allowed response size exceeded');
4105a8d6e48SMichael Große                    }
4115a8d6e48SMichael Große                    $this->readLine($socket, 'chunk');     // readtrailing \n
4125a8d6e48SMichael Große                    $chunk_size = hexdec($chunk_size);
4135a8d6e48SMichael Große
4145a8d6e48SMichael Große                    if ($this->max_bodysize && $chunk_size + strlen($r_body) > $this->max_bodysize) {
4155a8d6e48SMichael Große                        if ($this->max_bodysize_abort)
4165a8d6e48SMichael Große                            throw new HTTPClientException('Allowed response size exceeded');
4175a8d6e48SMichael Große                        $this->error = 'Allowed response size exceeded';
4185a8d6e48SMichael Große                        $chunk_size = $this->max_bodysize - strlen($r_body);
4195a8d6e48SMichael Große                        $abort = true;
4205a8d6e48SMichael Große                    }
4215a8d6e48SMichael Große
4225a8d6e48SMichael Große                    if ($chunk_size > 0) {
4235a8d6e48SMichael Große                        $r_body .= $this->readData($socket, $chunk_size, 'chunk');
4245a8d6e48SMichael Große                        $this->readData($socket, 2, 'chunk'); // read trailing \r\n
4255a8d6e48SMichael Große                    }
4265a8d6e48SMichael Große                } while ($chunk_size && !$abort);
42751bc2534SAndreas Gohr            } elseif (
42851bc2534SAndreas Gohr                isset($this->resp_headers['content-length']) &&
42951bc2534SAndreas Gohr                !isset($this->resp_headers['transfer-encoding'])
43051bc2534SAndreas Gohr            ) {
4315a8d6e48SMichael Große                /* RFC 2616
4325a8d6e48SMichael Große                 * If a message is received with both a Transfer-Encoding header field and a Content-Length
4335a8d6e48SMichael Große                 * header field, the latter MUST be ignored.
4345a8d6e48SMichael Große                 */
4355a8d6e48SMichael Große
4365a8d6e48SMichael Große                // read up to the content-length or max_bodysize
4375a8d6e48SMichael Große                // for keep alive we need to read the whole message to clean up the socket for the next read
4385a8d6e48SMichael Große                if (
4395a8d6e48SMichael Große                    !$this->keep_alive &&
4405a8d6e48SMichael Große                    $this->max_bodysize &&
4415a8d6e48SMichael Große                    $this->max_bodysize < $this->resp_headers['content-length']
4425a8d6e48SMichael Große                ) {
4435a8d6e48SMichael Große                    $length = $this->max_bodysize + 1;
4445a8d6e48SMichael Große                } else {
4455a8d6e48SMichael Große                    $length = $this->resp_headers['content-length'];
4465a8d6e48SMichael Große                }
4475a8d6e48SMichael Große
4485a8d6e48SMichael Große                $r_body = $this->readData($socket, $length, 'response (content-length limited)', true);
4495a8d6e48SMichael Große            } elseif (!isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive) {
4505a8d6e48SMichael Große                $r_body = $this->readData($socket, $this->max_bodysize + 1, 'response (content-length limited)', true);
4515a8d6e48SMichael Große            } elseif ((int)$this->status === 204) {
4525a8d6e48SMichael Große                // request has no content
4535a8d6e48SMichael Große            } else {
4545a8d6e48SMichael Große                // read entire socket
4555a8d6e48SMichael Große                while (!feof($socket)) {
4565a8d6e48SMichael Große                    $r_body .= $this->readData($socket, 4096, 'response (unlimited)', true);
4575a8d6e48SMichael Große                }
4585a8d6e48SMichael Große            }
4595a8d6e48SMichael Große
4605a8d6e48SMichael Große            // recheck body size, we might have read max_bodysize+1 or even the whole body, so we abort late here
4615a8d6e48SMichael Große            if ($this->max_bodysize) {
4625a8d6e48SMichael Große                if (strlen($r_body) > $this->max_bodysize) {
4635a8d6e48SMichael Große                    if ($this->max_bodysize_abort) {
4645a8d6e48SMichael Große                        throw new HTTPClientException('Allowed response size exceeded');
4655a8d6e48SMichael Große                    } else {
4665a8d6e48SMichael Große                        $this->error = 'Allowed response size exceeded';
4675a8d6e48SMichael Große                    }
4685a8d6e48SMichael Große                }
4695a8d6e48SMichael Große            }
4705a8d6e48SMichael Große        } catch (HTTPClientException $err) {
4715a8d6e48SMichael Große            $this->error = $err->getMessage();
4725a8d6e48SMichael Große            if ($err->getCode())
4735a8d6e48SMichael Große                $this->status = $err->getCode();
4745a8d6e48SMichael Große            unset(self::$connections[$connectionId]);
4755a8d6e48SMichael Große            fclose($socket);
4765a8d6e48SMichael Große            return false;
4775a8d6e48SMichael Große        }
4785a8d6e48SMichael Große
4797d34963bSAndreas Gohr        if (
4807d34963bSAndreas Gohr            !$this->keep_alive ||
4817d34963bSAndreas Gohr            (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')
4827d34963bSAndreas Gohr        ) {
4835a8d6e48SMichael Große            // close socket
4845a8d6e48SMichael Große            fclose($socket);
4855a8d6e48SMichael Große            unset(self::$connections[$connectionId]);
4865a8d6e48SMichael Große        }
4875a8d6e48SMichael Große
4885a8d6e48SMichael Große        // decode gzip if needed
4897d34963bSAndreas Gohr        if (
4907d34963bSAndreas Gohr            isset($this->resp_headers['content-encoding']) &&
4915a8d6e48SMichael Große            $this->resp_headers['content-encoding'] == 'gzip' &&
492*6c16a3a9Sfiwswe            strlen($r_body) > 10 && str_starts_with($r_body, "\x1f\x8b\x08")
4937d34963bSAndreas Gohr        ) {
4945a8d6e48SMichael Große            $this->resp_body = @gzinflate(substr($r_body, 10));
4955a8d6e48SMichael Große            if ($this->resp_body === false) {
4965a8d6e48SMichael Große                $this->error = 'Failed to decompress gzip encoded content';
4975a8d6e48SMichael Große                $this->resp_body = $r_body;
4985a8d6e48SMichael Große            }
4995a8d6e48SMichael Große        } else {
5005a8d6e48SMichael Große            $this->resp_body = $r_body;
5015a8d6e48SMichael Große        }
5025a8d6e48SMichael Große
5035a8d6e48SMichael Große        $this->debug('response body', $this->resp_body);
5045a8d6e48SMichael Große        $this->redirect_count = 0;
5055a8d6e48SMichael Große        return true;
5065a8d6e48SMichael Große    }
5075a8d6e48SMichael Große
5085a8d6e48SMichael Große    /**
5095a8d6e48SMichael Große     * Tries to establish a CONNECT tunnel via Proxy
5105a8d6e48SMichael Große     *
5115a8d6e48SMichael Große     * Protocol, Servername and Port will be stripped from the request URL when a successful CONNECT happened
5125a8d6e48SMichael Große     *
5135a8d6e48SMichael Große     * @param resource &$socket
5145a8d6e48SMichael Große     * @param string   &$requesturl
5155a8d6e48SMichael Große     * @return bool true if a tunnel was established
516a3b08db5SAndreas Gohr     * @throws HTTPClientException when a tunnel is needed but could not be established
5175a8d6e48SMichael Große     */
518a3b08db5SAndreas Gohr    protected function ssltunnel(&$socket, &$requesturl)
519a3b08db5SAndreas Gohr    {
520980f9f38SAndreas Gohr        if (!$this->useProxyForUrl($requesturl)) return false;
5215a8d6e48SMichael Große        $requestinfo = parse_url($requesturl);
5225a8d6e48SMichael Große        if ($requestinfo['scheme'] != 'https') return false;
523056bf31fSDamien Regad        if (empty($requestinfo['port'])) $requestinfo['port'] = 443;
5245a8d6e48SMichael Große
5255a8d6e48SMichael Große        // build request
5265a8d6e48SMichael Große        $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0" . HTTP_NL;
5275a8d6e48SMichael Große        $request .= "Host: {$requestinfo['host']}" . HTTP_NL;
5285a8d6e48SMichael Große        if ($this->proxy_user) {
52951bc2534SAndreas Gohr            $request .= 'Proxy-Authorization: Basic ' .
53051bc2534SAndreas Gohr                base64_encode($this->proxy_user . ':' . $this->proxy_pass) . HTTP_NL;
5315a8d6e48SMichael Große        }
5325a8d6e48SMichael Große        $request .= HTTP_NL;
5335a8d6e48SMichael Große
5345a8d6e48SMichael Große        $this->debug('SSL Tunnel CONNECT', $request);
5355a8d6e48SMichael Große        $this->sendData($socket, $request, 'SSL Tunnel CONNECT');
5365a8d6e48SMichael Große
5375a8d6e48SMichael Große        // read headers from socket
5385a8d6e48SMichael Große        $r_headers = '';
5395a8d6e48SMichael Große        do {
5405a8d6e48SMichael Große            $r_line = $this->readLine($socket, 'headers');
5415a8d6e48SMichael Große            $r_headers .= $r_line;
5425a8d6e48SMichael Große        } while ($r_line != "\r\n" && $r_line != "\n");
5435a8d6e48SMichael Große
5445a8d6e48SMichael Große        $this->debug('SSL Tunnel Response', $r_headers);
5455a8d6e48SMichael Große        if (preg_match('/^HTTP\/1\.[01] 200/i', $r_headers)) {
5465a8d6e48SMichael Große            // set correct peer name for verification (enabled since PHP 5.6)
5475a8d6e48SMichael Große            stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']);
5485a8d6e48SMichael Große
5495a8d6e48SMichael Große            // SSLv3 is broken, use only TLS connections.
5505a8d6e48SMichael Große            // @link https://bugs.php.net/69195
5515a8d6e48SMichael Große            if (PHP_VERSION_ID >= 50600 && PHP_VERSION_ID <= 50606) {
5525a8d6e48SMichael Große                $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_CLIENT;
5535a8d6e48SMichael Große            } else {
5545a8d6e48SMichael Große                // actually means neither SSLv2 nor SSLv3
5555a8d6e48SMichael Große                $cryptoMethod = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
5565a8d6e48SMichael Große            }
5575a8d6e48SMichael Große
5585a8d6e48SMichael Große            if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) {
559605810eeSAndreas Gohr                $requesturl = ($requestinfo['path'] ?? '/') .
560a3b08db5SAndreas Gohr                    (empty($requestinfo['query']) ? '' : '?' . $requestinfo['query']);
5615a8d6e48SMichael Große                return true;
5625a8d6e48SMichael Große            }
5635a8d6e48SMichael Große
5645a8d6e48SMichael Große            throw new HTTPClientException(
565dccd6b2bSAndreas Gohr                'Failed to set up crypto for secure connection to ' . $requestinfo['host'],
566dccd6b2bSAndreas Gohr                -151
5675a8d6e48SMichael Große            );
5685a8d6e48SMichael Große        }
5695a8d6e48SMichael Große
5705a8d6e48SMichael Große        throw new HTTPClientException('Failed to establish secure proxy connection', -150);
5715a8d6e48SMichael Große    }
5725a8d6e48SMichael Große
5735a8d6e48SMichael Große    /**
5745a8d6e48SMichael Große     * Safely write data to a socket
5755a8d6e48SMichael Große     *
5765a8d6e48SMichael Große     * @param resource $socket An open socket handle
5775a8d6e48SMichael Große     * @param string $data The data to write
5785a8d6e48SMichael Große     * @param string $message Description of what is being read
5795a8d6e48SMichael Große     * @throws HTTPClientException
5805a8d6e48SMichael Große     *
5815a8d6e48SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
5825a8d6e48SMichael Große     */
583a3b08db5SAndreas Gohr    protected function sendData($socket, $data, $message)
584a3b08db5SAndreas Gohr    {
5855a8d6e48SMichael Große        // send request
5865a8d6e48SMichael Große        $towrite = strlen($data);
5875a8d6e48SMichael Große        $written = 0;
5885a8d6e48SMichael Große        while ($written < $towrite) {
5895a8d6e48SMichael Große            // check timeout
590e8b8bf8cSElan Ruusamäe            $time_used = microtime(true) - $this->start;
5915a8d6e48SMichael Große            if ($time_used > $this->timeout)
5925a8d6e48SMichael Große                throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)', $message, $time_used), -100);
5935a8d6e48SMichael Große            if (feof($socket))
5945a8d6e48SMichael Große                throw new HTTPClientException("Socket disconnected while writing $message");
5955a8d6e48SMichael Große
5965a8d6e48SMichael Große            // select parameters
5975a8d6e48SMichael Große            $sel_r = null;
598a3b08db5SAndreas Gohr            $sel_w = [$socket];
5995a8d6e48SMichael Große            $sel_e = null;
6005a8d6e48SMichael Große            // wait for stream ready or timeout (1sec)
6015a8d6e48SMichael Große            if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) {
6025a8d6e48SMichael Große                usleep(1000);
6035a8d6e48SMichael Große                continue;
6045a8d6e48SMichael Große            }
6055a8d6e48SMichael Große
6065a8d6e48SMichael Große            // write to stream
6075a8d6e48SMichael Große            $nbytes = fwrite($socket, substr($data, $written, 4096));
6085a8d6e48SMichael Große            if ($nbytes === false)
6095a8d6e48SMichael Große                throw new HTTPClientException("Failed writing to socket while sending $message", -100);
6105a8d6e48SMichael Große            $written += $nbytes;
6115a8d6e48SMichael Große        }
6125a8d6e48SMichael Große    }
6135a8d6e48SMichael Große
6145a8d6e48SMichael Große    /**
6155a8d6e48SMichael Große     * Safely read data from a socket
6165a8d6e48SMichael Große     *
6175a8d6e48SMichael Große     * Reads up to a given number of bytes or throws an exception if the
6185a8d6e48SMichael Große     * response times out or ends prematurely.
6195a8d6e48SMichael Große     *
6205a8d6e48SMichael Große     * @param resource $socket An open socket handle in non-blocking mode
6215a8d6e48SMichael Große     * @param int $nbytes Number of bytes to read
6225a8d6e48SMichael Große     * @param string $message Description of what is being read
6235a8d6e48SMichael Große     * @param bool $ignore_eof End-of-file is not an error if this is set
6245a8d6e48SMichael Große     * @return string
6255a8d6e48SMichael Große     *
626a3b08db5SAndreas Gohr     * @throws HTTPClientException
6275a8d6e48SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
6285a8d6e48SMichael Große     */
629a3b08db5SAndreas Gohr    protected function readData($socket, $nbytes, $message, $ignore_eof = false)
630a3b08db5SAndreas Gohr    {
6315a8d6e48SMichael Große        $r_data = '';
6325a8d6e48SMichael Große        // Does not return immediately so timeout and eof can be checked
6335a8d6e48SMichael Große        if ($nbytes < 0) $nbytes = 0;
6345a8d6e48SMichael Große        $to_read = $nbytes;
6355a8d6e48SMichael Große        do {
636e8b8bf8cSElan Ruusamäe            $time_used = microtime(true) - $this->start;
6375a8d6e48SMichael Große            if ($time_used > $this->timeout)
6385a8d6e48SMichael Große                throw new HTTPClientException(
639dccd6b2bSAndreas Gohr                    sprintf(
640dccd6b2bSAndreas Gohr                        'Timeout while reading %s after %d bytes (%.3fs)',
641dccd6b2bSAndreas Gohr                        $message,
642dccd6b2bSAndreas Gohr                        strlen($r_data),
643dccd6b2bSAndreas Gohr                        $time_used
644dccd6b2bSAndreas Gohr                    ),
645dccd6b2bSAndreas Gohr                    -100
646dccd6b2bSAndreas Gohr                );
6475a8d6e48SMichael Große            if (feof($socket)) {
6485a8d6e48SMichael Große                if (!$ignore_eof)
6495a8d6e48SMichael Große                    throw new HTTPClientException("Premature End of File (socket) while reading $message");
6505a8d6e48SMichael Große                break;
6515a8d6e48SMichael Große            }
6525a8d6e48SMichael Große
6535a8d6e48SMichael Große            if ($to_read > 0) {
6545a8d6e48SMichael Große                // select parameters
655a3b08db5SAndreas Gohr                $sel_r = [$socket];
6565a8d6e48SMichael Große                $sel_w = null;
6575a8d6e48SMichael Große                $sel_e = null;
6585a8d6e48SMichael Große                // wait for stream ready or timeout (1sec)
6595a8d6e48SMichael Große                if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) {
6605a8d6e48SMichael Große                    usleep(1000);
6615a8d6e48SMichael Große                    continue;
6625a8d6e48SMichael Große                }
6635a8d6e48SMichael Große
6645a8d6e48SMichael Große                $bytes = fread($socket, $to_read);
6655a8d6e48SMichael Große                if ($bytes === false)
6665a8d6e48SMichael Große                    throw new HTTPClientException("Failed reading from socket while reading $message", -100);
6675a8d6e48SMichael Große                $r_data .= $bytes;
6685a8d6e48SMichael Große                $to_read -= strlen($bytes);
6695a8d6e48SMichael Große            }
6705a8d6e48SMichael Große        } while ($to_read > 0 && strlen($r_data) < $nbytes);
6715a8d6e48SMichael Große        return $r_data;
6725a8d6e48SMichael Große    }
6735a8d6e48SMichael Große
6745a8d6e48SMichael Große    /**
6755a8d6e48SMichael Große     * Safely read a \n-terminated line from a socket
6765a8d6e48SMichael Große     *
6775a8d6e48SMichael Große     * Always returns a complete line, including the terminating \n.
6785a8d6e48SMichael Große     *
6795a8d6e48SMichael Große     * @param resource $socket An open socket handle in non-blocking mode
6805a8d6e48SMichael Große     * @param string $message Description of what is being read
6815a8d6e48SMichael Große     * @return string
6825a8d6e48SMichael Große     *
683a3b08db5SAndreas Gohr     * @throws HTTPClientException
6845a8d6e48SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
6855a8d6e48SMichael Große     */
686a3b08db5SAndreas Gohr    protected function readLine($socket, $message)
687a3b08db5SAndreas Gohr    {
6885a8d6e48SMichael Große        $r_data = '';
6895a8d6e48SMichael Große        do {
690e8b8bf8cSElan Ruusamäe            $time_used = microtime(true) - $this->start;
6915a8d6e48SMichael Große            if ($time_used > $this->timeout)
6925a8d6e48SMichael Große                throw new HTTPClientException(
6935a8d6e48SMichael Große                    sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data),
694dccd6b2bSAndreas Gohr                    -100
695dccd6b2bSAndreas Gohr                );
6965a8d6e48SMichael Große            if (feof($socket))
6975a8d6e48SMichael Große                throw new HTTPClientException("Premature End of File (socket) while reading $message");
6985a8d6e48SMichael Große
6995a8d6e48SMichael Große            // select parameters
700a3b08db5SAndreas Gohr            $sel_r = [$socket];
7015a8d6e48SMichael Große            $sel_w = null;
7025a8d6e48SMichael Große            $sel_e = null;
7035a8d6e48SMichael Große            // wait for stream ready or timeout (1sec)
7045a8d6e48SMichael Große            if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) {
7055a8d6e48SMichael Große                usleep(1000);
7065a8d6e48SMichael Große                continue;
7075a8d6e48SMichael Große            }
7085a8d6e48SMichael Große
7095a8d6e48SMichael Große            $r_data = fgets($socket, 1024);
7105a8d6e48SMichael Große        } while (!preg_match('/\n$/', $r_data));
7115a8d6e48SMichael Große        return $r_data;
7125a8d6e48SMichael Große    }
7135a8d6e48SMichael Große
7145a8d6e48SMichael Große    /**
7155a8d6e48SMichael Große     * print debug info
7165a8d6e48SMichael Große     *
7175a8d6e48SMichael Große     * Uses _debug_text or _debug_html depending on the SAPI name
7185a8d6e48SMichael Große     *
7195a8d6e48SMichael Große     * @param string $info
7205a8d6e48SMichael Große     * @param mixed $var
721a3b08db5SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
722a3b08db5SAndreas Gohr     *
7235a8d6e48SMichael Große     */
724a3b08db5SAndreas Gohr    protected function debug($info, $var = null)
725a3b08db5SAndreas Gohr    {
7265a8d6e48SMichael Große        if (!$this->debug) return;
727a3b08db5SAndreas Gohr        if (PHP_SAPI == 'cli') {
7285a8d6e48SMichael Große            $this->debugText($info, $var);
7295a8d6e48SMichael Große        } else {
7305a8d6e48SMichael Große            $this->debugHtml($info, $var);
7315a8d6e48SMichael Große        }
7325a8d6e48SMichael Große    }
7335a8d6e48SMichael Große
7345a8d6e48SMichael Große    /**
7355a8d6e48SMichael Große     * print debug info as HTML
7365a8d6e48SMichael Große     *
7375a8d6e48SMichael Große     * @param string $info
7385a8d6e48SMichael Große     * @param mixed $var
7395a8d6e48SMichael Große     */
740a3b08db5SAndreas Gohr    protected function debugHtml($info, $var = null)
741a3b08db5SAndreas Gohr    {
74226dfc232SAndreas Gohr        echo '<b>' . $info . '</b> ' . (microtime(true) - $this->start) . 's<br />';
7435a8d6e48SMichael Große        if (!is_null($var)) {
7445a8d6e48SMichael Große            ob_start();
7455a8d6e48SMichael Große            print_r($var);
7465a8d6e48SMichael Große            $content = htmlspecialchars(ob_get_contents());
7475a8d6e48SMichael Große            ob_end_clean();
74826dfc232SAndreas Gohr            echo '<pre>' . $content . '</pre>';
7495a8d6e48SMichael Große        }
7505a8d6e48SMichael Große    }
7515a8d6e48SMichael Große
7525a8d6e48SMichael Große    /**
7535a8d6e48SMichael Große     * prints debug info as plain text
7545a8d6e48SMichael Große     *
7555a8d6e48SMichael Große     * @param string $info
7565a8d6e48SMichael Große     * @param mixed $var
7575a8d6e48SMichael Große     */
758a3b08db5SAndreas Gohr    protected function debugText($info, $var = null)
759a3b08db5SAndreas Gohr    {
76026dfc232SAndreas Gohr        echo '*' . $info . '* ' . (microtime(true) - $this->start) . "s\n";
7615a8d6e48SMichael Große        if (!is_null($var)) print_r($var);
76226dfc232SAndreas Gohr        echo "\n-----------------------------------------------\n";
7635a8d6e48SMichael Große    }
7645a8d6e48SMichael Große
7655a8d6e48SMichael Große    /**
7665a8d6e48SMichael Große     * convert given header string to Header array
7675a8d6e48SMichael Große     *
7685a8d6e48SMichael Große     * All Keys are lowercased.
7695a8d6e48SMichael Große     *
7705a8d6e48SMichael Große     * @param string $string
7715a8d6e48SMichael Große     * @return array
772a3b08db5SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
773a3b08db5SAndreas Gohr     *
7745a8d6e48SMichael Große     */
775a3b08db5SAndreas Gohr    protected function parseHeaders($string)
776a3b08db5SAndreas Gohr    {
777a3b08db5SAndreas Gohr        $headers = [];
7785a8d6e48SMichael Große        $lines = explode("\n", $string);
7795a8d6e48SMichael Große        array_shift($lines); //skip first line (status)
7805a8d6e48SMichael Große        foreach ($lines as $line) {
781a3b08db5SAndreas Gohr            [$key, $val] = sexplode(':', $line, 2, '');
7825a8d6e48SMichael Große            $key = trim($key);
783ec34bb30SAndreas Gohr            $val = trim($val);
7845a8d6e48SMichael Große            $key = strtolower($key);
7855a8d6e48SMichael Große            if (!$key) continue;
7865a8d6e48SMichael Große            if (isset($headers[$key])) {
7875a8d6e48SMichael Große                if (is_array($headers[$key])) {
7885a8d6e48SMichael Große                    $headers[$key][] = $val;
7895a8d6e48SMichael Große                } else {
790a3b08db5SAndreas Gohr                    $headers[$key] = [$headers[$key], $val];
7915a8d6e48SMichael Große                }
7925a8d6e48SMichael Große            } else {
7935a8d6e48SMichael Große                $headers[$key] = $val;
7945a8d6e48SMichael Große            }
7955a8d6e48SMichael Große        }
7965a8d6e48SMichael Große        return $headers;
7975a8d6e48SMichael Große    }
7985a8d6e48SMichael Große
7995a8d6e48SMichael Große    /**
8005a8d6e48SMichael Große     * convert given header array to header string
8015a8d6e48SMichael Große     *
8025a8d6e48SMichael Große     * @param array $headers
8035a8d6e48SMichael Große     * @return string
804a3b08db5SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
805a3b08db5SAndreas Gohr     *
8065a8d6e48SMichael Große     */
807a3b08db5SAndreas Gohr    protected function buildHeaders($headers)
808a3b08db5SAndreas Gohr    {
8095a8d6e48SMichael Große        $string = '';
8105a8d6e48SMichael Große        foreach ($headers as $key => $value) {
8115a8d6e48SMichael Große            if ($value === '') continue;
8125a8d6e48SMichael Große            $string .= $key . ': ' . $value . HTTP_NL;
8135a8d6e48SMichael Große        }
8145a8d6e48SMichael Große        return $string;
8155a8d6e48SMichael Große    }
8165a8d6e48SMichael Große
8175a8d6e48SMichael Große    /**
8185a8d6e48SMichael Große     * get cookies as http header string
8195a8d6e48SMichael Große     *
820a3b08db5SAndreas Gohr     * @return string
8215a8d6e48SMichael Große     * @author Andreas Goetz <cpuidle@gmx.de>
8225a8d6e48SMichael Große     *
8235a8d6e48SMichael Große     */
824a3b08db5SAndreas Gohr    protected function getCookies()
825a3b08db5SAndreas Gohr    {
8265a8d6e48SMichael Große        $headers = '';
8275a8d6e48SMichael Große        foreach ($this->cookies as $key => $val) {
8285a8d6e48SMichael Große            $headers .= "$key=$val; ";
8295a8d6e48SMichael Große        }
8305a8d6e48SMichael Große        $headers = substr($headers, 0, -2);
8315a8d6e48SMichael Große        if ($headers) $headers = "Cookie: $headers" . HTTP_NL;
8325a8d6e48SMichael Große        return $headers;
8335a8d6e48SMichael Große    }
8345a8d6e48SMichael Große
8355a8d6e48SMichael Große    /**
8365a8d6e48SMichael Große     * Encode data for posting
8375a8d6e48SMichael Große     *
8385a8d6e48SMichael Große     * @param array $data
8395a8d6e48SMichael Große     * @return string
840a3b08db5SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
841a3b08db5SAndreas Gohr     *
8425a8d6e48SMichael Große     */
843a3b08db5SAndreas Gohr    protected function postEncode($data)
844a3b08db5SAndreas Gohr    {
8455a8d6e48SMichael Große        return http_build_query($data, '', '&');
8465a8d6e48SMichael Große    }
8475a8d6e48SMichael Große
8485a8d6e48SMichael Große    /**
8495a8d6e48SMichael Große     * Encode data for posting using multipart encoding
8505a8d6e48SMichael Große     *
8515a8d6e48SMichael Große     * @fixme use of urlencode might be wrong here
8525a8d6e48SMichael Große     * @param array $data
8535a8d6e48SMichael Große     * @return string
854a3b08db5SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
855a3b08db5SAndreas Gohr     *
8565a8d6e48SMichael Große     */
857a3b08db5SAndreas Gohr    protected function postMultipartEncode($data)
858a3b08db5SAndreas Gohr    {
8595a8d6e48SMichael Große        $boundary = '--' . $this->boundary;
8605a8d6e48SMichael Große        $out = '';
8615a8d6e48SMichael Große        foreach ($data as $key => $val) {
8625a8d6e48SMichael Große            $out .= $boundary . HTTP_NL;
8635a8d6e48SMichael Große            if (!is_array($val)) {
8645a8d6e48SMichael Große                $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"' . HTTP_NL;
8655a8d6e48SMichael Große                $out .= HTTP_NL; // end of headers
8665a8d6e48SMichael Große                $out .= $val;
8675a8d6e48SMichael Große                $out .= HTTP_NL;
8685a8d6e48SMichael Große            } else {
8695a8d6e48SMichael Große                $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"';
8705a8d6e48SMichael Große                if ($val['filename']) $out .= '; filename="' . urlencode($val['filename']) . '"';
8715a8d6e48SMichael Große                $out .= HTTP_NL;
8725a8d6e48SMichael Große                if ($val['mimetype']) $out .= 'Content-Type: ' . $val['mimetype'] . HTTP_NL;
8735a8d6e48SMichael Große                $out .= HTTP_NL; // end of headers
8745a8d6e48SMichael Große                $out .= $val['body'];
8755a8d6e48SMichael Große                $out .= HTTP_NL;
8765a8d6e48SMichael Große            }
8775a8d6e48SMichael Große        }
8785a8d6e48SMichael Große        $out .= "$boundary--" . HTTP_NL;
8795a8d6e48SMichael Große        return $out;
8805a8d6e48SMichael Große    }
8815a8d6e48SMichael Große
8825a8d6e48SMichael Große    /**
8835a8d6e48SMichael Große     * Generates a unique identifier for a connection.
8845a8d6e48SMichael Große     *
8855a8d6e48SMichael Große     * @param string $server
8865a8d6e48SMichael Große     * @param string $port
8875a8d6e48SMichael Große     * @return string unique identifier
8885a8d6e48SMichael Große     */
889a3b08db5SAndreas Gohr    protected function uniqueConnectionId($server, $port)
890a3b08db5SAndreas Gohr    {
8915a8d6e48SMichael Große        return "$server:$port";
8925a8d6e48SMichael Große    }
893980f9f38SAndreas Gohr
894980f9f38SAndreas Gohr    /**
895980f9f38SAndreas Gohr     * Should the Proxy be used for the given URL?
896980f9f38SAndreas Gohr     *
897980f9f38SAndreas Gohr     * Checks the exceptions
898980f9f38SAndreas Gohr     *
899980f9f38SAndreas Gohr     * @param string $url
900980f9f38SAndreas Gohr     * @return bool
901980f9f38SAndreas Gohr     */
902a3b08db5SAndreas Gohr    protected function useProxyForUrl($url)
903a3b08db5SAndreas Gohr    {
904980f9f38SAndreas Gohr        return $this->proxy_host && (!$this->proxy_except || !preg_match('/' . $this->proxy_except . '/i', $url));
905980f9f38SAndreas Gohr    }
9065a8d6e48SMichael Große}
907