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