Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
Request.php
1 <?php
46 // Matrix modifications based on HTTP_Request v.1.4.4
47 // $Id: Request.php,v 1.8 2010/07/15 04:43:37 csmith Exp $
48 
52 require_once 'PEAR.php';
56 require_once 'Net/Socket.php';
60 require_once 'Net/URL.php';
61 
65 define('HTTP_REQUEST_METHOD_GET', 'GET', true);
66 define('HTTP_REQUEST_METHOD_HEAD', 'HEAD', true);
67 define('HTTP_REQUEST_METHOD_POST', 'POST', true);
68 define('HTTP_REQUEST_METHOD_PUT', 'PUT', true);
69 define('HTTP_REQUEST_METHOD_DELETE', 'DELETE', true);
70 define('HTTP_REQUEST_METHOD_OPTIONS', 'OPTIONS', true);
71 define('HTTP_REQUEST_METHOD_TRACE', 'TRACE', true);
77 define('HTTP_REQUEST_ERROR_FILE', 1);
78 define('HTTP_REQUEST_ERROR_URL', 2);
79 define('HTTP_REQUEST_ERROR_PROXY', 4);
80 define('HTTP_REQUEST_ERROR_REDIRECTS', 8);
81 define('HTTP_REQUEST_ERROR_RESPONSE', 16);
82 define('HTTP_REQUEST_ERROR_GZIP_METHOD', 32);
83 define('HTTP_REQUEST_ERROR_GZIP_READ', 64);
84 define('HTTP_REQUEST_ERROR_GZIP_DATA', 128);
85 define('HTTP_REQUEST_ERROR_GZIP_CRC', 256);
91 define('HTTP_REQUEST_HTTP_VER_1_0', '1.0', true);
92 define('HTTP_REQUEST_HTTP_VER_1_1', '1.1', true);
95 if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
99  define('HTTP_REQUEST_MBSTRING', true);
100 } else {
104  define('HTTP_REQUEST_MBSTRING', false);
105 }
106 
124 {
132  var $_url;
133 
138  var $_method;
139 
144  var $_http;
145 
150  var $_requestHeaders;
151 
156  var $_user;
157 
162  var $_pass;
163 
168  var $_sock;
169 
174  var $_proxy_host;
175 
180  var $_proxy_port;
181 
186  var $_proxy_user;
187 
192  var $_proxy_pass;
193 
198  var $_postData;
199 
204  var $_body;
205 
210  var $_bodyDisallowed = array('TRACE');
211 
220  var $_bodyRequired = array('POST', 'PUT');
221 
226  var $_postFiles = array();
227 
232  var $_timeout;
233 
238  var $_response;
239 
244  var $_allowRedirects;
245 
250  var $_maxRedirects;
251 
256  var $_redirects;
257 
262  var $_useBrackets = true;
263 
268  var $_listeners = array();
269 
274  var $_saveBody = true;
275 
280  var $_readTimeout = null;
281 
286  var $_socketOptions = null;
314  function HTTP_Request($url = '', $params = array())
315  {
316  $this->_method = HTTP_REQUEST_METHOD_GET;
317  $this->_http = HTTP_REQUEST_HTTP_VER_1_1;
318  $this->_requestHeaders = array();
319  $this->_postData = array();
320  $this->_body = null;
321 
322  $this->_user = null;
323  $this->_pass = null;
324 
325  $this->_proxy_host = null;
326  $this->_proxy_port = null;
327  $this->_proxy_user = null;
328  $this->_proxy_pass = null;
329 
330  $this->_allowRedirects = false;
331  $this->_maxRedirects = 3;
332  $this->_redirects = 0;
333 
334  $this->_timeout = null;
335  $this->_response = null;
336 
337  foreach ($params as $key => $value) {
338  $this->{'_' . $key} = $value;
339  }
340 
341  if (!empty($url)) {
342  $this->setURL($url);
343  }
344 
345  // Default useragent
346  $this->addHeader('User-Agent', 'PEAR HTTP_Request class ( http://pear.php.net/ )');
347 
348  // We don't do keep-alives by default
349  $this->addHeader('Connection', 'close');
350 
351  // Basic authentication
352  if (!empty($this->_user)) {
353  $this->addHeader('Authorization', 'Basic ' . base64_encode($this->_user . ':' . $this->_pass));
354  }
355 
356  // Proxy authentication (see bug #5913)
357  if (!empty($this->_proxy_user)) {
358  $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($this->_proxy_user . ':' . $this->_proxy_pass));
359  }
360 
361  // Use gzip encoding if possible
362  if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && extension_loaded('zlib')) {
363  $this->addHeader('Accept-Encoding', 'gzip');
364  }
365  }
366 
374  {
375  if ($this->_url->port != 80 AND strcasecmp($this->_url->protocol, 'http') == 0) {
376  $host = $this->_url->host . ':' . $this->_url->port;
377 
378  } elseif ($this->_url->port != 443 AND strcasecmp($this->_url->protocol, 'https') == 0) {
379  $host = $this->_url->host . ':' . $this->_url->port;
380 
381  } elseif ($this->_url->port == 443 AND strcasecmp($this->_url->protocol, 'https') == 0 AND strpos($this->_url->url, ':443') !== false) {
382  $host = $this->_url->host . ':' . $this->_url->port;
383 
384  } else {
385  $host = $this->_url->host;
386  }
387 
388  return $host;
389  }
390 
401  function reset($url, $params = array())
402  {
403  $this->HTTP_Request($url, $params);
404  }
405 
412  function setURL($url)
413  {
414  $this->_url = new Net_URL($url, $this->_useBrackets);
415 
416  if (!empty($this->_url->user) || !empty($this->_url->pass)) {
417  $this->setBasicAuth($this->_url->user, $this->_url->pass);
418  }
419 
420  if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http) {
421  $this->addHeader('Host', $this->_generateHostHeader());
422  }
423 
424  // set '/' instead of empty path rather than check later (see bug #8662)
425  if (empty($this->_url->path)) {
426  $this->_url->path = '/';
427  }
428  }
429 
436  function getUrl()
437  {
438  return empty($this->_url)? '': $this->_url->getUrl();
439  }
440 
450  function setProxy($host, $port = 8080, $user = null, $pass = null)
451  {
452  $this->_proxy_host = $host;
453  $this->_proxy_port = $port;
454  $this->_proxy_user = $user;
455  $this->_proxy_pass = $pass;
456 
457  if (!empty($user)) {
458  $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($user . ':' . $pass));
459  }
460  }
461 
468  function setBasicAuth($user, $pass)
469  {
470  $this->_user = $user;
471  $this->_pass = $pass;
472 
473  $this->addHeader('Authorization', 'Basic ' . base64_encode($user . ':' . $pass));
474  }
475 
482  function setMethod($method)
483  {
484  $this->_method = $method;
485  }
486 
493  function setHttpVer($http)
494  {
495  $this->_http = $http;
496  }
497 
505  function addHeader($name, $value)
506  {
507  $this->_requestHeaders[strtolower($name)] = $value;
508  }
509 
516  function removeHeader($name)
517  {
518  if (isset($this->_requestHeaders[strtolower($name)])) {
519  unset($this->_requestHeaders[strtolower($name)]);
520  }
521  }
522 
531  function addQueryString($name, $value, $preencoded = false)
532  {
533  $this->_url->addQueryString($name, $value, $preencoded);
534  }
535 
543  function addRawQueryString($querystring, $preencoded = true)
544  {
545  $this->_url->addRawQueryString($querystring, $preencoded);
546  }
547 
556  function addPostData($name, $value, $preencoded = false)
557  {
558  if ($preencoded) {
559  $this->_postData[$name] = $value;
560  } else {
561  $this->_postData[$name] = $this->_arrayMapRecursive('urlencode', $value);
562  }
563  }
564 
573  function _arrayMapRecursive($callback, $value)
574  {
575  if (!is_array($value)) {
576  return call_user_func($callback, $value);
577  } else {
578  $map = array();
579  foreach ($value as $k => $v) {
580  $map[$k] = $this->_arrayMapRecursive($callback, $v);
581  }
582  return $map;
583  }
584  }
585 
602  function addFile($inputName, $fileName, $contentType = 'application/octet-stream')
603  {
604  if (!is_array($fileName) && !is_readable($fileName)) {
605  return PEAR::raiseError("File '{$fileName}' is not readable", HTTP_REQUEST_ERROR_FILE);
606  } elseif (is_array($fileName)) {
607  foreach ($fileName as $name) {
608  if (!is_readable($name)) {
609  return PEAR::raiseError("File '{$name}' is not readable", HTTP_REQUEST_ERROR_FILE);
610  }
611  }
612  }
613  $this->addHeader('Content-Type', 'multipart/form-data');
614  $this->_postFiles[$inputName] = array(
615  'name' => $fileName,
616  'type' => $contentType
617  );
618  return true;
619  }
620 
629  function addRawPostData($postdata, $preencoded = true)
630  {
631  $this->_body = $preencoded ? $postdata : urlencode($postdata);
632  }
633 
640  function setBody($body)
641  {
642  $this->_body = $body;
643  }
644 
653  function clearPostData()
654  {
655  $this->_postData = null;
656  }
657 
665  function addCookie($name, $value)
666  {
667  $cookies = isset($this->_requestHeaders['cookie']) ? $this->_requestHeaders['cookie']. '; ' : '';
668  $this->addHeader('Cookie', $cookies . $name . '=' . $value);
669  }
670 
679  function clearCookies()
680  {
681  $this->removeHeader('Cookie');
682  }
683 
692  function sendRequest($saveBody = true)
693  {
694  if (!is_a($this->_url, 'Net_URL')) {
695  return PEAR::raiseError('No URL given', HTTP_REQUEST_ERROR_URL);
696  }
697 
698  $host = isset($this->_proxy_host) ? $this->_proxy_host : $this->_url->host;
699  $port = isset($this->_proxy_port) ? $this->_proxy_port : $this->_url->port;
700 
701  if (strcasecmp($this->_url->protocol, 'https') == 0) {
702  // Bug #14127, don't try connecting to HTTPS sites without OpenSSL
703  if (version_compare(PHP_VERSION, '4.3.0', '<') || !extension_loaded('openssl')) {
704  return PEAR::raiseError('Need PHP 4.3.0 or later with OpenSSL support for https:// requests',
705  HTTP_REQUEST_ERROR_URL);
706  } elseif (isset($this->_proxy_host)) {
707  return PEAR::raiseError('HTTPS proxies are not supported', HTTP_REQUEST_ERROR_PROXY);
708  }
709  $host = 'ssl://' . $host;
710  }
711 
712  // magic quotes may break file uploads and chunked response processing
713  $magicQuotes = ini_get('magic_quotes_runtime');
714  ini_set('magic_quotes_runtime', false);
715 
716  // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
717  // connection token to a proxy server...
718  if (isset($this->_proxy_host) && !empty($this->_requestHeaders['connection']) &&
719  'Keep-Alive' == $this->_requestHeaders['connection'])
720  {
721  $this->removeHeader('connection');
722  }
723 
724  $keepAlive = (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && empty($this->_requestHeaders['connection'])) ||
725  (!empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']);
726  $sockets = &PEAR::getStaticProperty('HTTP_Request', 'sockets');
727  $sockKey = $host . ':' . $port;
728  unset($this->_sock);
729 
730  // There is a connected socket in the "static" property?
731  if ($keepAlive && !empty($sockets[$sockKey]) &&
732  !empty($sockets[$sockKey]->fp))
733  {
734  $this->_sock =& $sockets[$sockKey];
735  $err = null;
736  } else {
737  $this->_notify('connect');
738  $this->_sock = new Net_Socket();
739  $err = $this->_sock->connect($host, $port, null, $this->_timeout, $this->_socketOptions);
740  }
741  PEAR::isError($err) or $err = $this->_sock->write($this->_buildRequest());
742 
743  if (!PEAR::isError($err)) {
744  if (!empty($this->_readTimeout)) {
745  $this->_sock->setTimeout($this->_readTimeout[0], $this->_readTimeout[1]);
746  }
747 
748  $this->_notify('sentRequest');
749 
750  // Read the response
751  $this->_response = new HTTP_Response($this->_sock, $this->_listeners);
752  $err = $this->_response->process(
753  $this->_saveBody && $saveBody,
754  HTTP_REQUEST_METHOD_HEAD != $this->_method
755  );
756 
757  if ($keepAlive) {
758  $keepAlive = (isset($this->_response->_headers['content-length'])
759  || (isset($this->_response->_headers['transfer-encoding'])
760  && strtolower($this->_response->_headers['transfer-encoding']) == 'chunked'));
761  if ($keepAlive) {
762  if (isset($this->_response->_headers['connection'])) {
763  $keepAlive = strtolower($this->_response->_headers['connection']) == 'keep-alive';
764  } else {
765  $keepAlive = 'HTTP/'.HTTP_REQUEST_HTTP_VER_1_1 == $this->_response->_protocol;
766  }
767  }
768  }
769  }
770 
771  ini_set('magic_quotes_runtime', $magicQuotes);
772 
773  if (PEAR::isError($err)) {
774  return $err;
775  }
776 
777  if (!$keepAlive) {
778  $this->disconnect();
779  // Store the connected socket in "static" property
780  } elseif (empty($sockets[$sockKey]) || empty($sockets[$sockKey]->fp)) {
781  $sockets[$sockKey] =& $this->_sock;
782  }
783 
784  // Check for redirection
785  if ( $this->_allowRedirects
786  AND $this->_redirects <= $this->_maxRedirects
787  AND $this->getResponseCode() > 300
788  AND $this->getResponseCode() < 399
789  AND !empty($this->_response->_headers['location'])) {
790 
791 
792  $redirect = $this->_response->_headers['location'];
793 
794  // Absolute URL
795  if (preg_match('/^https?:\/\//i', $redirect)) {
796  $this->_url = new Net_URL($redirect);
797  $this->addHeader('Host', $this->_generateHostHeader());
798  // Absolute path
799  } elseif ($redirect{0} == '/') {
800  $this->_url->path = $redirect;
801 
802  // Relative path
803  } elseif (substr($redirect, 0, 3) == '../' OR substr($redirect, 0, 2) == './') {
804  if (substr($this->_url->path, -1) == '/') {
805  $redirect = $this->_url->path . $redirect;
806  } else {
807  $redirect = dirname($this->_url->path) . '/' . $redirect;
808  }
809  $redirect = Net_URL::resolvePath($redirect);
810  $this->_url->path = $redirect;
811 
812  // Filename, no path
813  } else {
814  if (substr($this->_url->path, -1) == '/') {
815  $redirect = $this->_url->path . $redirect;
816  } else {
817  $redirect = dirname($this->_url->path) . '/' . $redirect;
818  }
819  $this->_url->path = $redirect;
820  }
821 
822  $this->_redirects++;
823  return $this->sendRequest($saveBody);
824 
825  // Too many redirects
826  } elseif ($this->_allowRedirects AND $this->_redirects > $this->_maxRedirects) {
827  return PEAR::raiseError('Too many redirects', HTTP_REQUEST_ERROR_REDIRECTS);
828  }
829 
830  return true;
831  }
832 
838  function disconnect()
839  {
840  if (!empty($this->_sock) && !empty($this->_sock->fp)) {
841  $this->_notify('disconnect');
842  $this->_sock->disconnect();
843  }
844  }
845 
852  function getResponseCode()
853  {
854  return isset($this->_response->_code) ? $this->_response->_code : false;
855  }
856 
863  function getResponseReason()
864  {
865  return isset($this->_response->_reason) ? $this->_response->_reason : false;
866  }
867 
876  function getResponseHeader($headername = null)
877  {
878  if (!isset($headername)) {
879  return isset($this->_response->_headers)? $this->_response->_headers: array();
880  } else {
881  $headername = strtolower($headername);
882  return isset($this->_response->_headers[$headername]) ? $this->_response->_headers[$headername] : false;
883  }
884  }
885 
892  function getResponseBody()
893  {
894  return isset($this->_response->_body) ? $this->_response->_body : false;
895  }
896 
904  {
905  return isset($this->_response->_cookies) ? $this->_response->_cookies : false;
906  }
907 
925  function getEncodedPath()
926  {
927  $is_dir = false;
928  if (strlen($this->_url->path) > 1 && substr($this->_url->path, -1) == '/') {
929  $is_dir = true;
930  }
931 
932  $path_parts = preg_split('|/|', $this->_url->path, -1, PREG_SPLIT_NO_EMPTY);
933 
934  if (empty($path_parts)) {
935  return '/';
936  }
937 
938  foreach ($path_parts as $key => $part) {
939  // Check for % that is NOT an escape sequence || invalid chars
940  if (preg_match('/%[^a-f0-9]/i', $part) || preg_match('/[^@a-z0-9_.!~*\'()$+&,:=-]/i', $part)) {
941  $path_parts[$key] = urlencode(urldecode($part));
942  }
943  }
944 
945  $path = '/'.implode('/', $path_parts);
946 
947  if ($is_dir) {
948  $path .= '/';
949  }
950 
951  return $path;
952  }
953 
960  function _buildRequest()
961  {
962  $separator = ini_get('arg_separator.output');
963  ini_set('arg_separator.output', '&');
964  $querystring = ($querystring = $this->_url->getQueryString()) ? '?' . $querystring : '';
965  ini_set('arg_separator.output', $separator);
966 
967  $host = isset($this->_proxy_host) ? $this->_url->protocol . '://' . $this->_url->host : '';
968  $port = (isset($this->_proxy_host) AND $this->_url->port != 80) ? ':' . $this->_url->port : '';
969  $path = $this->getEncodedPath() . $querystring;
970  $url = $host . $port . $path;
971 
972  if (!strlen($url)) {
973  $url = '/';
974  }
975 
976  $request = $this->_method . ' ' . $url . ' HTTP/' . $this->_http . "\r\n";
977 
978  if (in_array($this->_method, $this->_bodyDisallowed) ||
979  (0 == strlen($this->_body) && (HTTP_REQUEST_METHOD_POST != $this->_method ||
980  (empty($this->_postData) && empty($this->_postFiles)))))
981  {
982  $this->removeHeader('Content-Type');
983  } else {
984  if (empty($this->_requestHeaders['content-type'])) {
985  // Add default content-type
986  $this->addHeader('Content-Type', 'application/x-www-form-urlencoded');
987  } elseif ('multipart/form-data' == $this->_requestHeaders['content-type']) {
988  $boundary = 'HTTP_Request_' . md5(uniqid('request') . microtime());
989  $this->addHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary);
990  }
991  }
992 
993  // Request Headers
994  if (!empty($this->_requestHeaders)) {
995  foreach ($this->_requestHeaders as $name => $value) {
996  $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
997  $request .= $canonicalName . ': ' . $value . "\r\n";
998  }
999  }
1000 
1001  // Method does not allow a body, simply add a final CRLF
1002  if (in_array($this->_method, $this->_bodyDisallowed)) {
1003 
1004  $request .= "\r\n";
1005 
1006  // Post data if it's an array
1007  } elseif (HTTP_REQUEST_METHOD_POST == $this->_method &&
1008  (!empty($this->_postData) || !empty($this->_postFiles))) {
1009 
1010  // "normal" POST request
1011  if (!isset($boundary)) {
1012  $postdata = implode('&', array_map(
1013  create_function('$a', 'return $a[0] . \'=\' . $a[1];'),
1014  $this->_flattenArray('', $this->_postData)
1015  ));
1016 
1017  // multipart request, probably with file uploads
1018  } else {
1019  $postdata = '';
1020  if (!empty($this->_postData)) {
1021  $flatData = $this->_flattenArray('', $this->_postData);
1022  foreach ($flatData as $item) {
1023  $postdata .= '--' . $boundary . "\r\n";
1024  $postdata .= 'Content-Disposition: form-data; name="' . $item[0] . '"';
1025  $postdata .= "\r\n\r\n" . urldecode($item[1]) . "\r\n";
1026  }
1027  }
1028  foreach ($this->_postFiles as $name => $value) {
1029  if (is_array($value['name'])) {
1030  $varname = $name . ($this->_useBrackets? '[]': '');
1031  } else {
1032  $varname = $name;
1033  $value['name'] = array($value['name']);
1034  }
1035  foreach ($value['name'] as $key => $filename) {
1036  $fp = fopen($filename, 'r');
1037  $basename = basename($filename);
1038  $type = is_array($value['type'])? @$value['type'][$key]: $value['type'];
1039 
1040  $postdata .= '--' . $boundary . "\r\n";
1041  $postdata .= 'Content-Disposition: form-data; name="' . $varname . '"; filename="' . $basename . '"';
1042  $postdata .= "\r\nContent-Type: " . $type;
1043  $postdata .= "\r\n\r\n" . fread($fp, filesize($filename)) . "\r\n";
1044  fclose($fp);
1045  }
1046  }
1047  $postdata .= '--' . $boundary . "--\r\n";
1048  }
1049  $request .= 'Content-Length: ' .
1050  (HTTP_REQUEST_MBSTRING? mb_strlen($postdata, 'iso-8859-1'): strlen($postdata)) .
1051  "\r\n\r\n";
1052  $request .= $postdata;
1053 
1054  // Explicitly set request body
1055  } elseif (0 < strlen($this->_body)) {
1056 
1057  $request .= 'Content-Length: ' .
1058  (HTTP_REQUEST_MBSTRING? mb_strlen($this->_body, 'iso-8859-1'): strlen($this->_body)) .
1059  "\r\n\r\n";
1060  $request .= $this->_body;
1061 
1062  // No body: send a Content-Length header nonetheless (request #12900),
1063  // but do that only for methods that require a body (bug #14740)
1064  } else {
1065 
1066  if (in_array($this->_method, $this->_bodyRequired)) {
1067  $request .= "Content-Length: 0\r\n";
1068  }
1069  $request .= "\r\n";
1070  }
1071 
1072  return $request;
1073  }
1074 
1084  function _flattenArray($name, $values)
1085  {
1086  if (!is_array($values)) {
1087  return array(array($name, $values));
1088  } else {
1089  $ret = array();
1090  foreach ($values as $k => $v) {
1091  if (empty($name)) {
1092  $newName = $k;
1093  } elseif ($this->_useBrackets) {
1094  $newName = $name . '[' . $k . ']';
1095  } else {
1096  $newName = $name;
1097  }
1098  $ret = array_merge($ret, $this->_flattenArray($newName, $v));
1099  }
1100  return $ret;
1101  }
1102  }
1103 
1104 
1124  function attach(&$listener)
1125  {
1126  if (!is_a($listener, 'HTTP_Request_Listener')) {
1127  return false;
1128  }
1129  $this->_listeners[$listener->getId()] =& $listener;
1130  return true;
1131  }
1132 
1133 
1141  function detach(&$listener)
1142  {
1143  if (!is_a($listener, 'HTTP_Request_Listener') ||
1144  !isset($this->_listeners[$listener->getId()])) {
1145  return false;
1146  }
1147  unset($this->_listeners[$listener->getId()]);
1148  return true;
1149  }
1150 
1151 
1160  function _notify($event, $data = null)
1161  {
1162  foreach (array_keys($this->_listeners) as $id) {
1163  $this->_listeners[$id]->update($this, $event, $data);
1164  }
1165  }
1166 }
1167 
1168 
1179 {
1184  var $_sock;
1185 
1190  var $_protocol;
1191 
1196  var $_code;
1197 
1202  var $_reason;
1203 
1208  var $_headers;
1209 
1214  var $_cookies;
1215 
1220  var $_body = '';
1221 
1226  var $_chunkLength = 0;
1227 
1232  var $_listeners = array();
1233 
1238  var $_toRead;
1239 
1246  function HTTP_Response(&$sock, &$listeners)
1247  {
1248  $this->_sock =& $sock;
1249  $this->_listeners =& $listeners;
1250  }
1251 
1252 
1268  function process($saveBody = true, $canHaveBody = true)
1269  {
1270  do {
1271  $line = $this->_sock->readLine();
1272  if (!preg_match('!^(HTTP/\d\.\d) (\d{3})(?: (.+))?!', $line, $s)) {
1273  return PEAR::raiseError('Malformed response', HTTP_REQUEST_ERROR_RESPONSE);
1274  } else {
1275  $this->_protocol = $s[1];
1276  $this->_code = intval($s[2]);
1277  $this->_reason = empty($s[3])? null: $s[3];
1278  }
1279  while ('' !== ($header = $this->_sock->readLine())) {
1280  $this->_processHeader($header);
1281  }
1282  } while (100 == $this->_code);
1283 
1284  $this->_notify('gotHeaders', $this->_headers);
1285 
1286  // RFC 2616, section 4.4:
1287  // 1. Any response message which "MUST NOT" include a message-body ...
1288  // is always terminated by the first empty line after the header fields
1289  // 3. ... If a message is received with both a
1290  // Transfer-Encoding header field and a Content-Length header field,
1291  // the latter MUST be ignored.
1292  $canHaveBody = $canHaveBody && $this->_code >= 200 &&
1293  $this->_code != 204 && $this->_code != 304;
1294 
1295  // If response body is present, read it and decode
1296  $chunked = isset($this->_headers['transfer-encoding']) && ('chunked' == $this->_headers['transfer-encoding']);
1297  $gzipped = isset($this->_headers['content-encoding']) && ('gzip' == $this->_headers['content-encoding']);
1298  $hasBody = false;
1299  if ($canHaveBody && ($chunked || !isset($this->_headers['content-length']) ||
1300  0 != $this->_headers['content-length']))
1301  {
1302  if ($chunked || !isset($this->_headers['content-length'])) {
1303  $this->_toRead = null;
1304  } else {
1305  $this->_toRead = $this->_headers['content-length'];
1306  }
1307  while (!$this->_sock->eof() && (is_null($this->_toRead) || 0 < $this->_toRead)) {
1308  if ($chunked) {
1309  $data = $this->_readChunked();
1310  } elseif (is_null($this->_toRead)) {
1311  $data = $this->_sock->read(4096);
1312  } else {
1313  $data = $this->_sock->read(min(4096, $this->_toRead));
1314  $this->_toRead -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data);
1315  }
1316  if ('' == $data && (!$this->_chunkLength || $this->_sock->eof())) {
1317  break;
1318  } else {
1319  $hasBody = true;
1320  if ($saveBody || $gzipped) {
1321  $this->_body .= $data;
1322  }
1323  $this->_notify($gzipped? 'gzTick': 'tick', $data);
1324  }
1325  }
1326  }
1327 
1328  if ($hasBody) {
1329  // Uncompress the body if needed
1330  if ($gzipped) {
1331  $body = $this->_decodeGzip($this->_body);
1332  if (PEAR::isError($body)) {
1333  return $body;
1334  }
1335  $this->_body = $body;
1336  $this->_notify('gotBody', $this->_body);
1337  } else {
1338  $this->_notify('gotBody');
1339  }
1340  }
1341  return true;
1342  }
1343 
1344 
1351  function _processHeader($header)
1352  {
1353  if (false === strpos($header, ':')) {
1354  return;
1355  }
1356  list($headername, $headervalue) = explode(':', $header, 2);
1357  $headername = strtolower($headername);
1358  $headervalue = ltrim($headervalue);
1359 
1360  if ('set-cookie' != $headername) {
1361  if (isset($this->_headers[$headername])) {
1362  $this->_headers[$headername] .= ',' . $headervalue;
1363  } else {
1364  $this->_headers[$headername] = $headervalue;
1365  }
1366  } else {
1367  $this->_parseCookie($headervalue);
1368  }
1369  }
1370 
1371 
1378  function _parseCookie($headervalue)
1379  {
1380  $cookie = array(
1381  'expires' => null,
1382  'domain' => null,
1383  'path' => null,
1384  'secure' => false
1385  );
1386 
1387  // Only a name=value pair
1388  if (!strpos($headervalue, ';')) {
1389  $pos = strpos($headervalue, '=');
1390  $cookie['name'] = trim(substr($headervalue, 0, $pos));
1391  $cookie['value'] = trim(substr($headervalue, $pos + 1));
1392 
1393  // Some optional parameters are supplied
1394  } else {
1395  $elements = explode(';', $headervalue);
1396  $pos = strpos($elements[0], '=');
1397  $cookie['name'] = trim(substr($elements[0], 0, $pos));
1398  $cookie['value'] = trim(substr($elements[0], $pos + 1));
1399 
1400  for ($i = 1; $i < count($elements); $i++) {
1401  if (false === strpos($elements[$i], '=')) {
1402  $elName = trim($elements[$i]);
1403  $elValue = null;
1404  } else {
1405  list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
1406  }
1407  $elName = strtolower($elName);
1408  if ('secure' == $elName) {
1409  $cookie['secure'] = true;
1410  } elseif ('expires' == $elName) {
1411  $cookie['expires'] = str_replace('"', '', $elValue);
1412  } elseif ('path' == $elName || 'domain' == $elName) {
1413  $cookie[$elName] = urldecode($elValue);
1414  } else {
1415  $cookie[$elName] = $elValue;
1416  }
1417  }
1418  }
1419  $this->_cookies[] = $cookie;
1420  }
1421 
1422 
1429  function _readChunked()
1430  {
1431  // at start of the next chunk?
1432  if (0 == $this->_chunkLength) {
1433  $line = $this->_sock->readLine();
1434  if (preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
1435  $this->_chunkLength = hexdec($matches[1]);
1436  // Chunk with zero length indicates the end
1437  if (0 == $this->_chunkLength) {
1438  $this->_sock->readLine(); // make this an eof()
1439  return '';
1440  }
1441  } else {
1442  return '';
1443  }
1444  }
1445  $data = $this->_sock->read($this->_chunkLength);
1446  $this->_chunkLength -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data);
1447  if (0 == $this->_chunkLength) {
1448  $this->_sock->readLine(); // Trailing CRLF
1449  }
1450  return $data;
1451  }
1452 
1453 
1462  function _notify($event, $data = null)
1463  {
1464  foreach (array_keys($this->_listeners) as $id) {
1465  $this->_listeners[$id]->update($this, $event, $data);
1466  }
1467  }
1468 
1469 
1481  function _decodeGzip($data)
1482  {
1483  if (HTTP_REQUEST_MBSTRING) {
1484  $oldEncoding = mb_internal_encoding();
1485  mb_internal_encoding('iso-8859-1');
1486  }
1487  $length = strlen($data);
1488  // If it doesn't look like gzip-encoded data, don't bother
1489  if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
1490  return $data;
1491  }
1492  $method = ord(substr($data, 2, 1));
1493  if (8 != $method) {
1494  return PEAR::raiseError('_decodeGzip(): unknown compression method', HTTP_REQUEST_ERROR_GZIP_METHOD);
1495  }
1496  $flags = ord(substr($data, 3, 1));
1497  if ($flags & 224) {
1498  return PEAR::raiseError('_decodeGzip(): reserved bits are set', HTTP_REQUEST_ERROR_GZIP_DATA);
1499  }
1500 
1501  // header is 10 bytes minimum. may be longer, though.
1502  $headerLength = 10;
1503  // extra fields, need to skip 'em
1504  if ($flags & 4) {
1505  if ($length - $headerLength - 2 < 8) {
1506  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1507  }
1508  $extraLength = unpack('v', substr($data, 10, 2));
1509  if ($length - $headerLength - 2 - $extraLength[1] < 8) {
1510  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1511  }
1512  $headerLength += $extraLength[1] + 2;
1513  }
1514  // file name, need to skip that
1515  if ($flags & 8) {
1516  if ($length - $headerLength - 1 < 8) {
1517  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1518  }
1519  $filenameLength = strpos(substr($data, $headerLength), chr(0));
1520  if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
1521  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1522  }
1523  $headerLength += $filenameLength + 1;
1524  }
1525  // comment, need to skip that also
1526  if ($flags & 16) {
1527  if ($length - $headerLength - 1 < 8) {
1528  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1529  }
1530  $commentLength = strpos(substr($data, $headerLength), chr(0));
1531  if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
1532  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1533  }
1534  $headerLength += $commentLength + 1;
1535  }
1536  // have a CRC for header. let's check
1537  if ($flags & 1) {
1538  if ($length - $headerLength - 2 < 8) {
1539  return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);
1540  }
1541  $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));
1542  $crcStored = unpack('v', substr($data, $headerLength, 2));
1543  if ($crcReal != $crcStored[1]) {
1544  return PEAR::raiseError('_decodeGzip(): header CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC);
1545  }
1546  $headerLength += 2;
1547  }
1548  // unpacked data CRC and size at the end of encoded data
1549  $tmp = unpack('V2', substr($data, -8));
1550  $dataCrc = $tmp[1];
1551  $dataSize = $tmp[2];
1552 
1553  // finally, call the gzinflate() function
1554  // don't pass $dataSize to gzinflate, see bugs #13135, #14370
1555  $unpacked = gzinflate(substr($data, $headerLength, -8));
1556  if (false === $unpacked) {
1557  return PEAR::raiseError('_decodeGzip(): gzinflate() call failed', HTTP_REQUEST_ERROR_GZIP_READ);
1558  } elseif ($dataSize != strlen($unpacked)) {
1559  return PEAR::raiseError('_decodeGzip(): data size check failed', HTTP_REQUEST_ERROR_GZIP_READ);
1560  } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
1561  return PEAR::raiseError('_decodeGzip(): data CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC);
1562  }
1563  if (HTTP_REQUEST_MBSTRING) {
1564  mb_internal_encoding($oldEncoding);
1565  }
1566  return $unpacked;
1567  }
1568 } // End class HTTP_Response
1569 ?>