PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/w3-total-cache/lib/Microsoft/Http/Client.php

https://bitbucket.org/mrmustarde/manhattan-beach
PHP | 1446 lines | 703 code | 186 blank | 557 comment | 167 complexity | 8d6fb70a1e1fe9f163460db9af1080fd MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Microsoft
  16. * @package Microsoft_Http
  17. * @subpackage Client
  18. * @version $Id: Client.php 19661 2009-12-15 18:03:07Z matthew $
  19. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. if (!defined('W3TC')) {
  23. die();
  24. }
  25. /**
  26. * @see Microsoft_Uri
  27. */
  28. require_once 'Microsoft/Uri.php';
  29. /**
  30. * @see Microsoft_Http_Client_Adapter_Interface
  31. */
  32. require_once 'Microsoft/Http/Client/Adapter/Interface.php';
  33. /**
  34. * @see Microsoft_Http_Response
  35. */
  36. require_once 'Microsoft/Http/Response.php';
  37. /**
  38. * @see Microsoft_Http_Response_Stream
  39. */
  40. require_once 'Microsoft/Http/Response/Stream.php';
  41. /**
  42. * Microsoft_Http_Client is an implemetation of an HTTP client in PHP. The client
  43. * supports basic features like sending different HTTP requests and handling
  44. * redirections, as well as more advanced features like proxy settings, HTTP
  45. * authentication and cookie persistance (using a Microsoft_Http_CookieJar object)
  46. *
  47. * @todo Implement proxy settings
  48. * @category Microsoft
  49. * @package Microsoft_Http
  50. * @subpackage Client
  51. * @throws Microsoft_Http_Client_Exception
  52. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  53. * @license http://framework.zend.com/license/new-bsd New BSD License
  54. */
  55. class Microsoft_Http_Client
  56. {
  57. /**
  58. * HTTP request methods
  59. */
  60. const GET = 'GET';
  61. const POST = 'POST';
  62. const PUT = 'PUT';
  63. const HEAD = 'HEAD';
  64. const DELETE = 'DELETE';
  65. const TRACE = 'TRACE';
  66. const OPTIONS = 'OPTIONS';
  67. const CONNECT = 'CONNECT';
  68. const MERGE = 'MERGE';
  69. /**
  70. * Supported HTTP Authentication methods
  71. */
  72. const AUTH_BASIC = 'basic';
  73. //const AUTH_DIGEST = 'digest'; <-- not implemented yet
  74. /**
  75. * HTTP protocol versions
  76. */
  77. const HTTP_1 = '1.1';
  78. const HTTP_0 = '1.0';
  79. /**
  80. * Content attributes
  81. */
  82. const CONTENT_TYPE = 'Content-Type';
  83. const CONTENT_LENGTH = 'Content-Length';
  84. /**
  85. * POST data encoding methods
  86. */
  87. const ENC_URLENCODED = 'application/x-www-form-urlencoded';
  88. const ENC_FORMDATA = 'multipart/form-data';
  89. /**
  90. * Configuration array, set using the constructor or using ::setConfig()
  91. *
  92. * @var array
  93. */
  94. protected $config = array(
  95. 'maxredirects' => 5,
  96. 'strictredirects' => false,
  97. 'useragent' => 'Microsoft_Http_Client',
  98. 'timeout' => 10,
  99. 'adapter' => 'Microsoft_Http_Client_Adapter_Socket',
  100. 'httpversion' => self::HTTP_1,
  101. 'keepalive' => false,
  102. 'storeresponse' => true,
  103. 'strict' => true,
  104. 'output_stream' => false,
  105. );
  106. /**
  107. * The adapter used to preform the actual connection to the server
  108. *
  109. * @var Microsoft_Http_Client_Adapter_Interface
  110. */
  111. protected $adapter = null;
  112. /**
  113. * Request URI
  114. *
  115. * @var Microsoft_Uri_Http
  116. */
  117. protected $uri = null;
  118. /**
  119. * Associative array of request headers
  120. *
  121. * @var array
  122. */
  123. protected $headers = array();
  124. /**
  125. * HTTP request method
  126. *
  127. * @var string
  128. */
  129. protected $method = self::GET;
  130. /**
  131. * Associative array of GET parameters
  132. *
  133. * @var array
  134. */
  135. protected $paramsGet = array();
  136. /**
  137. * Assiciative array of POST parameters
  138. *
  139. * @var array
  140. */
  141. protected $paramsPost = array();
  142. /**
  143. * Request body content type (for POST requests)
  144. *
  145. * @var string
  146. */
  147. protected $enctype = null;
  148. /**
  149. * The raw post data to send. Could be set by setRawData($data, $enctype).
  150. *
  151. * @var string
  152. */
  153. protected $raw_post_data = null;
  154. /**
  155. * HTTP Authentication settings
  156. *
  157. * Expected to be an associative array with this structure:
  158. * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
  159. * Where 'type' should be one of the supported authentication types (see the AUTH_*
  160. * constants), for example 'basic' or 'digest'.
  161. *
  162. * If null, no authentication will be used.
  163. *
  164. * @var array|null
  165. */
  166. protected $auth;
  167. /**
  168. * File upload arrays (used in POST requests)
  169. *
  170. * An associative array, where each element is of the format:
  171. * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
  172. *
  173. * @var array
  174. */
  175. protected $files = array();
  176. /**
  177. * The client's cookie jar
  178. *
  179. * @var Microsoft_Http_CookieJar
  180. */
  181. protected $cookiejar = null;
  182. /**
  183. * The last HTTP request sent by the client, as string
  184. *
  185. * @var string
  186. */
  187. protected $last_request = null;
  188. /**
  189. * The last HTTP response received by the client
  190. *
  191. * @var Microsoft_Http_Response
  192. */
  193. protected $last_response = null;
  194. /**
  195. * Redirection counter
  196. *
  197. * @var int
  198. */
  199. protected $redirectCounter = 0;
  200. /**
  201. * Fileinfo magic database resource
  202. *
  203. * This varaiable is populated the first time _detectFileMimeType is called
  204. * and is then reused on every call to this method
  205. *
  206. * @var resource
  207. */
  208. static protected $_fileInfoDb = null;
  209. /**
  210. * Contructor method. Will create a new HTTP client. Accepts the target
  211. * URL and optionally configuration array.
  212. *
  213. * @param Microsoft_Uri_Http|string $uri
  214. * @param array $config Configuration key-value pairs.
  215. */
  216. public function __construct($uri = null, $config = null)
  217. {
  218. if ($uri !== null) {
  219. $this->setUri($uri);
  220. }
  221. if ($config !== null) {
  222. $this->setConfig($config);
  223. }
  224. }
  225. /**
  226. * Set the URI for the next request
  227. *
  228. * @param Microsoft_Uri_Http|string $uri
  229. * @return Microsoft_Http_Client
  230. * @throws Microsoft_Http_Client_Exception
  231. */
  232. public function setUri($uri)
  233. {
  234. if (is_string($uri)) {
  235. $uri = Microsoft_Uri::factory($uri);
  236. }
  237. if (!$uri instanceof Microsoft_Uri_Http) {
  238. /** @see Microsoft_Http_Client_Exception */
  239. require_once 'Microsoft/Http/Client/Exception.php';
  240. throw new Microsoft_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
  241. }
  242. // Set auth if username and password has been specified in the uri
  243. if ($uri->getUsername() && $uri->getPassword()) {
  244. $this->setAuth($uri->getUsername(), $uri->getPassword());
  245. }
  246. // We have no ports, set the defaults
  247. if (! $uri->getPort()) {
  248. $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
  249. }
  250. $this->uri = $uri;
  251. return $this;
  252. }
  253. /**
  254. * Get the URI for the next request
  255. *
  256. * @param boolean $as_string If true, will return the URI as a string
  257. * @return Microsoft_Uri_Http|string
  258. */
  259. public function getUri($as_string = false)
  260. {
  261. if ($as_string && $this->uri instanceof Microsoft_Uri_Http) {
  262. return $this->uri->__toString();
  263. } else {
  264. return $this->uri;
  265. }
  266. }
  267. /**
  268. * Set configuration parameters for this HTTP client
  269. *
  270. * @param Microsoft_Config | array $config
  271. * @return Microsoft_Http_Client
  272. * @throws Microsoft_Http_Client_Exception
  273. */
  274. public function setConfig($config = array())
  275. {
  276. if ($config instanceof Microsoft_Config) {
  277. $config = $config->toArray();
  278. } elseif (! is_array($config)) {
  279. /** @see Microsoft_Http_Client_Exception */
  280. require_once 'Microsoft/Http/Client/Exception.php';
  281. throw new Microsoft_Http_Client_Exception('Array expected, got ' . gettype($config));
  282. }
  283. foreach ($config as $k => $v) {
  284. $this->config[strtolower($k)] = $v;
  285. }
  286. // Pass configuration options to the adapter if it exists
  287. if ($this->adapter instanceof Microsoft_Http_Client_Adapter_Interface) {
  288. $this->adapter->setConfig($config);
  289. }
  290. return $this;
  291. }
  292. /**
  293. * Set the next request's method
  294. *
  295. * Validated the passed method and sets it. If we have files set for
  296. * POST requests, and the new method is not POST, the files are silently
  297. * dropped.
  298. *
  299. * @param string $method
  300. * @return Microsoft_Http_Client
  301. * @throws Microsoft_Http_Client_Exception
  302. */
  303. public function setMethod($method = self::GET)
  304. {
  305. if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
  306. /** @see Microsoft_Http_Client_Exception */
  307. require_once 'Microsoft/Http/Client/Exception.php';
  308. throw new Microsoft_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
  309. }
  310. if ($method == self::POST && $this->enctype === null) {
  311. $this->setEncType(self::ENC_URLENCODED);
  312. }
  313. $this->method = $method;
  314. return $this;
  315. }
  316. /**
  317. * Set one or more request headers
  318. *
  319. * This function can be used in several ways to set the client's request
  320. * headers:
  321. * 1. By providing two parameters: $name as the header to set (eg. 'Host')
  322. * and $value as it's value (eg. 'www.example.com').
  323. * 2. By providing a single header string as the only parameter
  324. * eg. 'Host: www.example.com'
  325. * 3. By providing an array of headers as the first parameter
  326. * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
  327. * the function will call itself recursively for each array item.
  328. *
  329. * @param string|array $name Header name, full header string ('Header: value')
  330. * or an array of headers
  331. * @param mixed $value Header value or null
  332. * @return Microsoft_Http_Client
  333. * @throws Microsoft_Http_Client_Exception
  334. */
  335. public function setHeaders($name, $value = null)
  336. {
  337. // If we got an array, go recusive!
  338. if (is_array($name)) {
  339. foreach ($name as $k => $v) {
  340. if (is_string($k)) {
  341. $this->setHeaders($k, $v);
  342. } else {
  343. $this->setHeaders($v, null);
  344. }
  345. }
  346. } else {
  347. // Check if $name needs to be split
  348. if ($value === null && (strpos($name, ':') > 0)) {
  349. list($name, $value) = explode(':', $name, 2);
  350. }
  351. // Make sure the name is valid if we are in strict mode
  352. if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
  353. /** @see Microsoft_Http_Client_Exception */
  354. require_once 'Microsoft/Http/Client/Exception.php';
  355. throw new Microsoft_Http_Client_Exception("{$name} is not a valid HTTP header name");
  356. }
  357. $normalized_name = strtolower($name);
  358. // If $value is null or false, unset the header
  359. if ($value === null || $value === false) {
  360. unset($this->headers[$normalized_name]);
  361. // Else, set the header
  362. } else {
  363. // Header names are stored lowercase internally.
  364. if (is_string($value)) {
  365. $value = trim($value);
  366. }
  367. $this->headers[$normalized_name] = array($name, $value);
  368. }
  369. }
  370. return $this;
  371. }
  372. /**
  373. * Get the value of a specific header
  374. *
  375. * Note that if the header has more than one value, an array
  376. * will be returned.
  377. *
  378. * @param string $key
  379. * @return string|array|null The header value or null if it is not set
  380. */
  381. public function getHeader($key)
  382. {
  383. $key = strtolower($key);
  384. if (isset($this->headers[$key])) {
  385. return $this->headers[$key][1];
  386. } else {
  387. return null;
  388. }
  389. }
  390. /**
  391. * Set a GET parameter for the request. Wrapper around _setParameter
  392. *
  393. * @param string|array $name
  394. * @param string $value
  395. * @return Microsoft_Http_Client
  396. */
  397. public function setParameterGet($name, $value = null)
  398. {
  399. if (is_array($name)) {
  400. foreach ($name as $k => $v)
  401. $this->_setParameter('GET', $k, $v);
  402. } else {
  403. $this->_setParameter('GET', $name, $value);
  404. }
  405. return $this;
  406. }
  407. /**
  408. * Set a POST parameter for the request. Wrapper around _setParameter
  409. *
  410. * @param string|array $name
  411. * @param string $value
  412. * @return Microsoft_Http_Client
  413. */
  414. public function setParameterPost($name, $value = null)
  415. {
  416. if (is_array($name)) {
  417. foreach ($name as $k => $v)
  418. $this->_setParameter('POST', $k, $v);
  419. } else {
  420. $this->_setParameter('POST', $name, $value);
  421. }
  422. return $this;
  423. }
  424. /**
  425. * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
  426. *
  427. * @param string $type GET or POST
  428. * @param string $name
  429. * @param string $value
  430. * @return null
  431. */
  432. protected function _setParameter($type, $name, $value)
  433. {
  434. $parray = array();
  435. $type = strtolower($type);
  436. switch ($type) {
  437. case 'get':
  438. $parray = &$this->paramsGet;
  439. break;
  440. case 'post':
  441. $parray = &$this->paramsPost;
  442. break;
  443. }
  444. if ($value === null) {
  445. if (isset($parray[$name])) unset($parray[$name]);
  446. } else {
  447. $parray[$name] = $value;
  448. }
  449. }
  450. /**
  451. * Get the number of redirections done on the last request
  452. *
  453. * @return int
  454. */
  455. public function getRedirectionsCount()
  456. {
  457. return $this->redirectCounter;
  458. }
  459. /**
  460. * Set HTTP authentication parameters
  461. *
  462. * $type should be one of the supported types - see the self::AUTH_*
  463. * constants.
  464. *
  465. * To enable authentication:
  466. * <code>
  467. * $this->setAuth('shahar', 'secret', Microsoft_Http_Client::AUTH_BASIC);
  468. * </code>
  469. *
  470. * To disable authentication:
  471. * <code>
  472. * $this->setAuth(false);
  473. * </code>
  474. *
  475. * @see http://www.faqs.org/rfcs/rfc2617.html
  476. * @param string|false $user User name or false disable authentication
  477. * @param string $password Password
  478. * @param string $type Authentication type
  479. * @return Microsoft_Http_Client
  480. * @throws Microsoft_Http_Client_Exception
  481. */
  482. public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
  483. {
  484. // If we got false or null, disable authentication
  485. if ($user === false || $user === null) {
  486. $this->auth = null;
  487. // Clear the auth information in the uri instance as well
  488. if ($this->uri instanceof Microsoft_Uri_Http) {
  489. $this->getUri()->setUsername('');
  490. $this->getUri()->setPassword('');
  491. }
  492. // Else, set up authentication
  493. } else {
  494. // Check we got a proper authentication type
  495. if (! defined('self::AUTH_' . strtoupper($type))) {
  496. /** @see Microsoft_Http_Client_Exception */
  497. require_once 'Microsoft/Http/Client/Exception.php';
  498. throw new Microsoft_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
  499. }
  500. $this->auth = array(
  501. 'user' => (string) $user,
  502. 'password' => (string) $password,
  503. 'type' => $type
  504. );
  505. }
  506. return $this;
  507. }
  508. /**
  509. * Set the HTTP client's cookie jar.
  510. *
  511. * A cookie jar is an object that holds and maintains cookies across HTTP requests
  512. * and responses.
  513. *
  514. * @param Microsoft_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
  515. * @return Microsoft_Http_Client
  516. * @throws Microsoft_Http_Client_Exception
  517. */
  518. public function setCookieJar($cookiejar = true)
  519. {
  520. if (! class_exists('Microsoft_Http_CookieJar')) {
  521. require_once 'Microsoft/Http/CookieJar.php';
  522. }
  523. if ($cookiejar instanceof Microsoft_Http_CookieJar) {
  524. $this->cookiejar = $cookiejar;
  525. } elseif ($cookiejar === true) {
  526. $this->cookiejar = new Microsoft_Http_CookieJar();
  527. } elseif (! $cookiejar) {
  528. $this->cookiejar = null;
  529. } else {
  530. /** @see Microsoft_Http_Client_Exception */
  531. require_once 'Microsoft/Http/Client/Exception.php';
  532. throw new Microsoft_Http_Client_Exception('Invalid parameter type passed as CookieJar');
  533. }
  534. return $this;
  535. }
  536. /**
  537. * Return the current cookie jar or null if none.
  538. *
  539. * @return Microsoft_Http_CookieJar|null
  540. */
  541. public function getCookieJar()
  542. {
  543. return $this->cookiejar;
  544. }
  545. /**
  546. * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  547. * will be added directly to the headers array as "Cookie" headers.
  548. *
  549. * @param Microsoft_Http_Cookie|string $cookie
  550. * @param string|null $value If "cookie" is a string, this is the cookie value.
  551. * @return Microsoft_Http_Client
  552. * @throws Microsoft_Http_Client_Exception
  553. */
  554. public function setCookie($cookie, $value = null)
  555. {
  556. if (! class_exists('Microsoft_Http_Cookie')) {
  557. require_once 'Microsoft/Http/Cookie.php';
  558. }
  559. if (is_array($cookie)) {
  560. foreach ($cookie as $c => $v) {
  561. if (is_string($c)) {
  562. $this->setCookie($c, $v);
  563. } else {
  564. $this->setCookie($v);
  565. }
  566. }
  567. return $this;
  568. }
  569. if ($value !== null) {
  570. $value = urlencode($value);
  571. }
  572. if (isset($this->cookiejar)) {
  573. if ($cookie instanceof Microsoft_Http_Cookie) {
  574. $this->cookiejar->addCookie($cookie);
  575. } elseif (is_string($cookie) && $value !== null) {
  576. $cookie = Microsoft_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
  577. $this->cookiejar->addCookie($cookie);
  578. }
  579. } else {
  580. if ($cookie instanceof Microsoft_Http_Cookie) {
  581. $name = $cookie->getName();
  582. $value = $cookie->getValue();
  583. $cookie = $name;
  584. }
  585. if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
  586. /** @see Microsoft_Http_Client_Exception */
  587. require_once 'Microsoft/Http/Client/Exception.php';
  588. throw new Microsoft_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
  589. }
  590. $value = addslashes($value);
  591. if (! isset($this->headers['cookie'])) {
  592. $this->headers['cookie'] = array('Cookie', '');
  593. }
  594. $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
  595. }
  596. return $this;
  597. }
  598. /**
  599. * Set a file to upload (using a POST request)
  600. *
  601. * Can be used in two ways:
  602. *
  603. * 1. $data is null (default): $filename is treated as the name if a local file which
  604. * will be read and sent. Will try to guess the content type using mime_content_type().
  605. * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
  606. * contents and no file is read from the file system. In this case, you need to
  607. * manually set the Content-Type ($ctype) or it will default to
  608. * application/octet-stream.
  609. *
  610. * @param string $filename Name of file to upload, or name to save as
  611. * @param string $formname Name of form element to send as
  612. * @param string $data Data to send (if null, $filename is read and sent)
  613. * @param string $ctype Content type to use (if $data is set and $ctype is
  614. * null, will be application/octet-stream)
  615. * @return Microsoft_Http_Client
  616. * @throws Microsoft_Http_Client_Exception
  617. */
  618. public function setFileUpload($filename, $formname, $data = null, $ctype = null)
  619. {
  620. if ($data === null) {
  621. if (($data = @file_get_contents($filename)) === false) {
  622. /** @see Microsoft_Http_Client_Exception */
  623. require_once 'Microsoft/Http/Client/Exception.php';
  624. throw new Microsoft_Http_Client_Exception("Unable to read file '{$filename}' for upload");
  625. }
  626. if (! $ctype) {
  627. $ctype = $this->_detectFileMimeType($filename);
  628. }
  629. }
  630. // Force enctype to multipart/form-data
  631. $this->setEncType(self::ENC_FORMDATA);
  632. $this->files[] = array(
  633. 'formname' => $formname,
  634. 'filename' => basename($filename),
  635. 'ctype' => $ctype,
  636. 'data' => $data
  637. );
  638. return $this;
  639. }
  640. /**
  641. * Set the encoding type for POST data
  642. *
  643. * @param string $enctype
  644. * @return Microsoft_Http_Client
  645. */
  646. public function setEncType($enctype = self::ENC_URLENCODED)
  647. {
  648. $this->enctype = $enctype;
  649. return $this;
  650. }
  651. /**
  652. * Set the raw (already encoded) POST data.
  653. *
  654. * This function is here for two reasons:
  655. * 1. For advanced user who would like to set their own data, already encoded
  656. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  657. * this method will be used to set the encoded data.
  658. *
  659. * $data can also be stream (such as file) from which the data will be read.
  660. *
  661. * @param string|resource $data
  662. * @param string $enctype
  663. * @return Microsoft_Http_Client
  664. */
  665. public function setRawData($data, $enctype = null)
  666. {
  667. $this->raw_post_data = $data;
  668. $this->setEncType($enctype);
  669. if (is_resource($data)) {
  670. // We've got stream data
  671. $stat = @fstat($data);
  672. if($stat) {
  673. $this->setHeaders(self::CONTENT_LENGTH, $stat['size']);
  674. }
  675. }
  676. return $this;
  677. }
  678. /**
  679. * Clear all GET and POST parameters
  680. *
  681. * Should be used to reset the request parameters if the client is
  682. * used for several concurrent requests.
  683. *
  684. * clearAll parameter controls if we clean just parameters or also
  685. * headers and last_*
  686. *
  687. * @param bool $clearAll Should all data be cleared?
  688. * @return Microsoft_Http_Client
  689. */
  690. public function resetParameters($clearAll = false)
  691. {
  692. // Reset parameter data
  693. $this->paramsGet = array();
  694. $this->paramsPost = array();
  695. $this->files = array();
  696. $this->raw_post_data = null;
  697. if($clearAll) {
  698. $this->headers = array();
  699. $this->last_request = null;
  700. $this->last_response = null;
  701. } else {
  702. // Clear outdated headers
  703. if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
  704. unset($this->headers[strtolower(self::CONTENT_TYPE)]);
  705. }
  706. if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
  707. unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
  708. }
  709. }
  710. return $this;
  711. }
  712. /**
  713. * Get the last HTTP request as string
  714. *
  715. * @return string
  716. */
  717. public function getLastRequest()
  718. {
  719. return $this->last_request;
  720. }
  721. /**
  722. * Get the last HTTP response received by this client
  723. *
  724. * If $config['storeresponse'] is set to false, or no response was
  725. * stored yet, will return null
  726. *
  727. * @return Microsoft_Http_Response or null if none
  728. */
  729. public function getLastResponse()
  730. {
  731. return $this->last_response;
  732. }
  733. /**
  734. * Load the connection adapter
  735. *
  736. * While this method is not called more than one for a client, it is
  737. * seperated from ->request() to preserve logic and readability
  738. *
  739. * @param Microsoft_Http_Client_Adapter_Interface|string $adapter
  740. * @return null
  741. * @throws Microsoft_Http_Client_Exception
  742. */
  743. public function setAdapter($adapter)
  744. {
  745. if (is_string($adapter)) {
  746. if (!class_exists($adapter)) {
  747. @require_once( str_replace('_', '/', $adapter) . '.php' );
  748. }
  749. $adapter = new $adapter;
  750. }
  751. if (! $adapter instanceof Microsoft_Http_Client_Adapter_Interface) {
  752. /** @see Microsoft_Http_Client_Exception */
  753. require_once 'Microsoft/Http/Client/Exception.php';
  754. throw new Microsoft_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  755. }
  756. $this->adapter = $adapter;
  757. $config = $this->config;
  758. unset($config['adapter']);
  759. $this->adapter->setConfig($config);
  760. }
  761. /**
  762. * Load the connection adapter
  763. *
  764. * @return Microsoft_Http_Client_Adapter_Interface $adapter
  765. */
  766. public function getAdapter()
  767. {
  768. return $this->adapter;
  769. }
  770. /**
  771. * Set streaming for received data
  772. *
  773. * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming
  774. * @return Microsoft_Http_Client
  775. */
  776. public function setStream($streamfile = true)
  777. {
  778. $this->setConfig(array("output_stream" => $streamfile));
  779. return $this;
  780. }
  781. /**
  782. * Get status of streaming for received data
  783. * @return boolean|string
  784. */
  785. public function getStream()
  786. {
  787. return $this->config["output_stream"];
  788. }
  789. /**
  790. * Create temporary stream
  791. *
  792. * @return resource
  793. */
  794. protected function _openTempStream()
  795. {
  796. $this->_stream_name = $this->config['output_stream'];
  797. if(!is_string($this->_stream_name)) {
  798. // If name is not given, create temp name
  799. $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(),
  800. 'Microsoft_Http_Client');
  801. }
  802. $fp = fopen($this->_stream_name, "w+b");
  803. if(!$fp) {
  804. $this->close();
  805. require_once 'Microsoft/Http/Client/Exception.php';
  806. throw new Microsoft_Http_Client_Exception("Could not open temp file $name");
  807. }
  808. return $fp;
  809. }
  810. /**
  811. * Send the HTTP request and return an HTTP response object
  812. *
  813. * @param string $method
  814. * @return Microsoft_Http_Response
  815. * @throws Microsoft_Http_Client_Exception
  816. */
  817. public function request($method = null)
  818. {
  819. if (! $this->uri instanceof Microsoft_Uri_Http) {
  820. /** @see Microsoft_Http_Client_Exception */
  821. require_once 'Microsoft/Http/Client/Exception.php';
  822. throw new Microsoft_Http_Client_Exception('No valid URI has been passed to the client');
  823. }
  824. if ($method) {
  825. $this->setMethod($method);
  826. }
  827. $this->redirectCounter = 0;
  828. $response = null;
  829. // Make sure the adapter is loaded
  830. if ($this->adapter == null) {
  831. $this->setAdapter($this->config['adapter']);
  832. }
  833. // Send the first request. If redirected, continue.
  834. do {
  835. // Clone the URI and add the additional GET parameters to it
  836. $uri = clone $this->uri;
  837. if (! empty($this->paramsGet)) {
  838. $query = $uri->getQuery();
  839. if (! empty($query)) {
  840. $query .= '&';
  841. }
  842. $query .= http_build_query($this->paramsGet, null, '&');
  843. $uri->setQuery($query);
  844. }
  845. $body = $this->_prepareBody();
  846. $headers = $this->_prepareHeaders();
  847. // check that adapter supports streaming before using it
  848. if(is_resource($body) && !($this->adapter instanceof Microsoft_Http_Client_Adapter_Stream)) {
  849. /** @see Microsoft_Http_Client_Exception */
  850. require_once 'Microsoft/Http/Client/Exception.php';
  851. throw new Microsoft_Http_Client_Exception('Adapter does not support streaming');
  852. }
  853. // Open the connection, send the request and read the response
  854. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  855. ($uri->getScheme() == 'https' ? true : false));
  856. if($this->config['output_stream']) {
  857. if($this->adapter instanceof Microsoft_Http_Client_Adapter_Stream) {
  858. $stream = $this->_openTempStream();
  859. $this->adapter->setOutputStream($stream);
  860. } else {
  861. /** @see Microsoft_Http_Client_Exception */
  862. require_once 'Microsoft/Http/Client/Exception.php';
  863. throw new Microsoft_Http_Client_Exception('Adapter does not support streaming');
  864. }
  865. }
  866. $this->last_request = $this->adapter->write($this->method,
  867. $uri, $this->config['httpversion'], $headers, $body);
  868. $response = $this->adapter->read();
  869. if (! $response) {
  870. /** @see Microsoft_Http_Client_Exception */
  871. require_once 'Microsoft/Http/Client/Exception.php';
  872. throw new Microsoft_Http_Client_Exception('Unable to read response, or response is empty');
  873. }
  874. if($this->config['output_stream']) {
  875. rewind($stream);
  876. // cleanup the adapter
  877. $this->adapter->setOutputStream(null);
  878. $response = Microsoft_Http_Response_Stream::fromStream($response, $stream);
  879. $response->setStreamName($this->_stream_name);
  880. if(!is_string($this->config['output_stream'])) {
  881. // we used temp name, will need to clean up
  882. $response->setCleanup(true);
  883. }
  884. } else {
  885. $response = Microsoft_Http_Response::fromString($response);
  886. }
  887. if ($this->config['storeresponse']) {
  888. $this->last_response = $response;
  889. }
  890. // Load cookies into cookie jar
  891. if (isset($this->cookiejar)) {
  892. $this->cookiejar->addCookiesFromResponse($response, $uri);
  893. }
  894. // If we got redirected, look for the Location header
  895. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  896. // Check whether we send the exact same request again, or drop the parameters
  897. // and send a GET request
  898. if ($response->getStatus() == 303 ||
  899. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  900. $response->getStatus() == 301))) {
  901. $this->resetParameters();
  902. $this->setMethod(self::GET);
  903. }
  904. // If we got a well formed absolute URI
  905. if (Microsoft_Uri_Http::check($location)) {
  906. $this->setHeaders('host', null);
  907. $this->setUri($location);
  908. } else {
  909. // Split into path and query and set the query
  910. if (strpos($location, '?') !== false) {
  911. list($location, $query) = explode('?', $location, 2);
  912. } else {
  913. $query = '';
  914. }
  915. $this->uri->setQuery($query);
  916. // Else, if we got just an absolute path, set it
  917. if(strpos($location, '/') === 0) {
  918. $this->uri->setPath($location);
  919. // Else, assume we have a relative path
  920. } else {
  921. // Get the current path directory, removing any trailing slashes
  922. $path = $this->uri->getPath();
  923. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  924. $this->uri->setPath($path . '/' . $location);
  925. }
  926. }
  927. ++$this->redirectCounter;
  928. } else {
  929. // If we didn't get any location, stop redirecting
  930. break;
  931. }
  932. } while ($this->redirectCounter < $this->config['maxredirects']);
  933. return $response;
  934. }
  935. /**
  936. * Prepare the request headers
  937. *
  938. * @return array
  939. */
  940. protected function _prepareHeaders()
  941. {
  942. $headers = array();
  943. // Set the host header
  944. if (! isset($this->headers['host'])) {
  945. $host = $this->uri->getHost();
  946. // If the port is not default, add it
  947. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  948. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  949. $host .= ':' . $this->uri->getPort();
  950. }
  951. $headers[] = "Host: {$host}";
  952. }
  953. // Set the connection header
  954. if (! isset($this->headers['connection'])) {
  955. if (! $this->config['keepalive']) {
  956. $headers[] = "Connection: close";
  957. }
  958. }
  959. // Set the Accept-encoding header if not set - depending on whether
  960. // zlib is available or not.
  961. if (! isset($this->headers['accept-encoding'])) {
  962. if (function_exists('gzinflate')) {
  963. $headers[] = 'Accept-encoding: gzip, deflate';
  964. } else {
  965. $headers[] = 'Accept-encoding: identity';
  966. }
  967. }
  968. // Set the Content-Type header
  969. if ($this->method == self::POST &&
  970. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  971. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  972. }
  973. // Set the user agent header
  974. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  975. $headers[] = "User-Agent: {$this->config['useragent']}";
  976. }
  977. // Set HTTP authentication if needed
  978. if (is_array($this->auth)) {
  979. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  980. $headers[] = "Authorization: {$auth}";
  981. }
  982. // Load cookies from cookie jar
  983. if (isset($this->cookiejar)) {
  984. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  985. true, Microsoft_Http_CookieJar::COOKIE_STRING_CONCAT);
  986. if ($cookstr) {
  987. $headers[] = "Cookie: {$cookstr}";
  988. }
  989. }
  990. // Add all other user defined headers
  991. foreach ($this->headers as $header) {
  992. list($name, $value) = $header;
  993. if (is_array($value)) {
  994. $value = implode(', ', $value);
  995. }
  996. $headers[] = "$name: $value";
  997. }
  998. return $headers;
  999. }
  1000. /**
  1001. * Prepare the request body (for POST and PUT requests)
  1002. *
  1003. * @return string
  1004. * @throws Microsoft_Http_Client_Exception
  1005. */
  1006. protected function _prepareBody()
  1007. {
  1008. // According to RFC2616, a TRACE request should not have a body.
  1009. if ($this->method == self::TRACE) {
  1010. return '';
  1011. }
  1012. if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) {
  1013. return $this->raw_post_data;
  1014. }
  1015. // If mbstring overloads substr and strlen functions, we have to
  1016. // override it's internal encoding
  1017. if (function_exists('mb_internal_encoding') &&
  1018. ((int) ini_get('mbstring.func_overload')) & 2) {
  1019. $mbIntEnc = mb_internal_encoding();
  1020. mb_internal_encoding('ASCII');
  1021. }
  1022. // If we have raw_post_data set, just use it as the body.
  1023. if (isset($this->raw_post_data)) {
  1024. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  1025. if (isset($mbIntEnc)) {
  1026. mb_internal_encoding($mbIntEnc);
  1027. }
  1028. return $this->raw_post_data;
  1029. }
  1030. $body = '';
  1031. // If we have files to upload, force enctype to multipart/form-data
  1032. if (count ($this->files) > 0) {
  1033. $this->setEncType(self::ENC_FORMDATA);
  1034. }
  1035. // If we have POST parameters or files, encode and add them to the body
  1036. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  1037. switch($this->enctype) {
  1038. case self::ENC_FORMDATA:
  1039. // Encode body as multipart/form-data
  1040. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  1041. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  1042. // Get POST parameters and encode them
  1043. $params = self::_flattenParametersArray($this->paramsPost);
  1044. foreach ($params as $pp) {
  1045. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  1046. }
  1047. // Encode files
  1048. foreach ($this->files as $file) {
  1049. $fhead = array(self::CONTENT_TYPE => $file['ctype']);
  1050. $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
  1051. }
  1052. $body .= "--{$boundary}--\r\n";
  1053. break;
  1054. case self::ENC_URLENCODED:
  1055. // Encode body as application/x-www-form-urlencoded
  1056. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  1057. $body = http_build_query($this->paramsPost, '', '&');
  1058. break;
  1059. default:
  1060. if (isset($mbIntEnc)) {
  1061. mb_internal_encoding($mbIntEnc);
  1062. }
  1063. /** @see Microsoft_Http_Client_Exception */
  1064. require_once 'Microsoft/Http/Client/Exception.php';
  1065. throw new Microsoft_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  1066. " Please use Microsoft_Http_Client::setRawData to send this kind of content.");
  1067. break;
  1068. }
  1069. }
  1070. // Set the Content-Length if we have a body or if request is POST/PUT
  1071. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  1072. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  1073. }
  1074. if (isset($mbIntEnc)) {
  1075. mb_internal_encoding($mbIntEnc);
  1076. }
  1077. return $body;
  1078. }
  1079. /**
  1080. * Helper method that gets a possibly multi-level parameters array (get or
  1081. * post) and flattens it.
  1082. *
  1083. * The method returns an array of (key, value) pairs (because keys are not
  1084. * necessarily unique. If one of the parameters in as array, it will also
  1085. * add a [] suffix to the key.
  1086. *
  1087. * This method is deprecated since Zend Framework 1.9 in favour of
  1088. * self::_flattenParametersArray() and will be dropped in 2.0
  1089. *
  1090. * @deprecated since 1.9
  1091. *
  1092. * @param array $parray The parameters array
  1093. * @param bool $urlencode Whether to urlencode the name and value
  1094. * @return array
  1095. */
  1096. protected function _getParametersRecursive($parray, $urlencode = false)
  1097. {
  1098. // Issue a deprecated notice
  1099. trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
  1100. E_USER_NOTICE);
  1101. if (! is_array($parray)) {
  1102. return $parray;
  1103. }
  1104. $parameters = array();
  1105. foreach ($parray as $name => $value) {
  1106. if ($urlencode) {
  1107. $name = urlencode($name);
  1108. }
  1109. // If $value is an array, iterate over it
  1110. if (is_array($value)) {
  1111. $name .= ($urlencode ? '%5B%5D' : '[]');
  1112. foreach ($value as $subval) {
  1113. if ($urlencode) {
  1114. $subval = urlencode($subval);
  1115. }
  1116. $parameters[] = array($name, $subval);
  1117. }
  1118. } else {
  1119. if ($urlencode) {
  1120. $value = urlencode($value);
  1121. }
  1122. $parameters[] = array($name, $value);
  1123. }
  1124. }
  1125. return $parameters;
  1126. }
  1127. /**
  1128. * Attempt to detect the MIME type of a file using available extensions
  1129. *
  1130. * This method will try to detect the MIME type of a file. If the fileinfo
  1131. * extension is available, it will be used. If not, the mime_magic
  1132. * extension which is deprected but is still available in many PHP setups
  1133. * will be tried.
  1134. *
  1135. * If neither extension is available, the default application/octet-stream
  1136. * MIME type will be returned
  1137. *
  1138. * @param string $file File path
  1139. * @return string MIME type
  1140. */
  1141. protected function _detectFileMimeType($file)
  1142. {
  1143. $type = null;
  1144. // First try with fileinfo functions
  1145. if (function_exists('finfo_open')) {
  1146. if (self::$_fileInfoDb === null) {
  1147. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1148. }
  1149. if (self::$_fileInfoDb) {
  1150. $type = finfo_file(self::$_fileInfoDb, $file);
  1151. }
  1152. } elseif (function_exists('mime_content_type')) {
  1153. $type = mime_content_type($file);
  1154. }
  1155. // Fallback to the default application/octet-stream
  1156. if (! $type) {
  1157. $type = 'application/octet-stream';
  1158. }
  1159. return $type;
  1160. }
  1161. /**
  1162. * Encode data to a multipart/form-data part suitable for a POST request.
  1163. *
  1164. * @param string $boundary
  1165. * @param string $name
  1166. * @param mixed $value
  1167. * @param string $filename
  1168. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1169. * @return string
  1170. */
  1171. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1172. $ret = "--{$boundary}\r\n" .
  1173. 'Content-Disposition: form-data; name="' . $name .'"';
  1174. if ($filename) {
  1175. $ret .= '; filename="' . $filename . '"';
  1176. }
  1177. $ret .= "\r\n";
  1178. foreach ($headers as $hname => $hvalue) {
  1179. $ret .= "{$hname}: {$hvalue}\r\n";
  1180. }
  1181. $ret .= "\r\n";
  1182. $ret .= "{$value}\r\n";
  1183. return $ret;
  1184. }
  1185. /**
  1186. * Create a HTTP authentication "Authorization:" header according to the
  1187. * specified user, password and authentication method.
  1188. *
  1189. * @see http://www.faqs.org/rfcs/rfc2617.html
  1190. * @param string $user
  1191. * @param string $password
  1192. * @param string $type
  1193. * @return string
  1194. * @throws Microsoft_Http_Client_Exception
  1195. */
  1196. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1197. {
  1198. $authHeader = null;
  1199. switch ($type) {
  1200. case self::AUTH_BASIC:
  1201. // In basic authentication, the user name cannot contain ":"
  1202. if (strpos($user, ':') !== false) {
  1203. /** @see Microsoft_Http_Client_Exception */
  1204. require_once 'Microsoft/Http/Client/Exception.php';
  1205. throw new Microsoft_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1206. }
  1207. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1208. break;
  1209. //case self::AUTH_DIGEST:
  1210. /**
  1211. * @todo Implement digest authentication
  1212. */
  1213. // break;
  1214. default:
  1215. /** @see Microsoft_Http_Client_Exception */
  1216. require_once 'Microsoft/Http/Client/Exception.php';
  1217. throw new Microsoft_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1218. }
  1219. return $authHeader;
  1220. }
  1221. /**
  1222. * Convert an array of parameters into a flat array of (key, value) pairs
  1223. *
  1224. * Will flatten a potentially multi-dimentional array of parameters (such
  1225. * as POST parameters) into a flat array of (key, value) paris. In case
  1226. * of multi-dimentional arrays, square brackets ([]) will be added to the
  1227. * key to indicate an array.
  1228. *
  1229. * @since 1.9
  1230. *
  1231. * @param array $parray
  1232. * @param string $prefix
  1233. * @return array
  1234. */
  1235. static protected function _flattenParametersArray($parray, $prefix = null)
  1236. {
  1237. if (! is_array($parray)) {
  1238. return $parray;
  1239. }
  1240. $parameters = array();
  1241. foreach($parray as $name => $value) {
  1242. // Calculate array key
  1243. if ($prefix) {
  1244. if (is_int($name)) {
  1245. $key = $prefix . '[]';
  1246. } else {
  1247. $key = $prefix . "[$name]";
  1248. }
  1249. } else {
  1250. $key = $name;
  1251. }
  1252. if (is_array($value)) {
  1253. $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
  1254. } else {
  1255. $parameters[] = array($key, $value);
  1256. }
  1257. }
  1258. return $parameters;
  1259. }
  1260. }