PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/concrete/libraries/3rdparty/Zend/Http/Client.php

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