1<?php
2/**
3 * HTTP Client
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Goetz <cpuidle@gmx.de>
7 */
8
9namespace dokuwiki\plugin\elwikiupgrade;
10
11if(!defined('HTTP_NL')) define('HTTP_NL',"\r\n");
12
13/**
14 * Class HTTPClientException
15 */
16class HTTPClientException extends \Exception { }
17
18/**
19 * This class implements a basic HTTP client
20 *
21 * It supports POST and GET, Proxy usage, basic authentication,
22 * handles cookies and referers. It is based upon the httpclient
23 * function from the VideoDB project.
24 *
25 * @link   http://www.splitbrain.org/go/videodb
26 * @author Andreas Goetz <cpuidle@gmx.de>
27 * @author Andreas Gohr <andi@splitbrain.org>
28 * @author Tobias Sarnowski <sarnowski@new-thoughts.org>
29 */
30class HTTPClient {
31    //set these if you like
32    var $agent;         // User agent
33    var $http;          // HTTP version defaults to 1.0
34    var $timeout;       // read timeout (seconds)
35    var $cookies;
36    var $referer;
37    var $max_redirect;
38    var $max_bodysize;
39    var $max_bodysize_abort = true;  // if set, abort if the response body is bigger than max_bodysize
40    var $header_regexp; // if set this RE must match against the headers, else abort
41    var $headers;
42    var $debug;
43    var $start = 0.0; // for timings
44    var $keep_alive = true; // keep alive rocks
45
46    // don't set these, read on error
47    var $error;
48    var $redirect_count;
49
50    // read these after a successful request
51    var $status;
52    var $resp_body;
53    var $resp_headers;
54
55    // set these to do basic authentication
56    var $user;
57    var $pass;
58
59    // set these if you need to use a proxy
60    var $proxy_host;
61    var $proxy_port;
62    var $proxy_user;
63    var $proxy_pass;
64    var $proxy_ssl; //boolean set to true if your proxy needs SSL
65    var $proxy_except; // regexp of URLs to exclude from proxy
66
67    // list of kept alive connections
68    static $connections = array();
69
70    // what we use as boundary on multipart/form-data posts
71    var $boundary = '---DokuWikiHTTPClient--4523452351';
72
73    /**
74     * Constructor.
75     *
76     * @author Andreas Gohr <andi@splitbrain.org>
77     */
78    function __construct(){
79        $this->agent        = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')';
80        $this->timeout      = 15;
81        $this->cookies      = array();
82        $this->referer      = '';
83        $this->max_redirect = 3;
84        $this->redirect_count = 0;
85        $this->status       = 0;
86        $this->headers      = array();
87        $this->http         = '1.0';
88        $this->debug        = false;
89        $this->max_bodysize = 0;
90        $this->header_regexp= '';
91        if(extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip';
92        $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'.
93                                   'text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
94        $this->headers['Accept-Language'] = 'en-us';
95    }
96
97
98    /**
99     * Simple function to do a GET request
100     *
101     * Returns the wanted page or false on an error;
102     *
103     * @param  string $url       The URL to fetch
104     * @param  bool   $sloppy304 Return body on 304 not modified
105     * @return false|string  response body, false on error
106     *
107     * @author Andreas Gohr <andi@splitbrain.org>
108     */
109    function get($url,$sloppy304=false){
110        if(!$this->sendRequest($url)) return false;
111        if($this->status == 304 && $sloppy304) return $this->resp_body;
112        if($this->status < 200 || $this->status > 206) return false;
113        return $this->resp_body;
114    }
115
116    /**
117     * Simple function to do a GET request with given parameters
118     *
119     * Returns the wanted page or false on an error.
120     *
121     * This is a convenience wrapper around get(). The given parameters
122     * will be correctly encoded and added to the given base URL.
123     *
124     * @param  string $url       The URL to fetch
125     * @param  array  $data      Associative array of parameters
126     * @param  bool   $sloppy304 Return body on 304 not modified
127     * @return false|string  response body, false on error
128     *
129     * @author Andreas Gohr <andi@splitbrain.org>
130     */
131    function dget($url,$data,$sloppy304=false){
132        if(strpos($url,'?')){
133            $url .= '&';
134        }else{
135            $url .= '?';
136        }
137        $url .= $this->_postEncode($data);
138        return $this->get($url,$sloppy304);
139    }
140
141    /**
142     * Simple function to do a POST request
143     *
144     * Returns the resulting page or false on an error;
145     *
146     * @param  string $url       The URL to fetch
147     * @param  array  $data      Associative array of parameters
148     * @return false|string  response body, false on error
149     * @author Andreas Gohr <andi@splitbrain.org>
150     */
151    function post($url,$data){
152        if(!$this->sendRequest($url,$data,'POST')) return false;
153        if($this->status < 200 || $this->status > 206) return false;
154        return $this->resp_body;
155    }
156
157    /**
158     * Send an HTTP request
159     *
160     * This method handles the whole HTTP communication. It respects set proxy settings,
161     * builds the request headers, follows redirects and parses the response.
162     *
163     * Post data should be passed as associative array. When passed as string it will be
164     * sent as is. You will need to setup your own Content-Type header then.
165     *
166     * @param  string $url    - the complete URL
167     * @param  mixed  $data   - the post data either as array or raw data
168     * @param  string $method - HTTP Method usually GET or POST.
169     * @return bool - true on success
170     *
171     * @author Andreas Goetz <cpuidle@gmx.de>
172     * @author Andreas Gohr <andi@splitbrain.org>
173     */
174    function sendRequest($url,$data='',$method='GET'){
175        $this->start  = $this->_time();
176        $this->error  = '';
177        $this->status = 0;
178        $this->status = 0;
179        $this->resp_body = '';
180        $this->resp_headers = array();
181
182        // don't accept gzip if truncated bodies might occur
183        if($this->max_bodysize &&
184           !$this->max_bodysize_abort &&
185           $this->headers['Accept-encoding'] == 'gzip'){
186            unset($this->headers['Accept-encoding']);
187        }
188
189        // parse URL into bits
190        $uri = parse_url($url);
191        $server = $uri['host'];
192        $path   = $uri['path'];
193        if(empty($path)) $path = '/';
194        if(!empty($uri['query'])) $path .= '?'.$uri['query'];
195        if(!empty($uri['port'])) $port = $uri['port'];
196        if(isset($uri['user'])) $this->user = $uri['user'];
197        if(isset($uri['pass'])) $this->pass = $uri['pass'];
198
199        // proxy setup
200        if($this->proxy_host && (!$this->proxy_except || !preg_match('/'.$this->proxy_except.'/i',$url)) ){
201            $request_url = $url;
202            $server      = $this->proxy_host;
203            $port        = $this->proxy_port;
204            if (empty($port)) $port = 8080;
205            $use_tls     = $this->proxy_ssl;
206        }else{
207            $request_url = $path;
208            if (!isset($port)) $port = ($uri['scheme'] == 'https') ? 443 : 80;
209            $use_tls     = ($uri['scheme'] == 'https');
210        }
211
212        // add SSL stream prefix if needed - needs SSL support in PHP
213        if($use_tls) {
214            if(!in_array('ssl', stream_get_transports())) {
215                $this->status = -200;
216                $this->error = 'This PHP version does not support SSL - cannot connect to server';
217            }
218            $server = 'ssl://'.$server;
219        }
220
221        // prepare headers
222        $headers               = $this->headers;
223        $headers['Host']       = $uri['host'];
224        if(!empty($uri['port'])) $headers['Host'].= ':'.$uri['port'];
225        $headers['User-Agent'] = $this->agent;
226        $headers['Referer']    = $this->referer;
227
228        if($method == 'POST'){
229            if(is_array($data)){
230                if (empty($headers['Content-Type'])) {
231                    $headers['Content-Type'] = null;
232                }
233                switch ($headers['Content-Type']) {
234                case 'multipart/form-data':
235                    $headers['Content-Type']   = 'multipart/form-data; boundary=' . $this->boundary;
236                    $data = $this->_postMultipartEncode($data);
237                    break;
238                default:
239                    $headers['Content-Type']   = 'application/x-www-form-urlencoded';
240                    $data = $this->_postEncode($data);
241                }
242            }
243        }elseif($method == 'GET'){
244            $data = ''; //no data allowed on GET requests
245        }
246
247        $contentlength = strlen($data);
248        if($contentlength)  {
249            $headers['Content-Length'] = $contentlength;
250        }
251
252        if($this->user) {
253            $headers['Authorization'] = 'Basic '.base64_encode($this->user.':'.$this->pass);
254        }
255        if($this->proxy_user) {
256            $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass);
257        }
258
259        // already connected?
260        $connectionId = $this->_uniqueConnectionId($server,$port);
261        $this->_debug('connection pool', self::$connections);
262        $socket = null;
263        if (isset(self::$connections[$connectionId])) {
264            $this->_debug('reusing connection', $connectionId);
265            $socket = self::$connections[$connectionId];
266        }
267        if (is_null($socket) || feof($socket)) {
268            $this->_debug('opening connection', $connectionId);
269            // open socket
270            $socket = @fsockopen($server,$port,$errno, $errstr, $this->timeout);
271            if (!$socket){
272                $this->status = -100;
273                $this->error = "Could not connect to $server:$port\n$errstr ($errno)";
274                return false;
275            }
276
277            // try establish a CONNECT tunnel for SSL
278            try {
279                if($this->_ssltunnel($socket, $request_url)){
280                    // no keep alive for tunnels
281                    $this->keep_alive = false;
282                    // tunnel is authed already
283                    if(isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']);
284                }
285            } catch (HTTPClientException $e) {
286                $this->status = $e->getCode();
287                $this->error = $e->getMessage();
288                fclose($socket);
289                return false;
290            }
291
292            // keep alive?
293            if ($this->keep_alive) {
294                self::$connections[$connectionId] = $socket;
295            } else {
296                unset(self::$connections[$connectionId]);
297            }
298        }
299
300        if ($this->keep_alive && !$this->proxy_host) {
301            // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
302            // connection token to a proxy server. We still do keep the connection the
303            // proxy alive (well except for CONNECT tunnels)
304            $headers['Connection'] = 'Keep-Alive';
305        } else {
306            $headers['Connection'] = 'Close';
307        }
308
309        try {
310            //set non-blocking
311            stream_set_blocking($socket, 0);
312
313            // build request
314            $request  = "$method $request_url HTTP/".$this->http.HTTP_NL;
315            $request .= $this->_buildHeaders($headers);
316            $request .= $this->_getCookies();
317            $request .= HTTP_NL;
318            $request .= $data;
319
320            $this->_debug('request',$request);
321            $this->_sendData($socket, $request, 'request');
322
323            // read headers from socket
324            $r_headers = '';
325            do{
326                $r_line = $this->_readLine($socket, 'headers');
327                $r_headers .= $r_line;
328            }while($r_line != "\r\n" && $r_line != "\n");
329
330            $this->_debug('response headers',$r_headers);
331
332            // check if expected body size exceeds allowance
333            if($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){
334                if($match[1] > $this->max_bodysize){
335                    if ($this->max_bodysize_abort)
336                        throw new HTTPClientException('Reported content length exceeds allowed response size');
337                    else
338                        $this->error = 'Reported content length exceeds allowed response size';
339                }
340            }
341
342            // get Status
343            if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/', $r_headers, $m))
344                throw new HTTPClientException('Server returned bad answer '.$r_headers);
345
346            $this->status = $m[2];
347
348            // handle headers and cookies
349            $this->resp_headers = $this->_parseHeaders($r_headers);
350            if(isset($this->resp_headers['set-cookie'])){
351                foreach ((array) $this->resp_headers['set-cookie'] as $cookie){
352                    list($cookie)   = explode(';',$cookie,2);
353                    list($key,$val) = explode('=',$cookie,2);
354                    $key = trim($key);
355                    if($val == 'deleted'){
356                        if(isset($this->cookies[$key])){
357                            unset($this->cookies[$key]);
358                        }
359                    }elseif($key){
360                        $this->cookies[$key] = $val;
361                    }
362                }
363            }
364
365            $this->_debug('Object headers',$this->resp_headers);
366
367            // check server status code to follow redirect
368            if($this->status == 301 || $this->status == 302 ){
369                if (empty($this->resp_headers['location'])){
370                    throw new HTTPClientException('Redirect but no Location Header found');
371                }elseif($this->redirect_count == $this->max_redirect){
372                    throw new HTTPClientException('Maximum number of redirects exceeded');
373                }else{
374                    // close the connection because we don't handle content retrieval here
375                    // that's the easiest way to clean up the connection
376                    fclose($socket);
377                    unset(self::$connections[$connectionId]);
378
379                    $this->redirect_count++;
380                    $this->referer = $url;
381                    // handle non-RFC-compliant relative redirects
382                    if (!preg_match('/^http/i', $this->resp_headers['location'])){
383                        if($this->resp_headers['location'][0] != '/'){
384                            $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uri['port'].
385                                                            dirname($uri['path']).'/'.$this->resp_headers['location'];
386                        }else{
387                            $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uri['port'].
388                                                            $this->resp_headers['location'];
389                        }
390                    }
391                    // perform redirected request, always via GET (required by RFC)
392                    return $this->sendRequest($this->resp_headers['location'],array(),'GET');
393                }
394            }
395
396            // check if headers are as expected
397            if($this->header_regexp && !preg_match($this->header_regexp,$r_headers))
398                throw new HTTPClientException('The received headers did not match the given regexp');
399
400            //read body (with chunked encoding if needed)
401            $r_body    = '';
402            if((isset($this->resp_headers['transfer-encoding']) && $this->resp_headers['transfer-encoding'] == 'chunked')
403            || (isset($this->resp_headers['transfer-coding']) && $this->resp_headers['transfer-coding'] == 'chunked')){
404                $abort = false;
405                do {
406                    $chunk_size = '';
407                    while (preg_match('/^[a-zA-Z0-9]?$/',$byte=$this->_readData($socket,1,'chunk'))){
408                        // read chunksize until \r
409                        $chunk_size .= $byte;
410                        if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks
411                            throw new HTTPClientException('Allowed response size exceeded');
412                    }
413                    $this->_readLine($socket, 'chunk');     // readtrailing \n
414                    $chunk_size = hexdec($chunk_size);
415
416                    if($this->max_bodysize && $chunk_size+strlen($r_body) > $this->max_bodysize){
417                        if ($this->max_bodysize_abort)
418                            throw new HTTPClientException('Allowed response size exceeded');
419                        $this->error = 'Allowed response size exceeded';
420                        $chunk_size = $this->max_bodysize - strlen($r_body);
421                        $abort = true;
422                    }
423
424                    if ($chunk_size > 0) {
425                        $r_body .= $this->_readData($socket, $chunk_size, 'chunk');
426                        $this->_readData($socket, 2, 'chunk'); // read trailing \r\n
427                    }
428                } while ($chunk_size && !$abort);
429            }elseif(isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])){
430                /* RFC 2616
431                 * If a message is received with both a Transfer-Encoding header field and a Content-Length
432                 * header field, the latter MUST be ignored.
433                 */
434
435                // read up to the content-length or max_bodysize
436                // for keep alive we need to read the whole message to clean up the socket for the next read
437                if(!$this->keep_alive && $this->max_bodysize && $this->max_bodysize < $this->resp_headers['content-length']){
438                    $length = $this->max_bodysize;
439                }else{
440                    $length = $this->resp_headers['content-length'];
441                }
442
443                $r_body = $this->_readData($socket, $length, 'response (content-length limited)', true);
444            }elseif( !isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive){
445                $r_body = $this->_readData($socket, $this->max_bodysize, 'response (content-length limited)', true);
446            } elseif ((int)$this->status === 204) {
447                // request has no content
448            } else{
449                // read entire socket
450                while (!feof($socket)) {
451                    $r_body .= $this->_readData($socket, 4096, 'response (unlimited)', true);
452                }
453            }
454
455            // recheck body size, we might had to read the whole body, so we abort late or trim here
456            if($this->max_bodysize){
457                if(strlen($r_body) > $this->max_bodysize){
458                    if ($this->max_bodysize_abort) {
459                        throw new HTTPClientException('Allowed response size exceeded');
460                    } else {
461                        $this->error = 'Allowed response size exceeded';
462                    }
463                }
464            }
465
466        } catch (HTTPClientException $err) {
467            $this->error = $err->getMessage();
468            if ($err->getCode())
469                $this->status = $err->getCode();
470            unset(self::$connections[$connectionId]);
471            fclose($socket);
472            return false;
473        }
474
475        if (!$this->keep_alive ||
476                (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')) {
477            // close socket
478            fclose($socket);
479            unset(self::$connections[$connectionId]);
480        }
481
482        // decode gzip if needed
483        if(isset($this->resp_headers['content-encoding']) &&
484           $this->resp_headers['content-encoding'] == 'gzip' &&
485           strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){
486            $this->resp_body = @gzinflate(substr($r_body, 10));
487            if($this->resp_body === false){
488                $this->error = 'Failed to decompress gzip encoded content';
489                $this->resp_body = $r_body;
490            }
491        }else{
492            $this->resp_body = $r_body;
493        }
494
495        $this->_debug('response body',$this->resp_body);
496        $this->redirect_count = 0;
497        return true;
498    }
499
500    /**
501     * Tries to establish a CONNECT tunnel via Proxy
502     *
503     * Protocol, Servername and Port will be stripped from the request URL when a successful CONNECT happened
504     *
505     * @param resource &$socket
506     * @param string   &$requesturl
507     * @throws HTTPClientException when a tunnel is needed but could not be established
508     * @return bool true if a tunnel was established
509     */
510    function _ssltunnel(&$socket, &$requesturl){
511        if(!$this->proxy_host) return false;
512        $requestinfo = parse_url($requesturl);
513        if($requestinfo['scheme'] != 'https') return false;
514        if(!$requestinfo['port']) $requestinfo['port'] = 443;
515
516        // build request
517        $request  = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0".HTTP_NL;
518        $request .= "Host: {$requestinfo['host']}".HTTP_NL;
519        if($this->proxy_user) {
520            $request .= 'Proxy-Authorization: Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass).HTTP_NL;
521        }
522        $request .= HTTP_NL;
523
524        $this->_debug('SSL Tunnel CONNECT',$request);
525        $this->_sendData($socket, $request, 'SSL Tunnel CONNECT');
526
527        // read headers from socket
528        $r_headers = '';
529        do{
530            $r_line = $this->_readLine($socket, 'headers');
531            $r_headers .= $r_line;
532        }while($r_line != "\r\n" && $r_line != "\n");
533
534        $this->_debug('SSL Tunnel Response',$r_headers);
535        if(preg_match('/^HTTP\/1\.[01] 200/i',$r_headers)){
536            // set correct peer name for verification (enabled since PHP 5.6)
537            stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']);
538
539            // SSLv3 is broken, use only TLS connections.
540            // @link https://bugs.php.net/69195
541            if (PHP_VERSION_ID >= 50600 && PHP_VERSION_ID <= 50606) {
542                $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_CLIENT;
543            } else {
544                // actually means neither SSLv2 nor SSLv3
545                $cryptoMethod = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
546            }
547
548            if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) {
549                $requesturl = $requestinfo['path'].
550                  (!empty($requestinfo['query'])?'?'.$requestinfo['query']:'');
551                return true;
552            }
553
554            throw new HTTPClientException('Failed to set up crypto for secure connection to '.$requestinfo['host'], -151);
555        }
556
557        throw new HTTPClientException('Failed to establish secure proxy connection', -150);
558    }
559
560    /**
561     * Safely write data to a socket
562     *
563     * @param  resource $socket     An open socket handle
564     * @param  string   $data       The data to write
565     * @param  string   $message    Description of what is being read
566     * @throws HTTPClientException
567     *
568     * @author Tom N Harris <tnharris@whoopdedo.org>
569     */
570    function _sendData($socket, $data, $message) {
571        // send request
572        $towrite = strlen($data);
573        $written = 0;
574        while($written < $towrite){
575            // check timeout
576            $time_used = $this->_time() - $this->start;
577            if($time_used > $this->timeout)
578                throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)',$message, $time_used), -100);
579            if(feof($socket))
580                throw new HTTPClientException("Socket disconnected while writing $message");
581
582            // select parameters
583            $sel_r = null;
584            $sel_w = array($socket);
585            $sel_e = null;
586            // wait for stream ready or timeout (1sec)
587            if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
588                 usleep(1000);
589                 continue;
590            }
591
592            // write to stream
593            $nbytes = fwrite($socket, substr($data,$written,4096));
594            if($nbytes === false)
595                throw new HTTPClientException("Failed writing to socket while sending $message", -100);
596            $written += $nbytes;
597        }
598    }
599
600    /**
601     * Safely read data from a socket
602     *
603     * Reads up to a given number of bytes or throws an exception if the
604     * response times out or ends prematurely.
605     *
606     * @param  resource $socket     An open socket handle in non-blocking mode
607     * @param  int      $nbytes     Number of bytes to read
608     * @param  string   $message    Description of what is being read
609     * @param  bool     $ignore_eof End-of-file is not an error if this is set
610     * @throws HTTPClientException
611     * @return string
612     *
613     * @author Tom N Harris <tnharris@whoopdedo.org>
614     */
615    function _readData($socket, $nbytes, $message, $ignore_eof = false) {
616        $r_data = '';
617        // Does not return immediately so timeout and eof can be checked
618        if ($nbytes < 0) $nbytes = 0;
619        $to_read = $nbytes;
620        do {
621            $time_used = $this->_time() - $this->start;
622            if ($time_used > $this->timeout)
623                throw new HTTPClientException(
624                        sprintf('Timeout while reading %s after %d bytes (%.3fs)', $message,
625                                strlen($r_data), $time_used), -100);
626            if(feof($socket)) {
627                if(!$ignore_eof)
628                    throw new HTTPClientException("Premature End of File (socket) while reading $message");
629                break;
630            }
631
632            if ($to_read > 0) {
633                // select parameters
634                $sel_r = array($socket);
635                $sel_w = null;
636                $sel_e = null;
637                // wait for stream ready or timeout (1sec)
638                if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
639                     usleep(1000);
640                     continue;
641                }
642
643                $bytes = fread($socket, $to_read);
644                if($bytes === false)
645                    throw new HTTPClientException("Failed reading from socket while reading $message", -100);
646                $r_data .= $bytes;
647                $to_read -= strlen($bytes);
648            }
649        } while ($to_read > 0 && strlen($r_data) < $nbytes);
650        return $r_data;
651    }
652
653    /**
654     * Safely read a \n-terminated line from a socket
655     *
656     * Always returns a complete line, including the terminating \n.
657     *
658     * @param  resource $socket     An open socket handle in non-blocking mode
659     * @param  string   $message    Description of what is being read
660     * @throws HTTPClientException
661     * @return string
662     *
663     * @author Tom N Harris <tnharris@whoopdedo.org>
664     */
665    function _readLine($socket, $message) {
666        $r_data = '';
667        do {
668            $time_used = $this->_time() - $this->start;
669            if ($time_used > $this->timeout)
670                throw new HTTPClientException(
671                        sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data),
672                        -100);
673            if(feof($socket))
674                throw new HTTPClientException("Premature End of File (socket) while reading $message");
675
676            // select parameters
677            $sel_r = array($socket);
678            $sel_w = null;
679            $sel_e = null;
680            // wait for stream ready or timeout (1sec)
681            if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
682                 usleep(1000);
683                 continue;
684            }
685
686            $r_data = fgets($socket, 1024);
687        } while (!preg_match('/\n$/',$r_data));
688        return $r_data;
689    }
690
691    /**
692     * print debug info
693     *
694     * Uses _debug_text or _debug_html depending on the SAPI name
695     *
696     * @author Andreas Gohr <andi@splitbrain.org>
697     *
698     * @param string $info
699     * @param mixed  $var
700     */
701    function _debug($info,$var=null){
702        if(!$this->debug) return;
703        if(php_sapi_name() == 'cli'){
704            $this->_debug_text($info, $var);
705        }else{
706            $this->_debug_html($info, $var);
707        }
708    }
709
710    /**
711     * print debug info as HTML
712     *
713     * @param string $info
714     * @param mixed  $var
715     */
716    function _debug_html($info, $var=null){
717        print '<b>'.$info.'</b> '.($this->_time() - $this->start).'s<br />';
718        if(!is_null($var)){
719            ob_start();
720            print_r($var);
721            $content = htmlspecialchars(ob_get_contents());
722            ob_end_clean();
723            print '<pre>'.$content.'</pre>';
724        }
725    }
726
727    /**
728     * prints debug info as plain text
729     *
730     * @param string $info
731     * @param mixed  $var
732     */
733    function _debug_text($info, $var=null){
734        print '*'.$info.'* '.($this->_time() - $this->start)."s\n";
735        if(!is_null($var)) print_r($var);
736        print "\n-----------------------------------------------\n";
737    }
738
739    /**
740     * Return current timestamp in microsecond resolution
741     *
742     * @return float
743     */
744    static function _time(){
745        list($usec, $sec) = explode(" ", microtime());
746        return ((float)$usec + (float)$sec);
747    }
748
749    /**
750     * convert given header string to Header array
751     *
752     * All Keys are lowercased.
753     *
754     * @author Andreas Gohr <andi@splitbrain.org>
755     *
756     * @param string $string
757     * @return array
758     */
759    function _parseHeaders($string){
760        $headers = array();
761        $lines = explode("\n",$string);
762        array_shift($lines); //skip first line (status)
763        foreach($lines as $line){
764            @list($key, $val) = explode(':',$line,2);
765            $key = trim($key);
766            $val = trim($val);
767            $key = strtolower($key);
768            if(!$key) continue;
769            if(isset($headers[$key])){
770                if(is_array($headers[$key])){
771                    $headers[$key][] = $val;
772                }else{
773                    $headers[$key] = array($headers[$key],$val);
774                }
775            }else{
776                $headers[$key] = $val;
777            }
778        }
779        return $headers;
780    }
781
782    /**
783     * convert given header array to header string
784     *
785     * @author Andreas Gohr <andi@splitbrain.org>
786     *
787     * @param array $headers
788     * @return string
789     */
790    function _buildHeaders($headers){
791        $string = '';
792        foreach($headers as $key => $value){
793            if($value === '') continue;
794            $string .= $key.': '.$value.HTTP_NL;
795        }
796        return $string;
797    }
798
799    /**
800     * get cookies as http header string
801     *
802     * @author Andreas Goetz <cpuidle@gmx.de>
803     *
804     * @return string
805     */
806    function _getCookies(){
807        $headers = '';
808        foreach ($this->cookies as $key => $val){
809            $headers .= "$key=$val; ";
810        }
811        $headers = substr($headers, 0, -2);
812        if ($headers) $headers = "Cookie: $headers".HTTP_NL;
813        return $headers;
814    }
815
816    /**
817     * Encode data for posting
818     *
819     * @author Andreas Gohr <andi@splitbrain.org>
820     *
821     * @param array $data
822     * @return string
823     */
824    function _postEncode($data){
825        return http_build_query($data,'','&');
826    }
827
828    /**
829     * Encode data for posting using multipart encoding
830     *
831     * @fixme use of urlencode might be wrong here
832     * @author Andreas Gohr <andi@splitbrain.org>
833     *
834     * @param array $data
835     * @return string
836     */
837    function _postMultipartEncode($data){
838        $boundary = '--'.$this->boundary;
839        $out = '';
840        foreach($data as $key => $val){
841            $out .= $boundary.HTTP_NL;
842            if(!is_array($val)){
843                $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL;
844                $out .= HTTP_NL; // end of headers
845                $out .= $val;
846                $out .= HTTP_NL;
847            }else{
848                $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"';
849                if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"';
850                $out .= HTTP_NL;
851                if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL;
852                $out .= HTTP_NL; // end of headers
853                $out .= $val['body'];
854                $out .= HTTP_NL;
855            }
856        }
857        $out .= "$boundary--".HTTP_NL;
858        return $out;
859    }
860
861    /**
862     * Generates a unique identifier for a connection.
863     *
864     * @param  string $server
865     * @param  string $port
866     * @return string unique identifier
867     */
868    function _uniqueConnectionId($server, $port) {
869        return "$server:$port";
870    }
871}
872
873
874/**
875 * Adds DokuWiki specific configs to the HTTP client
876 *
877 * @author Andreas Goetz <cpuidle@gmx.de>
878 */
879class DokuHTTPClient extends HTTPClient {
880
881    /**
882     * Constructor.
883     *
884     * @author Andreas Gohr <andi@splitbrain.org>
885     */
886    function __construct(){
887        global $conf;
888
889        // call parent constructor
890        parent::__construct();
891
892        // set some values from the config
893        $this->proxy_host   = $conf['proxy']['host'];
894        $this->proxy_port   = $conf['proxy']['port'];
895        $this->proxy_user   = $conf['proxy']['user'];
896        $this->proxy_pass   = conf_decodeString($conf['proxy']['pass']);
897        $this->proxy_ssl    = $conf['proxy']['ssl'];
898        $this->proxy_except = $conf['proxy']['except'];
899
900        // allow enabling debugging via URL parameter (if debugging allowed)
901        if($conf['allowdebug']) {
902            if(
903                isset($_REQUEST['httpdebug']) ||
904                (
905                    isset($_SERVER['HTTP_REFERER']) &&
906                    strpos($_SERVER['HTTP_REFERER'], 'httpdebug') !== false
907                )
908            ) {
909                $this->debug = true;
910            }
911        }
912    }
913
914
915    /**
916     * Wraps an event around the parent function
917     *
918     * @triggers HTTPCLIENT_REQUEST_SEND
919     * @author   Andreas Gohr <andi@splitbrain.org>
920     */
921    /**
922     * @param string $url
923     * @param string|array $data the post data either as array or raw data
924     * @param string $method
925     * @return bool
926     */
927    function sendRequest($url,$data='',$method='GET'){
928        $httpdata = array('url'    => $url,
929                          'data'   => $data,
930                          'method' => $method);
931        $evt = new \Doku_Event('HTTPCLIENT_REQUEST_SEND',$httpdata);
932        if($evt->advise_before()){
933            $url    = $httpdata['url'];
934            $data   = $httpdata['data'];
935            $method = $httpdata['method'];
936        }
937        $evt->advise_after();
938        unset($evt);
939        return parent::sendRequest($url,$data,$method);
940    }
941
942}
943
944//Setup VIM: ex: et ts=4 :
945