summaryrefslogtreecommitdiff
path: root/vendor/miniflux/picofeed/lib/PicoFeed/Client/Stream.php
blob: 2e91d47212e69490d6ee82648759bd9f0c2ec5ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
<?php

namespace PicoFeed\Client;

use PicoFeed\Logging\Logger;

/**
 * Stream context HTTP client.
 *
 * @author  Frederic Guillot
 */
class Stream extends Client
{
    /**
     * Prepare HTTP headers.
     *
     * @return string[]
     */
    private function prepareHeaders()
    {
        $headers = array(
            'Connection: close',
            'User-Agent: '.$this->user_agent,
        );

        // disable compression in passthrough mode. It could result in double
        // compressed content which isn't decodeable by browsers
        if (function_exists('gzdecode') && !$this->isPassthroughEnabled()) {
            $headers[] = 'Accept-Encoding: gzip';
        }

        if ($this->etag) {
            $headers[] = 'If-None-Match: '.$this->etag;
            $headers[] = 'A-IM: feed';
        }

        if ($this->last_modified) {
            $headers[] = 'If-Modified-Since: '.$this->last_modified;
        }

        if ($this->proxy_username) {
            $headers[] = 'Proxy-Authorization: Basic '.base64_encode($this->proxy_username.':'.$this->proxy_password);
        }

        if ($this->username && $this->password) {
            $headers[] = 'Authorization: Basic '.base64_encode($this->username.':'.$this->password);
        }

        $headers = array_merge($headers, $this->request_headers);

        return $headers;
    }

    /**
     * Construct the final URL from location headers.
     *
     * @param array $headers List of HTTP response header
     */
    private function setEffectiveUrl($headers)
    {
        foreach ($headers as $header) {
            if (stripos($header, 'Location') === 0) {
                list(, $value) = explode(': ', $header);

                $this->url = Url::resolve($value, $this->url);
            }
        }
    }

    /**
     * Prepare stream context.
     *
     * @return array
     */
    private function prepareContext()
    {
        $context = array(
            'http' => array(
                'method' => 'GET',
                'protocol_version' => 1.1,
                'timeout' => $this->timeout,
                'max_redirects' => $this->max_redirects,
            ),
        );

        if ($this->proxy_hostname) {
            Logger::setMessage(get_called_class().' Proxy: '.$this->proxy_hostname.':'.$this->proxy_port);

            $context['http']['proxy'] = 'tcp://'.$this->proxy_hostname.':'.$this->proxy_port;
            $context['http']['request_fulluri'] = true;

            if ($this->proxy_username) {
                Logger::setMessage(get_called_class().' Proxy credentials: Yes');
            } else {
                Logger::setMessage(get_called_class().' Proxy credentials: No');
            }
        }

        $context['http']['header'] = implode("\r\n", $this->prepareHeaders());

        return $context;
    }

    /**
     * Do the HTTP request.
     *
     * @return array HTTP response ['body' => ..., 'status' => ..., 'headers' => ...]
     * @throws InvalidUrlException
     * @throws MaxSizeException
     * @throws TimeoutException
     */
    public function doRequest()
    {
        $body = '';

        // Create context
        $context = stream_context_create($this->prepareContext());

        // Make HTTP request
        $stream = @fopen($this->url, 'r', false, $context);
        if (!is_resource($stream)) {
            throw new InvalidUrlException('Unable to establish a connection');
        }

        // Get HTTP headers response
        $metadata = stream_get_meta_data($stream);
        list($status, $headers) = HttpHeaders::parse($metadata['wrapper_data']);

        if ($this->isPassthroughEnabled()) {
            header(':', true, $status);

            if (isset($headers['Content-Type'])) {
                header('Content-Type: '.$headers['Content-Type']);
            }

            fpassthru($stream);
        } else {
            // Get the entire body until the max size
            $body = stream_get_contents($stream, $this->max_body_size + 1);

            // If the body size is too large abort everything
            if (strlen($body) > $this->max_body_size) {
                throw new MaxSizeException('Content size too large');
            }

            if ($metadata['timed_out']) {
                throw new TimeoutException('Operation timeout');
            }
        }

        fclose($stream);

        $this->setEffectiveUrl($metadata['wrapper_data']);

        return array(
            'status' => $status,
            'body' => $this->decodeBody($body, $headers),
            'headers' => $headers,
        );
    }

    /**
     * Decode body response according to the HTTP headers.
     *
     * @param string      $body    Raw body
     * @param HttpHeaders $headers HTTP headers
     *
     * @return string
     */
    public function decodeBody($body, HttpHeaders $headers)
    {
        if (isset($headers['Transfer-Encoding']) && $headers['Transfer-Encoding'] === 'chunked') {
            $body = $this->decodeChunked($body);
        }

        if (isset($headers['Content-Encoding']) && $headers['Content-Encoding'] === 'gzip') {
            $body = gzdecode($body);
        }

        return $body;
    }

    /**
     * Decode a chunked body.
     *
     * @param string $str Raw body
     *
     * @return string Decoded body
     */
    public function decodeChunked($str)
    {
        for ($result = ''; !empty($str); $str = trim($str)) {

            // Get the chunk length
            $pos = strpos($str, "\r\n");
            $len = hexdec(substr($str, 0, $pos));

            // Append the chunk to the result
            $result .= substr($str, $pos + 2, $len);
            $str = substr($str, $pos + 2 + $len);
        }

        return $result;
    }
}