PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/zend/Zend/Http/Client.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 1460 lines | 711 code | 188 blank | 561 comment | 168 complexity | e2c6ddb4974cd902b0afc41416b8295b MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  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$
  19. * @copyright Copyright (c) 2005-2010 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 implemetation 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 persistance (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-2010 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. );
  108. /**
  109. * The adapter used to preform the actual connection to the server
  110. *
  111. * @var Zend_Http_Client_Adapter_Interface
  112. */
  113. protected $adapter = null;
  114. /**
  115. * Request URI
  116. *
  117. * @var Zend_Uri_Http
  118. */
  119. protected $uri = null;
  120. /**
  121. * Associative array of request headers
  122. *
  123. * @var array
  124. */
  125. protected $headers = array();
  126. /**
  127. * HTTP request method
  128. *
  129. * @var string
  130. */
  131. protected $method = self::GET;
  132. /**
  133. * Associative array of GET parameters
  134. *
  135. * @var array
  136. */
  137. protected $paramsGet = array();
  138. /**
  139. * Assiciative array of POST parameters
  140. *
  141. * @var array
  142. */
  143. protected $paramsPost = array();
  144. /**
  145. * Request body content type (for POST requests)
  146. *
  147. * @var string
  148. */
  149. protected $enctype = null;
  150. /**
  151. * The raw post data to send. Could be set by setRawData($data, $enctype).
  152. *
  153. * @var string
  154. */
  155. protected $raw_post_data = null;
  156. /**
  157. * HTTP Authentication settings
  158. *
  159. * Expected to be an associative array with this structure:
  160. * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
  161. * Where 'type' should be one of the supported authentication types (see the AUTH_*
  162. * constants), for example 'basic' or 'digest'.
  163. *
  164. * If null, no authentication will be used.
  165. *
  166. * @var array|null
  167. */
  168. protected $auth;
  169. /**
  170. * File upload arrays (used in POST requests)
  171. *
  172. * An associative array, where each element is of the format:
  173. * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
  174. *
  175. * @var array
  176. */
  177. protected $files = array();
  178. /**
  179. * The client's cookie jar
  180. *
  181. * @var Zend_Http_CookieJar
  182. */
  183. protected $cookiejar = null;
  184. /**
  185. * The last HTTP request sent by the client, as string
  186. *
  187. * @var string
  188. */
  189. protected $last_request = null;
  190. /**
  191. * The last HTTP response received by the client
  192. *
  193. * @var Zend_Http_Response
  194. */
  195. protected $last_response = null;
  196. /**
  197. * Redirection counter
  198. *
  199. * @var int
  200. */
  201. protected $redirectCounter = 0;
  202. /**
  203. * Fileinfo magic database resource
  204. *
  205. * This varaiable is populated the first time _detectFileMimeType is called
  206. * and is then reused on every call to this method
  207. *
  208. * @var resource
  209. */
  210. static protected $_fileInfoDb = null;
  211. /**
  212. * Contructor method. Will create a new HTTP client. Accepts the target
  213. * URL and optionally configuration array.
  214. *
  215. * @param Zend_Uri_Http|string $uri
  216. * @param array $config Configuration key-value pairs.
  217. */
  218. public function __construct($uri = null, $config = null)
  219. {
  220. if ($uri !== null) {
  221. $this->setUri($uri);
  222. }
  223. if ($config !== null) {
  224. $this->setConfig($config);
  225. }
  226. }
  227. /**
  228. * Set the URI for the next request
  229. *
  230. * @param Zend_Uri_Http|string $uri
  231. * @return Zend_Http_Client
  232. * @throws Zend_Http_Client_Exception
  233. */
  234. public function setUri($uri)
  235. {
  236. if (is_string($uri)) {
  237. $uri = Zend_Uri::factory($uri);
  238. }
  239. if (!$uri instanceof Zend_Uri_Http) {
  240. /** @see Zend_Http_Client_Exception */
  241. require_once 'Zend/Http/Client/Exception.php';
  242. throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
  243. }
  244. // Set auth if username and password has been specified in the uri
  245. if ($uri->getUsername() && $uri->getPassword()) {
  246. $this->setAuth($uri->getUsername(), $uri->getPassword());
  247. }
  248. // We have no ports, set the defaults
  249. if (! $uri->getPort()) {
  250. $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
  251. }
  252. $this->uri = $uri;
  253. return $this;
  254. }
  255. /**
  256. * Get the URI for the next request
  257. *
  258. * @param boolean $as_string If true, will return the URI as a string
  259. * @return Zend_Uri_Http|string
  260. */
  261. public function getUri($as_string = false)
  262. {
  263. if ($as_string && $this->uri instanceof Zend_Uri_Http) {
  264. return $this->uri->__toString();
  265. } else {
  266. return $this->uri;
  267. }
  268. }
  269. /**
  270. * Set configuration parameters for this HTTP client
  271. *
  272. * @param Zend_Config | array $config
  273. * @return Zend_Http_Client
  274. * @throws Zend_Http_Client_Exception
  275. */
  276. public function setConfig($config = array())
  277. {
  278. if ($config instanceof Zend_Config) {
  279. $config = $config->toArray();
  280. } elseif (! is_array($config)) {
  281. /** @see Zend_Http_Client_Exception */
  282. require_once 'Zend/Http/Client/Exception.php';
  283. throw new Zend_Http_Client_Exception('Array or Zend_Config object expected, got ' . gettype($config));
  284. }
  285. foreach ($config as $k => $v) {
  286. $this->config[strtolower($k)] = $v;
  287. }
  288. // Pass configuration options to the adapter if it exists
  289. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  290. $this->adapter->setConfig($config);
  291. }
  292. return $this;
  293. }
  294. /**
  295. * Set the next request's method
  296. *
  297. * Validated the passed method and sets it. If we have files set for
  298. * POST requests, and the new method is not POST, the files are silently
  299. * dropped.
  300. *
  301. * @param string $method
  302. * @return Zend_Http_Client
  303. * @throws Zend_Http_Client_Exception
  304. */
  305. public function setMethod($method = self::GET)
  306. {
  307. if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
  308. /** @see Zend_Http_Client_Exception */
  309. require_once 'Zend/Http/Client/Exception.php';
  310. throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
  311. }
  312. if ($method == self::POST && $this->enctype === null) {
  313. $this->setEncType(self::ENC_URLENCODED);
  314. }
  315. $this->method = $method;
  316. return $this;
  317. }
  318. /**
  319. * Set one or more request headers
  320. *
  321. * This function can be used in several ways to set the client's request
  322. * headers:
  323. * 1. By providing two parameters: $name as the header to set (eg. 'Host')
  324. * and $value as it's value (eg. 'www.example.com').
  325. * 2. By providing a single header string as the only parameter
  326. * eg. 'Host: www.example.com'
  327. * 3. By providing an array of headers as the first parameter
  328. * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
  329. * the function will call itself recursively for each array item.
  330. *
  331. * @param string|array $name Header name, full header string ('Header: value')
  332. * or an array of headers
  333. * @param mixed $value Header value or null
  334. * @return Zend_Http_Client
  335. * @throws Zend_Http_Client_Exception
  336. */
  337. public function setHeaders($name, $value = null)
  338. {
  339. // If we got an array, go recusive!
  340. if (is_array($name)) {
  341. foreach ($name as $k => $v) {
  342. if (is_string($k)) {
  343. $this->setHeaders($k, $v);
  344. } else {
  345. $this->setHeaders($v, null);
  346. }
  347. }
  348. } else {
  349. // Check if $name needs to be split
  350. if ($value === null && (strpos($name, ':') > 0)) {
  351. list($name, $value) = explode(':', $name, 2);
  352. }
  353. // Make sure the name is valid if we are in strict mode
  354. if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
  355. /** @see Zend_Http_Client_Exception */
  356. require_once 'Zend/Http/Client/Exception.php';
  357. throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
  358. }
  359. $normalized_name = strtolower($name);
  360. // If $value is null or false, unset the header
  361. if ($value === null || $value === false) {
  362. unset($this->headers[$normalized_name]);
  363. // Else, set the header
  364. } else {
  365. // Header names are stored lowercase internally.
  366. if (is_string($value)) {
  367. $value = trim($value);
  368. }
  369. $this->headers[$normalized_name] = array($name, $value);
  370. }
  371. }
  372. return $this;
  373. }
  374. /**
  375. * Get the value of a specific header
  376. *
  377. * Note that if the header has more than one value, an array
  378. * will be returned.
  379. *
  380. * @param string $key
  381. * @return string|array|null The header value or null if it is not set
  382. */
  383. public function getHeader($key)
  384. {
  385. $key = strtolower($key);
  386. if (isset($this->headers[$key])) {
  387. return $this->headers[$key][1];
  388. } else {
  389. return null;
  390. }
  391. }
  392. /**
  393. * Set a GET parameter for the request. Wrapper around _setParameter
  394. *
  395. * @param string|array $name
  396. * @param string $value
  397. * @return Zend_Http_Client
  398. */
  399. public function setParameterGet($name, $value = null)
  400. {
  401. if (is_array($name)) {
  402. foreach ($name as $k => $v)
  403. $this->_setParameter('GET', $k, $v);
  404. } else {
  405. $this->_setParameter('GET', $name, $value);
  406. }
  407. return $this;
  408. }
  409. /**
  410. * Set a POST parameter for the request. Wrapper around _setParameter
  411. *
  412. * @param string|array $name
  413. * @param string $value
  414. * @return Zend_Http_Client
  415. */
  416. public function setParameterPost($name, $value = null)
  417. {
  418. if (is_array($name)) {
  419. foreach ($name as $k => $v)
  420. $this->_setParameter('POST', $k, $v);
  421. } else {
  422. $this->_setParameter('POST', $name, $value);
  423. }
  424. return $this;
  425. }
  426. /**
  427. * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
  428. *
  429. * @param string $type GET or POST
  430. * @param string $name
  431. * @param string $value
  432. * @return null
  433. */
  434. protected function _setParameter($type, $name, $value)
  435. {
  436. $parray = array();
  437. $type = strtolower($type);
  438. switch ($type) {
  439. case 'get':
  440. $parray = &$this->paramsGet;
  441. break;
  442. case 'post':
  443. $parray = &$this->paramsPost;
  444. break;
  445. }
  446. if ($value === null) {
  447. if (isset($parray[$name])) unset($parray[$name]);
  448. } else {
  449. $parray[$name] = $value;
  450. }
  451. }
  452. /**
  453. * Get the number of redirections done on the last request
  454. *
  455. * @return int
  456. */
  457. public function getRedirectionsCount()
  458. {
  459. return $this->redirectCounter;
  460. }
  461. /**
  462. * Set HTTP authentication parameters
  463. *
  464. * $type should be one of the supported types - see the self::AUTH_*
  465. * constants.
  466. *
  467. * To enable authentication:
  468. * <code>
  469. * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
  470. * </code>
  471. *
  472. * To disable authentication:
  473. * <code>
  474. * $this->setAuth(false);
  475. * </code>
  476. *
  477. * @see http://www.faqs.org/rfcs/rfc2617.html
  478. * @param string|false $user User name or false disable authentication
  479. * @param string $password Password
  480. * @param string $type Authentication type
  481. * @return Zend_Http_Client
  482. * @throws Zend_Http_Client_Exception
  483. */
  484. public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
  485. {
  486. // If we got false or null, disable authentication
  487. if ($user === false || $user === null) {
  488. $this->auth = null;
  489. // Clear the auth information in the uri instance as well
  490. if ($this->uri instanceof Zend_Uri_Http) {
  491. $this->getUri()->setUsername('');
  492. $this->getUri()->setPassword('');
  493. }
  494. // Else, set up authentication
  495. } else {
  496. // Check we got a proper authentication type
  497. if (! defined('self::AUTH_' . strtoupper($type))) {
  498. /** @see Zend_Http_Client_Exception */
  499. require_once 'Zend/Http/Client/Exception.php';
  500. throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
  501. }
  502. $this->auth = array(
  503. 'user' => (string) $user,
  504. 'password' => (string) $password,
  505. 'type' => $type
  506. );
  507. }
  508. return $this;
  509. }
  510. /**
  511. * Set the HTTP client's cookie jar.
  512. *
  513. * A cookie jar is an object that holds and maintains cookies across HTTP requests
  514. * and responses.
  515. *
  516. * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
  517. * @return Zend_Http_Client
  518. * @throws Zend_Http_Client_Exception
  519. */
  520. public function setCookieJar($cookiejar = true)
  521. {
  522. if (! class_exists('Zend_Http_CookieJar')) {
  523. require_once 'Zend/Http/CookieJar.php';
  524. }
  525. if ($cookiejar instanceof Zend_Http_CookieJar) {
  526. $this->cookiejar = $cookiejar;
  527. } elseif ($cookiejar === true) {
  528. $this->cookiejar = new Zend_Http_CookieJar();
  529. } elseif (! $cookiejar) {
  530. $this->cookiejar = null;
  531. } else {
  532. /** @see Zend_Http_Client_Exception */
  533. require_once 'Zend/Http/Client/Exception.php';
  534. throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
  535. }
  536. return $this;
  537. }
  538. /**
  539. * Return the current cookie jar or null if none.
  540. *
  541. * @return Zend_Http_CookieJar|null
  542. */
  543. public function getCookieJar()
  544. {
  545. return $this->cookiejar;
  546. }
  547. /**
  548. * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  549. * will be added directly to the headers array as "Cookie" headers.
  550. *
  551. * @param Zend_Http_Cookie|string $cookie
  552. * @param string|null $value If "cookie" is a string, this is the cookie value.
  553. * @return Zend_Http_Client
  554. * @throws Zend_Http_Client_Exception
  555. */
  556. public function setCookie($cookie, $value = null)
  557. {
  558. if (! class_exists('Zend_Http_Cookie')) {
  559. require_once 'Zend/Http/Cookie.php';
  560. }
  561. if (is_array($cookie)) {
  562. foreach ($cookie as $c => $v) {
  563. if (is_string($c)) {
  564. $this->setCookie($c, $v);
  565. } else {
  566. $this->setCookie($v);
  567. }
  568. }
  569. return $this;
  570. }
  571. if ($value !== null && $this->config['encodecookies']) {
  572. $value = urlencode($value);
  573. }
  574. if (isset($this->cookiejar)) {
  575. if ($cookie instanceof Zend_Http_Cookie) {
  576. $this->cookiejar->addCookie($cookie);
  577. } elseif (is_string($cookie) && $value !== null) {
  578. $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}",
  579. $this->uri,
  580. $this->config['encodecookies']);
  581. $this->cookiejar->addCookie($cookie);
  582. }
  583. } else {
  584. if ($cookie instanceof Zend_Http_Cookie) {
  585. $name = $cookie->getName();
  586. $value = $cookie->getValue();
  587. $cookie = $name;
  588. }
  589. if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
  590. /** @see Zend_Http_Client_Exception */
  591. require_once 'Zend/Http/Client/Exception.php';
  592. throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
  593. }
  594. $value = addslashes($value);
  595. if (! isset($this->headers['cookie'])) {
  596. $this->headers['cookie'] = array('Cookie', '');
  597. }
  598. $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
  599. }
  600. return $this;
  601. }
  602. /**
  603. * Set a file to upload (using a POST request)
  604. *
  605. * Can be used in two ways:
  606. *
  607. * 1. $data is null (default): $filename is treated as the name if a local file which
  608. * will be read and sent. Will try to guess the content type using mime_content_type().
  609. * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
  610. * contents and no file is read from the file system. In this case, you need to
  611. * manually set the Content-Type ($ctype) or it will default to
  612. * application/octet-stream.
  613. *
  614. * @param string $filename Name of file to upload, or name to save as
  615. * @param string $formname Name of form element to send as
  616. * @param string $data Data to send (if null, $filename is read and sent)
  617. * @param string $ctype Content type to use (if $data is set and $ctype is
  618. * null, will be application/octet-stream)
  619. * @return Zend_Http_Client
  620. * @throws Zend_Http_Client_Exception
  621. */
  622. public function setFileUpload($filename, $formname, $data = null, $ctype = null)
  623. {
  624. if ($data === null) {
  625. if (($data = @file_get_contents($filename)) === false) {
  626. /** @see Zend_Http_Client_Exception */
  627. require_once 'Zend/Http/Client/Exception.php';
  628. throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
  629. }
  630. if (! $ctype) {
  631. $ctype = $this->_detectFileMimeType($filename);
  632. }
  633. }
  634. // Force enctype to multipart/form-data
  635. $this->setEncType(self::ENC_FORMDATA);
  636. $this->files[] = array(
  637. 'formname' => $formname,
  638. 'filename' => basename($filename),
  639. 'ctype' => $ctype,
  640. 'data' => $data
  641. );
  642. return $this;
  643. }
  644. /**
  645. * Set the encoding type for POST data
  646. *
  647. * @param string $enctype
  648. * @return Zend_Http_Client
  649. */
  650. public function setEncType($enctype = self::ENC_URLENCODED)
  651. {
  652. $this->enctype = $enctype;
  653. return $this;
  654. }
  655. /**
  656. * Set the raw (already encoded) POST data.
  657. *
  658. * This function is here for two reasons:
  659. * 1. For advanced user who would like to set their own data, already encoded
  660. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  661. * this method will be used to set the encoded data.
  662. *
  663. * $data can also be stream (such as file) from which the data will be read.
  664. *
  665. * @param string|resource $data
  666. * @param string $enctype
  667. * @return Zend_Http_Client
  668. */
  669. public function setRawData($data, $enctype = null)
  670. {
  671. $this->raw_post_data = $data;
  672. $this->setEncType($enctype);
  673. if (is_resource($data)) {
  674. // We've got stream data
  675. $stat = @fstat($data);
  676. if($stat) {
  677. $this->setHeaders(self::CONTENT_LENGTH, $stat['size']);
  678. }
  679. }
  680. return $this;
  681. }
  682. /**
  683. * Clear all GET and POST parameters
  684. *
  685. * Should be used to reset the request parameters if the client is
  686. * used for several concurrent requests.
  687. *
  688. * clearAll parameter controls if we clean just parameters or also
  689. * headers and last_*
  690. *
  691. * @param bool $clearAll Should all data be cleared?
  692. * @return Zend_Http_Client
  693. */
  694. public function resetParameters($clearAll = false)
  695. {
  696. // Reset parameter data
  697. $this->paramsGet = array();
  698. $this->paramsPost = array();
  699. $this->files = array();
  700. $this->raw_post_data = null;
  701. if($clearAll) {
  702. $this->headers = array();
  703. $this->last_request = null;
  704. $this->last_response = null;
  705. } else {
  706. // Clear outdated headers
  707. if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
  708. unset($this->headers[strtolower(self::CONTENT_TYPE)]);
  709. }
  710. if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
  711. unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
  712. }
  713. }
  714. return $this;
  715. }
  716. /**
  717. * Get the last HTTP request as string
  718. *
  719. * @return string
  720. */
  721. public function getLastRequest()
  722. {
  723. return $this->last_request;
  724. }
  725. /**
  726. * Get the last HTTP response received by this client
  727. *
  728. * If $config['storeresponse'] is set to false, or no response was
  729. * stored yet, will return null
  730. *
  731. * @return Zend_Http_Response or null if none
  732. */
  733. public function getLastResponse()
  734. {
  735. return $this->last_response;
  736. }
  737. /**
  738. * Load the connection adapter
  739. *
  740. * While this method is not called more than one for a client, it is
  741. * seperated from ->request() to preserve logic and readability
  742. *
  743. * @param Zend_Http_Client_Adapter_Interface|string $adapter
  744. * @return null
  745. * @throws Zend_Http_Client_Exception
  746. */
  747. public function setAdapter($adapter)
  748. {
  749. if (is_string($adapter)) {
  750. if (!class_exists($adapter)) {
  751. try {
  752. require_once 'Zend/Loader.php';
  753. Zend_Loader::loadClass($adapter);
  754. } catch (Zend_Exception $e) {
  755. /** @see Zend_Http_Client_Exception */
  756. require_once 'Zend/Http/Client/Exception.php';
  757. throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}", 0, $e);
  758. }
  759. }
  760. $adapter = new $adapter;
  761. }
  762. if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
  763. /** @see Zend_Http_Client_Exception */
  764. require_once 'Zend/Http/Client/Exception.php';
  765. throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  766. }
  767. $this->adapter = $adapter;
  768. $config = $this->config;
  769. unset($config['adapter']);
  770. $this->adapter->setConfig($config);
  771. }
  772. /**
  773. * Load the connection adapter
  774. *
  775. * @return Zend_Http_Client_Adapter_Interface $adapter
  776. */
  777. public function getAdapter()
  778. {
  779. return $this->adapter;
  780. }
  781. /**
  782. * Set streaming for received data
  783. *
  784. * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming
  785. * @return Zend_Http_Client
  786. */
  787. public function setStream($streamfile = true)
  788. {
  789. $this->setConfig(array("output_stream" => $streamfile));
  790. return $this;
  791. }
  792. /**
  793. * Get status of streaming for received data
  794. * @return boolean|string
  795. */
  796. public function getStream()
  797. {
  798. return $this->config["output_stream"];
  799. }
  800. /**
  801. * Create temporary stream
  802. *
  803. * @return resource
  804. */
  805. protected function _openTempStream()
  806. {
  807. $this->_stream_name = $this->config['output_stream'];
  808. if(!is_string($this->_stream_name)) {
  809. // If name is not given, create temp name
  810. $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(),
  811. 'Zend_Http_Client');
  812. }
  813. if (false === ($fp = @fopen($this->_stream_name, "w+b"))) {
  814. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  815. $this->adapter->close();
  816. }
  817. require_once 'Zend/Http/Client/Exception.php';
  818. throw new Zend_Http_Client_Exception("Could not open temp file {$this->_stream_name}");
  819. }
  820. return $fp;
  821. }
  822. /**
  823. * Send the HTTP request and return an HTTP response object
  824. *
  825. * @param string $method
  826. * @return Zend_Http_Response
  827. * @throws Zend_Http_Client_Exception
  828. */
  829. public function request($method = null)
  830. {
  831. if (! $this->uri instanceof Zend_Uri_Http) {
  832. /** @see Zend_Http_Client_Exception */
  833. require_once 'Zend/Http/Client/Exception.php';
  834. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  835. }
  836. if ($method) {
  837. $this->setMethod($method);
  838. }
  839. $this->redirectCounter = 0;
  840. $response = null;
  841. // Make sure the adapter is loaded
  842. if ($this->adapter == null) {
  843. $this->setAdapter($this->config['adapter']);
  844. }
  845. // Send the first request. If redirected, continue.
  846. do {
  847. // Clone the URI and add the additional GET parameters to it
  848. $uri = clone $this->uri;
  849. if (! empty($this->paramsGet)) {
  850. $query = $uri->getQuery();
  851. if (! empty($query)) {
  852. $query .= '&';
  853. }
  854. $query .= http_build_query($this->paramsGet, null, '&');
  855. $uri->setQuery($query);
  856. }
  857. $body = $this->_prepareBody();
  858. $headers = $this->_prepareHeaders();
  859. // check that adapter supports streaming before using it
  860. if(is_resource($body) && !($this->adapter instanceof Zend_Http_Client_Adapter_Stream)) {
  861. /** @see Zend_Http_Client_Exception */
  862. require_once 'Zend/Http/Client/Exception.php';
  863. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  864. }
  865. // Open the connection, send the request and read the response
  866. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  867. ($uri->getScheme() == 'https' ? true : false));
  868. if($this->config['output_stream']) {
  869. if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
  870. $stream = $this->_openTempStream();
  871. $this->adapter->setOutputStream($stream);
  872. } else {
  873. /** @see Zend_Http_Client_Exception */
  874. require_once 'Zend/Http/Client/Exception.php';
  875. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  876. }
  877. }
  878. $this->last_request = $this->adapter->write($this->method,
  879. $uri, $this->config['httpversion'], $headers, $body);
  880. $response = $this->adapter->read();
  881. if (! $response) {
  882. /** @see Zend_Http_Client_Exception */
  883. require_once 'Zend/Http/Client/Exception.php';
  884. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  885. }
  886. if($this->config['output_stream']) {
  887. rewind($stream);
  888. // cleanup the adapter
  889. $this->adapter->setOutputStream(null);
  890. $response = Zend_Http_Response_Stream::fromStream($response, $stream);
  891. $response->setStreamName($this->_stream_name);
  892. if(!is_string($this->config['output_stream'])) {
  893. // we used temp name, will need to clean up
  894. $response->setCleanup(true);
  895. }
  896. } else {
  897. $response = Zend_Http_Response::fromString($response);
  898. }
  899. if ($this->config['storeresponse']) {
  900. $this->last_response = $response;
  901. }
  902. // Load cookies into cookie jar
  903. if (isset($this->cookiejar)) {
  904. $this->cookiejar->addCookiesFromResponse($response, $uri);
  905. }
  906. // If we got redirected, look for the Location header
  907. if ($response->isRedirect() && ($location = $response->getHeader('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 (Zend_Uri_Http::check($location)) {
  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 &&
  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. }