PageRenderTime 65ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Http/Client.php

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