[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> HTTPClient.php (source)

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