HTTP.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Shane Caraveo <Shane@Caraveo.com> |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: HTTP.php,v 1.39.2.4 2004/01/17 14:00:51 arnaud Exp $
  20. //
  21. /**
  22. * HTTP Transport class
  23. *
  24. * @package SOAP
  25. * @category Web_Services
  26. */
  27. /**
  28. * Needed Classes
  29. */
  30. require_once 'SOAP/Base.php';
  31. /**
  32. * HTTP Transport for SOAP
  33. *
  34. * @access public
  35. * @version $Id: HTTP.php,v 1.39.2.4 2004/01/17 14:00:51 arnaud Exp $
  36. * @package SOAP::Transport::HTTP
  37. * @author Shane Caraveo <shane@php.net>
  38. */
  39. class SOAP_Transport_HTTP extends SOAP_Base
  40. {
  41. /**
  42. * Basic Auth string
  43. *
  44. * @var array
  45. */
  46. var $headers = array();
  47. /**
  48. * Cookies
  49. *
  50. * @var
  51. */
  52. var $cookies;
  53. /**
  54. *
  55. * @var int connection timeout in seconds - 0 = none
  56. */
  57. var $timeout = 4;
  58. /**
  59. * Array containing urlparts - parse_url()
  60. *
  61. * @var mixed
  62. */
  63. var $urlparts = NULL;
  64. /**
  65. * Connection endpoint - URL
  66. *
  67. * @var string
  68. */
  69. var $url = '';
  70. /**
  71. * Incoming payload
  72. *
  73. * @var string
  74. */
  75. var $incoming_payload = '';
  76. /**
  77. * HTTP-Request User-Agent
  78. *
  79. * @var string
  80. */
  81. var $_userAgent = SOAP_LIBRARY_NAME;
  82. /**
  83. * HTTP Encoding
  84. *
  85. * @var string
  86. */
  87. var $encoding = SOAP_DEFAULT_ENCODING;
  88. /**
  89. * HTTP-Response Content-Type encoding
  90. *
  91. * we assume UTF-8 if no encoding is set
  92. * @var string
  93. */
  94. var $result_encoding = 'UTF-8';
  95. /**
  96. * HTTP-Response Content-Type
  97. */
  98. var $result_content_type;
  99. var $result_headers = array();
  100. var $result_cookies = array();
  101. /**
  102. * SOAP_Transport_HTTP Constructor
  103. *
  104. * @param string $URL http url to soap endpoint
  105. *
  106. * @access public
  107. * @param string $URI
  108. * @param string $encoding encoding to use
  109. */
  110. function SOAP_Transport_HTTP($URL, $encoding = SOAP_DEFAULT_ENCODING)
  111. {
  112. parent::SOAP_Base('HTTP');
  113. $this->urlparts = @parse_url($URL);
  114. $this->url = $URL;
  115. $this->encoding = $encoding;
  116. }
  117. /**
  118. * send and receive soap data
  119. *
  120. * @param string outgoing post data
  121. * @param array options
  122. *
  123. * @return string|fault response
  124. * @access public
  125. */
  126. function &send(&$msg, $options = null)
  127. {
  128. if (!$this->_validateUrl()) {
  129. return $this->fault;
  130. }
  131. if (isset($options['timeout']))
  132. $this->timeout = (int)$options['timeout'];
  133. if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0) {
  134. return $this->_sendHTTP($msg, $options);
  135. } else if (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0) {
  136. return $this->_sendHTTPS($msg, $options);
  137. }
  138. return $this->_raiseSoapFault('Invalid url scheme '.$this->url);
  139. }
  140. /**
  141. * set data for http authentication
  142. * creates Authorization header
  143. *
  144. * @param string $username username
  145. * @param string $password response data, minus http headers
  146. *
  147. * @return none
  148. * @access public
  149. */
  150. function setCredentials($username, $password)
  151. {
  152. $this->headers['Authorization'] = 'Basic ' . base64_encode($username . ':' . $password);
  153. }
  154. /**
  155. * Add a cookie
  156. *
  157. * @access public
  158. * @param string $name cookie name
  159. * @param mixed $value cookie value
  160. * @return void
  161. */
  162. function addCookie($name, $value)
  163. {
  164. $this->cookies[$name]=$value;
  165. }
  166. // private methods
  167. /**
  168. * Generates the correct headers for the cookies
  169. *
  170. * @access private
  171. * @return void
  172. */
  173. function _genCookieHeader()
  174. {
  175. foreach ($this->cookies as $name=>$value) {
  176. $cookies = (isset($cookies) ? $cookies. '; ' : '') .
  177. urlencode($name) . '=' . urlencode($value);
  178. }
  179. return $cookies;
  180. }
  181. /**
  182. * validate url data passed to constructor
  183. *
  184. * @access private
  185. * @return boolean
  186. */
  187. function _validateUrl()
  188. {
  189. if ( ! is_array($this->urlparts) ) {
  190. $this->_raiseSoapFault("Unable to parse URL " . $this->url);
  191. return false;
  192. }
  193. if (!isset($this->urlparts['host'])) {
  194. $this->_raiseSoapFault("No host in URL " . $this->url);
  195. return false;
  196. }
  197. if (!isset($this->urlparts['port'])) {
  198. if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0)
  199. $this->urlparts['port'] = 80;
  200. else if (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0)
  201. $this->urlparts['port'] = 443;
  202. }
  203. if (isset($this->urlparts['user'])) {
  204. $this->setCredentials(urldecode($this->urlparts['user']),
  205. urldecode($this->urlparts['pass']));
  206. }
  207. if (!isset($this->urlparts['path']) || !$this->urlparts['path'])
  208. $this->urlparts['path'] = '/';
  209. return true;
  210. }
  211. /**
  212. * Finds out what is the encoding.
  213. *
  214. * Sets the object property accordingly.
  215. *
  216. * @access private
  217. * @param array $headers headers
  218. * @return void
  219. */
  220. function _parseEncoding($headers)
  221. {
  222. $h = stristr($headers,'Content-Type');
  223. preg_match('/^Content-Type:\s*(.*)$/im',$h,$ct);
  224. $this->result_content_type = str_replace("\r","",$ct[1]);
  225. if (preg_match('/(.*?)(?:;\s?charset=)(.*)/i',$this->result_content_type,$m)) {
  226. // strip the string of \r
  227. $this->result_content_type = $m[1];
  228. if (count($m) > 2) {
  229. $enc = strtoupper(str_replace('"',"",$m[2]));
  230. if (in_array($enc, $this->_encodings)) {
  231. $this->result_encoding = $enc;
  232. }
  233. }
  234. }
  235. // deal with broken servers that don't set content type on faults
  236. if (!$this->result_content_type) $this->result_content_type = 'text/xml';
  237. }
  238. /**
  239. * Parses the headers
  240. *
  241. * @param array $headers the headers
  242. * @return void
  243. */
  244. function _parseHeaders($headers)
  245. {
  246. /* largely borrowed from HTTP_Request */
  247. $this->result_headers = array();
  248. $headers = split("\r?\n", $headers);
  249. foreach ($headers as $value) {
  250. if (strpos($value,':') === false) {
  251. $this->result_headers[0]=$value;
  252. continue;
  253. }
  254. list($name,$value) = split(':',$value);
  255. $headername = strtolower($name);
  256. $headervalue = trim($value);
  257. $this->result_headers[$headername]=$headervalue;
  258. if ($headername == 'set-cookie') {
  259. // Parse a SetCookie header to fill _cookies array
  260. $cookie = array(
  261. 'expires' => null,
  262. 'domain' => $this->urlparts['host'],
  263. 'path' => null,
  264. 'secure' => false
  265. );
  266. // Only a name=value pair
  267. if (!strpos($headervalue, ';')) {
  268. list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $headervalue));
  269. $cookie['name'] = urldecode($cookie['name']);
  270. $cookie['value'] = urldecode($cookie['value']);
  271. // Some optional parameters are supplied
  272. } else {
  273. $elements = explode(';', $headervalue);
  274. list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $elements[0]));
  275. $cookie['name'] = urldecode($cookie['name']);
  276. $cookie['value'] = urldecode($cookie['value']);
  277. for ($i = 1; $i < count($elements);$i++) {
  278. list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
  279. if ('secure' == $elName) {
  280. $cookie['secure'] = true;
  281. } elseif ('expires' == $elName) {
  282. $cookie['expires'] = str_replace('"', '', $elValue);
  283. } elseif ('path' == $elName OR 'domain' == $elName) {
  284. $cookie[$elName] = urldecode($elValue);
  285. } else {
  286. $cookie[$elName] = $elValue;
  287. }
  288. }
  289. }
  290. $this->result_cookies[] = $cookie;
  291. }
  292. }
  293. }
  294. /**
  295. * Remove http headers from response
  296. *
  297. * @return boolean
  298. * @access private
  299. */
  300. function _parseResponse()
  301. {
  302. if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $this->incoming_payload, $match)) {
  303. #$this->response = preg_replace("/[\r|\n]/", '', $match[2]);
  304. $this->response =& $match[2];
  305. // find the response error, some servers response with 500 for soap faults
  306. $this->_parseHeaders($match[1]);
  307. list($protocol, $code) = sscanf($this->result_headers[0], '%s %s');
  308. unset($this->result_headers[0]);
  309. switch($code) {
  310. case 400:
  311. $this->_raiseSoapFault("HTTP Response $code Bad Request");
  312. return false;
  313. break;
  314. case 401:
  315. $this->_raiseSoapFault("HTTP Response $code Authentication Failed");
  316. return false;
  317. break;
  318. case 403:
  319. $this->_raiseSoapFault("HTTP Response $code Forbidden");
  320. return false;
  321. break;
  322. case 404:
  323. $this->_raiseSoapFault("HTTP Response $code Not Found");
  324. return false;
  325. break;
  326. case 407:
  327. $this->_raiseSoapFault("HTTP Response $code Proxy Authentication Required");
  328. return false;
  329. break;
  330. case 408:
  331. $this->_raiseSoapFault("HTTP Response $code Request Timeout");
  332. return false;
  333. break;
  334. case 410:
  335. $this->_raiseSoapFault("HTTP Response $code Gone");
  336. return false;
  337. break;
  338. default:
  339. if ($code >= 400 && $code < 500) {
  340. $this->_raiseSoapFault("HTTP Response $code Not Found");
  341. return false;
  342. }
  343. }
  344. $this->_parseEncoding($match[1]);
  345. if ($this->result_content_type == 'application/dime') {
  346. // XXX quick hack insertion of DIME
  347. if (PEAR::isError($this->_decodeDIMEMessage($this->response,$this->headers,$this->attachments))) {
  348. // _decodeDIMEMessage already raised $this->fault
  349. return false;
  350. }
  351. $this->result_content_type = $this->headers['content-type'];
  352. } else if (stristr($this->result_content_type,'multipart/related')) {
  353. $this->response = $this->incoming_payload;
  354. if (PEAR::isError($this->_decodeMimeMessage($this->response,$this->headers,$this->attachments))) {
  355. // _decodeMimeMessage already raised $this->fault
  356. return false;
  357. }
  358. } else if ($this->result_content_type != 'text/xml') {
  359. $this->_raiseSoapFault($this->response);
  360. return false;
  361. }
  362. // if no content, return false
  363. return strlen($this->response) > 0;
  364. }
  365. $this->_raiseSoapFault('Invalid HTTP Response');
  366. return false;
  367. }
  368. /**
  369. * Create http request, including headers, for outgoing request
  370. *
  371. * @param string &$msg outgoing SOAP package
  372. * @param $options
  373. * @return string outgoing_payload
  374. * @access private
  375. */
  376. function &_getRequest(&$msg, $options)
  377. {
  378. $action = isset($options['soapaction'])?$options['soapaction']:'';
  379. $fullpath = $this->urlparts['path'].
  380. (isset($this->urlparts['query'])?'?'.$this->urlparts['query']:'').
  381. (isset($this->urlparts['fragment'])?'#'.$this->urlparts['fragment']:'');
  382. if (isset($options['proxy_host'])) {
  383. $fullpath = 'http://' . $this->urlparts['host'] . ':' . $this->urlparts['port'] . $fullpath;
  384. }
  385. if (isset($options['proxy_user'])) {
  386. $this->headers['Proxy-Authorization'] = 'Basic ' . base64_encode($options['proxy_user'].":".$options['proxy_pass']);
  387. }
  388. if (isset($options['user'])) {
  389. $this->setCredentials($options['user'], $options['pass']);
  390. }
  391. $this->headers['User-Agent'] = $this->_userAgent;
  392. $this->headers['Host'] = $this->urlparts['host'];
  393. $this->headers['Content-Type'] = "text/xml; charset=$this->encoding";
  394. $this->headers['Content-Length'] = strlen($msg);
  395. $this->headers['SOAPAction'] = "\"$action\"";
  396. if (isset($options['headers'])) {
  397. $this->headers = array_merge($this->headers, $options['headers']);
  398. }
  399. $this->cookies = array();
  400. if (!isset($options['nocookies']) || !$options['nocookies']) {
  401. // add the cookies we got from the last request
  402. if (isset($this->result_cookies)) {
  403. foreach ($this->result_cookies as $cookie) {
  404. if ($cookie['domain'] == $this->urlparts['host'])
  405. $this->cookies[$cookie['name']]=$cookie['value'];
  406. }
  407. }
  408. }
  409. // add cookies the user wants to set
  410. if (isset($options['cookies'])) {
  411. foreach ($options['cookies'] as $cookie) {
  412. if ($cookie['domain'] == $this->urlparts['host'])
  413. $this->cookies[$cookie['name']]=$cookie['value'];
  414. }
  415. }
  416. if (count($this->cookies)) {
  417. $this->headers['Cookie'] = $this->_genCookieHeader();
  418. }
  419. $headers = '';
  420. foreach ($this->headers as $k => $v) {
  421. $headers .= "$k: $v\r\n";
  422. }
  423. $this->outgoing_payload =
  424. "POST $fullpath HTTP/1.0\r\n".
  425. $headers."\r\n".
  426. $msg;
  427. return $this->outgoing_payload;
  428. }
  429. /**
  430. * Send outgoing request, and read/parse response
  431. *
  432. * @param string &$msg outgoing SOAP package
  433. * @param string $action SOAP Action
  434. * @return string &$response response data, minus http headers
  435. * @access private
  436. */
  437. function &_sendHTTP(&$msg, $options)
  438. {
  439. $this->incoming_payload = '';
  440. $this->_getRequest($msg, $options);
  441. $host = $this->urlparts['host'];
  442. $port = $this->urlparts['port'];
  443. if (isset($options['proxy_host'])) {
  444. $host = $options['proxy_host'];
  445. $port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080;
  446. }
  447. // send
  448. if ($this->timeout > 0) {
  449. $fp = @fsockopen($host, $port, $this->errno, $this->errmsg, $this->timeout);
  450. } else {
  451. $fp = @fsockopen($host, $port, $this->errno, $this->errmsg);
  452. }
  453. if (!$fp) {
  454. return $this->_raiseSoapFault("Connect Error to $host:$port");
  455. }
  456. if ($this->timeout > 0) {
  457. // some builds of php do not support this, silence
  458. // the warning
  459. @socket_set_timeout($fp, $this->timeout);
  460. }
  461. if (!fputs($fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
  462. return $this->_raiseSoapFault("Error POSTing Data to $host");
  463. }
  464. // get reponse
  465. // XXX time consumer
  466. do {
  467. $data = fread($fp, 4096);
  468. $_tmp_status = socket_get_status($fp);
  469. if ($_tmp_status['timed_out']) {
  470. return $this->_raiseSoapFault("Timed out read from $host");
  471. } else {
  472. $this->incoming_payload .= $data;
  473. }
  474. } while (!$_tmp_status['eof']);
  475. fclose($fp);
  476. if (!$this->_parseResponse()) {
  477. return $this->fault;
  478. }
  479. return $this->response;
  480. }
  481. /**
  482. * Send outgoing request, and read/parse response, via HTTPS
  483. *
  484. * @param string &$msg outgoing SOAP package
  485. * @param string $action SOAP Action
  486. * @return string &$response response data, minus http headers
  487. * @access private
  488. */
  489. function &_sendHTTPS(&$msg, $options)
  490. {
  491. /* NOTE This function uses the CURL functions
  492. * Your php must be compiled with CURL
  493. */
  494. if (!extension_loaded('curl')) {
  495. return $this->_raiseSoapFault('CURL Extension is required for HTTPS');
  496. }
  497. // $this->_getRequest($msg, $options);
  498. $ch = curl_init();
  499. // XXX don't know if this proxy stuff is right for CURL
  500. // Arnaud: apparently it is, we have a proxy and it works
  501. // with these lines.
  502. if (isset($options['proxy_host'])) {
  503. // $options['http_proxy'] == 'hostname:port'
  504. $host = $options['proxy_host'];
  505. $port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080;
  506. curl_setopt($ch, CURLOPT_PROXY, $host . ":" . $port);
  507. }
  508. if (isset($options['proxy_user'])) {
  509. // $options['http_proxy_userpw'] == 'username:password'
  510. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $options['proxy_user'] . ':' . $options['proxy_pass']);
  511. }
  512. if (isset($options['user'])) {
  513. curl_setopt($ch, CURLOPT_USERPWD, $options['user'] . ':' . $options['pass']);
  514. }
  515. if (!isset($options['soapaction'])) {
  516. $options['soapaction'] = '';
  517. }
  518. curl_setopt($ch, CURLOPT_HTTPHEADER , array('Content-Type: text/xml;charset=' . $this->encoding, 'SOAPAction: "'.$options['soapaction'].'"'));
  519. curl_setopt($ch, CURLOPT_USERAGENT , $this->_userAgent);
  520. if ($this->timeout) {
  521. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); //times out after 4s
  522. }
  523. curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
  524. curl_setopt($ch, CURLOPT_URL, $this->url);
  525. curl_setopt($ch, CURLOPT_POST, 1);
  526. curl_setopt($ch, CURLOPT_FAILONERROR, 0);
  527. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  528. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  529. curl_setopt($ch, CURLOPT_HEADER, 1);
  530. if (isset($options['curl'])) {
  531. reset($options['curl']);
  532. while (list($key, $val) = each ($options['curl'])) {
  533. curl_setopt($ch, $key, $val);
  534. }
  535. }
  536. $this->incoming_payload = curl_exec($ch);
  537. if (! $this->incoming_payload ) {
  538. $m = 'curl_exec error ' . curl_errno($ch) . ' ' . curl_error($ch);
  539. curl_close($ch);
  540. return $this->_raiseSoapFault($m);
  541. }
  542. curl_close($ch);
  543. if (!$this->_parseResponse()) {
  544. return $this->fault;
  545. }
  546. return $this->response;
  547. }
  548. } // end SOAP_Transport_HTTP
  549. ?>