Client.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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-2009 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-2009 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) {
  214. $this->setUri($uri);
  215. }
  216. if ($config !== null) {
  217. $this->setConfig($config);
  218. }
  219. }
  220. /**
  221. * Set the URI for the next request
  222. *
  223. * @param Zend_Uri_Http|string $uri
  224. * @return Zend_Http_Client
  225. * @throws Zend_Http_Client_Exception
  226. */
  227. public function setUri($uri)
  228. {
  229. if (is_string($uri)) {
  230. $uri = Zend_Uri::factory($uri);
  231. }
  232. if (!$uri instanceof Zend_Uri_Http) {
  233. /** @see Zend_Http_Client_Exception */
  234. require_once 'Zend/Http/Client/Exception.php';
  235. throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
  236. }
  237. // We have no ports, set the defaults
  238. if (! $uri->getPort()) {
  239. $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
  240. }
  241. $this->uri = $uri;
  242. return $this;
  243. }
  244. /**
  245. * Get the URI for the next request
  246. *
  247. * @param boolean $as_string If true, will return the URI as a string
  248. * @return Zend_Uri_Http|string
  249. */
  250. public function getUri($as_string = false)
  251. {
  252. if ($as_string && $this->uri instanceof Zend_Uri_Http) {
  253. return $this->uri->__toString();
  254. } else {
  255. return $this->uri;
  256. }
  257. }
  258. /**
  259. * Set configuration parameters for this HTTP client
  260. *
  261. * @param Zend_Config | array $config
  262. * @return Zend_Http_Client
  263. * @throws Zend_Http_Client_Exception
  264. */
  265. public function setConfig($config = array())
  266. {
  267. if ($config instanceof Zend_Config) {
  268. $config = $config->toArray();
  269. } elseif (! is_array($config)) {
  270. /** @see Zend_Http_Client_Exception */
  271. require_once 'Zend/Http/Client/Exception.php';
  272. throw new Zend_Http_Client_Exception('Array or Zend_Config object expected, got ' . gettype($config));
  273. }
  274. foreach ($config as $k => $v) {
  275. $this->config[strtolower($k)] = $v;
  276. }
  277. // Pass configuration options to the adapter if it exists
  278. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  279. $this->adapter->setConfig($config);
  280. }
  281. return $this;
  282. }
  283. /**
  284. * Set the next request's method
  285. *
  286. * Validated the passed method and sets it. If we have files set for
  287. * POST requests, and the new method is not POST, the files are silently
  288. * dropped.
  289. *
  290. * @param string $method
  291. * @return Zend_Http_Client
  292. * @throws Zend_Http_Client_Exception
  293. */
  294. public function setMethod($method = self::GET)
  295. {
  296. if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
  297. /** @see Zend_Http_Client_Exception */
  298. require_once 'Zend/Http/Client/Exception.php';
  299. throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
  300. }
  301. if ($method == self::POST && $this->enctype === null) {
  302. $this->setEncType(self::ENC_URLENCODED);
  303. }
  304. $this->method = $method;
  305. return $this;
  306. }
  307. /**
  308. * Set one or more request headers
  309. *
  310. * This function can be used in several ways to set the client's request
  311. * headers:
  312. * 1. By providing two parameters: $name as the header to set (eg. 'Host')
  313. * and $value as it's value (eg. 'www.example.com').
  314. * 2. By providing a single header string as the only parameter
  315. * eg. 'Host: www.example.com'
  316. * 3. By providing an array of headers as the first parameter
  317. * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
  318. * the function will call itself recursively for each array item.
  319. *
  320. * @param string|array $name Header name, full header string ('Header: value')
  321. * or an array of headers
  322. * @param mixed $value Header value or null
  323. * @return Zend_Http_Client
  324. * @throws Zend_Http_Client_Exception
  325. */
  326. public function setHeaders($name, $value = null)
  327. {
  328. // If we got an array, go recusive!
  329. if (is_array($name)) {
  330. foreach ($name as $k => $v) {
  331. if (is_string($k)) {
  332. $this->setHeaders($k, $v);
  333. } else {
  334. $this->setHeaders($v, null);
  335. }
  336. }
  337. } else {
  338. // Check if $name needs to be split
  339. if ($value === null && (strpos($name, ':') > 0)) {
  340. list($name, $value) = explode(':', $name, 2);
  341. }
  342. // Make sure the name is valid if we are in strict mode
  343. if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
  344. /** @see Zend_Http_Client_Exception */
  345. require_once 'Zend/Http/Client/Exception.php';
  346. throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
  347. }
  348. $normalized_name = strtolower($name);
  349. // If $value is null or false, unset the header
  350. if ($value === null || $value === false) {
  351. unset($this->headers[$normalized_name]);
  352. // Else, set the header
  353. } else {
  354. // Header names are stored lowercase internally.
  355. if (is_string($value)) {
  356. $value = trim($value);
  357. }
  358. $this->headers[$normalized_name] = array($name, $value);
  359. }
  360. }
  361. return $this;
  362. }
  363. /**
  364. * Get the value of a specific header
  365. *
  366. * Note that if the header has more than one value, an array
  367. * will be returned.
  368. *
  369. * @param string $key
  370. * @return string|array|null The header value or null if it is not set
  371. */
  372. public function getHeader($key)
  373. {
  374. $key = strtolower($key);
  375. if (isset($this->headers[$key])) {
  376. return $this->headers[$key][1];
  377. } else {
  378. return null;
  379. }
  380. }
  381. /**
  382. * Set a GET parameter for the request. Wrapper around _setParameter
  383. *
  384. * @param string|array $name
  385. * @param string $value
  386. * @return Zend_Http_Client
  387. */
  388. public function setParameterGet($name, $value = null)
  389. {
  390. if (is_array($name)) {
  391. foreach ($name as $k => $v)
  392. $this->_setParameter('GET', $k, $v);
  393. } else {
  394. $this->_setParameter('GET', $name, $value);
  395. }
  396. return $this;
  397. }
  398. /**
  399. * Set a POST parameter for the request. Wrapper around _setParameter
  400. *
  401. * @param string|array $name
  402. * @param string $value
  403. * @return Zend_Http_Client
  404. */
  405. public function setParameterPost($name, $value = null)
  406. {
  407. if (is_array($name)) {
  408. foreach ($name as $k => $v)
  409. $this->_setParameter('POST', $k, $v);
  410. } else {
  411. $this->_setParameter('POST', $name, $value);
  412. }
  413. return $this;
  414. }
  415. /**
  416. * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
  417. *
  418. * @param string $type GET or POST
  419. * @param string $name
  420. * @param string $value
  421. * @return null
  422. */
  423. protected function _setParameter($type, $name, $value)
  424. {
  425. $parray = array();
  426. $type = strtolower($type);
  427. switch ($type) {
  428. case 'get':
  429. $parray = &$this->paramsGet;
  430. break;
  431. case 'post':
  432. $parray = &$this->paramsPost;
  433. break;
  434. }
  435. if ($value === null) {
  436. if (isset($parray[$name])) unset($parray[$name]);
  437. } else {
  438. $parray[$name] = $value;
  439. }
  440. }
  441. /**
  442. * Get the number of redirections done on the last request
  443. *
  444. * @return int
  445. */
  446. public function getRedirectionsCount()
  447. {
  448. return $this->redirectCounter;
  449. }
  450. /**
  451. * Set HTTP authentication parameters
  452. *
  453. * $type should be one of the supported types - see the self::AUTH_*
  454. * constants.
  455. *
  456. * To enable authentication:
  457. * <code>
  458. * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
  459. * </code>
  460. *
  461. * To disable authentication:
  462. * <code>
  463. * $this->setAuth(false);
  464. * </code>
  465. *
  466. * @see http://www.faqs.org/rfcs/rfc2617.html
  467. * @param string|false $user User name or false disable authentication
  468. * @param string $password Password
  469. * @param string $type Authentication type
  470. * @return Zend_Http_Client
  471. * @throws Zend_Http_Client_Exception
  472. */
  473. public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
  474. {
  475. // If we got false or null, disable authentication
  476. if ($user === false || $user === null) {
  477. $this->auth = null;
  478. // Else, set up authentication
  479. } else {
  480. // Check we got a proper authentication type
  481. if (! defined('self::AUTH_' . strtoupper($type))) {
  482. /** @see Zend_Http_Client_Exception */
  483. require_once 'Zend/Http/Client/Exception.php';
  484. throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
  485. }
  486. $this->auth = array(
  487. 'user' => (string) $user,
  488. 'password' => (string) $password,
  489. 'type' => $type
  490. );
  491. }
  492. return $this;
  493. }
  494. /**
  495. * Set the HTTP client's cookie jar.
  496. *
  497. * A cookie jar is an object that holds and maintains cookies across HTTP requests
  498. * and responses.
  499. *
  500. * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
  501. * @return Zend_Http_Client
  502. * @throws Zend_Http_Client_Exception
  503. */
  504. public function setCookieJar($cookiejar = true)
  505. {
  506. if (! class_exists('Zend_Http_CookieJar')) {
  507. require_once 'Zend/Http/CookieJar.php';
  508. }
  509. if ($cookiejar instanceof Zend_Http_CookieJar) {
  510. $this->cookiejar = $cookiejar;
  511. } elseif ($cookiejar === true) {
  512. $this->cookiejar = new Zend_Http_CookieJar();
  513. } elseif (! $cookiejar) {
  514. $this->cookiejar = null;
  515. } else {
  516. /** @see Zend_Http_Client_Exception */
  517. require_once 'Zend/Http/Client/Exception.php';
  518. throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
  519. }
  520. return $this;
  521. }
  522. /**
  523. * Return the current cookie jar or null if none.
  524. *
  525. * @return Zend_Http_CookieJar|null
  526. */
  527. public function getCookieJar()
  528. {
  529. return $this->cookiejar;
  530. }
  531. /**
  532. * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  533. * will be added directly to the headers array as "Cookie" headers.
  534. *
  535. * @param Zend_Http_Cookie|string $cookie
  536. * @param string|null $value If "cookie" is a string, this is the cookie value.
  537. * @return Zend_Http_Client
  538. * @throws Zend_Http_Client_Exception
  539. */
  540. public function setCookie($cookie, $value = null)
  541. {
  542. if (! class_exists('Zend_Http_Cookie')) {
  543. require_once 'Zend/Http/Cookie.php';
  544. }
  545. if (is_array($cookie)) {
  546. foreach ($cookie as $c => $v) {
  547. if (is_string($c)) {
  548. $this->setCookie($c, $v);
  549. } else {
  550. $this->setCookie($v);
  551. }
  552. }
  553. return $this;
  554. }
  555. if ($value !== null) {
  556. $value = urlencode($value);
  557. }
  558. if (isset($this->cookiejar)) {
  559. if ($cookie instanceof Zend_Http_Cookie) {
  560. $this->cookiejar->addCookie($cookie);
  561. } elseif (is_string($cookie) && $value !== null) {
  562. $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
  563. $this->cookiejar->addCookie($cookie);
  564. }
  565. } else {
  566. if ($cookie instanceof Zend_Http_Cookie) {
  567. $name = $cookie->getName();
  568. $value = $cookie->getValue();
  569. $cookie = $name;
  570. }
  571. if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
  572. /** @see Zend_Http_Client_Exception */
  573. require_once 'Zend/Http/Client/Exception.php';
  574. throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
  575. }
  576. $value = addslashes($value);
  577. if (! isset($this->headers['cookie'])) {
  578. $this->headers['cookie'] = array('Cookie', '');
  579. }
  580. $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
  581. }
  582. return $this;
  583. }
  584. /**
  585. * Set a file to upload (using a POST request)
  586. *
  587. * Can be used in two ways:
  588. *
  589. * 1. $data is null (default): $filename is treated as the name if a local file which
  590. * will be read and sent. Will try to guess the content type using mime_content_type().
  591. * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
  592. * contents and no file is read from the file system. In this case, you need to
  593. * manually set the Content-Type ($ctype) or it will default to
  594. * application/octet-stream.
  595. *
  596. * @param string $filename Name of file to upload, or name to save as
  597. * @param string $formname Name of form element to send as
  598. * @param string $data Data to send (if null, $filename is read and sent)
  599. * @param string $ctype Content type to use (if $data is set and $ctype is
  600. * null, will be application/octet-stream)
  601. * @return Zend_Http_Client
  602. * @throws Zend_Http_Client_Exception
  603. */
  604. public function setFileUpload($filename, $formname, $data = null, $ctype = null)
  605. {
  606. if ($data === null) {
  607. if (($data = @file_get_contents($filename)) === false) {
  608. /** @see Zend_Http_Client_Exception */
  609. require_once 'Zend/Http/Client/Exception.php';
  610. throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
  611. }
  612. if (! $ctype) {
  613. $ctype = $this->_detectFileMimeType($filename);
  614. }
  615. }
  616. // Force enctype to multipart/form-data
  617. $this->setEncType(self::ENC_FORMDATA);
  618. $this->files[] = array(
  619. 'formname' => $formname,
  620. 'filename' => basename($filename),
  621. 'ctype' => $ctype,
  622. 'data' => $data
  623. );
  624. return $this;
  625. }
  626. /**
  627. * Set the encoding type for POST data
  628. *
  629. * @param string $enctype
  630. * @return Zend_Http_Client
  631. */
  632. public function setEncType($enctype = self::ENC_URLENCODED)
  633. {
  634. $this->enctype = $enctype;
  635. return $this;
  636. }
  637. /**
  638. * Set the raw (already encoded) POST data.
  639. *
  640. * This function is here for two reasons:
  641. * 1. For advanced user who would like to set their own data, already encoded
  642. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  643. * this method will be used to set the encoded data.
  644. *
  645. * @param string $data
  646. * @param string $enctype
  647. * @return Zend_Http_Client
  648. */
  649. public function setRawData($data, $enctype = null)
  650. {
  651. $this->raw_post_data = $data;
  652. $this->setEncType($enctype);
  653. return $this;
  654. }
  655. /**
  656. * Clear all GET and POST parameters
  657. *
  658. * Should be used to reset the request parameters if the client is
  659. * used for several concurrent requests.
  660. *
  661. * @return Zend_Http_Client
  662. */
  663. public function resetParameters()
  664. {
  665. // Reset parameter data
  666. $this->paramsGet = array();
  667. $this->paramsPost = array();
  668. $this->files = array();
  669. $this->raw_post_data = null;
  670. // Clear outdated headers
  671. if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
  672. unset($this->headers[strtolower(self::CONTENT_TYPE)]);
  673. }
  674. if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
  675. unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
  676. }
  677. return $this;
  678. }
  679. /**
  680. * Get the last HTTP request as string
  681. *
  682. * @return string
  683. */
  684. public function getLastRequest()
  685. {
  686. return $this->last_request;
  687. }
  688. /**
  689. * Get the last HTTP response received by this client
  690. *
  691. * If $config['storeresponse'] is set to false, or no response was
  692. * stored yet, will return null
  693. *
  694. * @return Zend_Http_Response or null if none
  695. */
  696. public function getLastResponse()
  697. {
  698. return $this->last_response;
  699. }
  700. /**
  701. * Load the connection adapter
  702. *
  703. * While this method is not called more than one for a client, it is
  704. * seperated from ->request() to preserve logic and readability
  705. *
  706. * @param Zend_Http_Client_Adapter_Interface|string $adapter
  707. * @return null
  708. * @throws Zend_Http_Client_Exception
  709. */
  710. public function setAdapter($adapter)
  711. {
  712. if (is_string($adapter)) {
  713. if (!class_exists($adapter)) {
  714. try {
  715. require_once 'Zend/Loader.php';
  716. Zend_Loader::loadClass($adapter);
  717. } catch (Zend_Exception $e) {
  718. /** @see Zend_Http_Client_Exception */
  719. require_once 'Zend/Http/Client/Exception.php';
  720. throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
  721. }
  722. }
  723. $adapter = new $adapter;
  724. }
  725. if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
  726. /** @see Zend_Http_Client_Exception */
  727. require_once 'Zend/Http/Client/Exception.php';
  728. throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  729. }
  730. $this->adapter = $adapter;
  731. $config = $this->config;
  732. unset($config['adapter']);
  733. $this->adapter->setConfig($config);
  734. }
  735. /**
  736. * Send the HTTP request and return an HTTP response object
  737. *
  738. * @param string $method
  739. * @return Zend_Http_Response
  740. * @throws Zend_Http_Client_Exception
  741. */
  742. public function request($method = null)
  743. {
  744. if (! $this->uri instanceof Zend_Uri_Http) {
  745. /** @see Zend_Http_Client_Exception */
  746. require_once 'Zend/Http/Client/Exception.php';
  747. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  748. }
  749. if ($method) {
  750. $this->setMethod($method);
  751. }
  752. $this->redirectCounter = 0;
  753. $response = null;
  754. // Make sure the adapter is loaded
  755. if ($this->adapter == null) {
  756. $this->setAdapter($this->config['adapter']);
  757. }
  758. // Send the first request. If redirected, continue.
  759. do {
  760. // Clone the URI and add the additional GET parameters to it
  761. $uri = clone $this->uri;
  762. if (! empty($this->paramsGet)) {
  763. $query = $uri->getQuery();
  764. if (! empty($query)) {
  765. $query .= '&';
  766. }
  767. $query .= http_build_query($this->paramsGet, null, '&');
  768. $uri->setQuery($query);
  769. }
  770. $body = $this->_prepareBody();
  771. $headers = $this->_prepareHeaders();
  772. // Open the connection, send the request and read the response
  773. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  774. ($uri->getScheme() == 'https' ? true : false));
  775. $this->last_request = $this->adapter->write($this->method,
  776. $uri, $this->config['httpversion'], $headers, $body);
  777. $response = $this->adapter->read();
  778. if (! $response) {
  779. /** @see Zend_Http_Client_Exception */
  780. require_once 'Zend/Http/Client/Exception.php';
  781. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  782. }
  783. $response = Zend_Http_Response::fromString($response);
  784. if ($this->config['storeresponse']) {
  785. $this->last_response = $response;
  786. }
  787. // Load cookies into cookie jar
  788. if (isset($this->cookiejar)) {
  789. $this->cookiejar->addCookiesFromResponse($response, $uri);
  790. }
  791. // If we got redirected, look for the Location header
  792. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  793. // Check whether we send the exact same request again, or drop the parameters
  794. // and send a GET request
  795. if ($response->getStatus() == 303 ||
  796. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  797. $response->getStatus() == 301))) {
  798. $this->resetParameters();
  799. $this->setMethod(self::GET);
  800. }
  801. // If we got a well formed absolute URI
  802. if (Zend_Uri_Http::check($location)) {
  803. $this->setHeaders('host', null);
  804. $this->setUri($location);
  805. } else {
  806. // Split into path and query and set the query
  807. if (strpos($location, '?') !== false) {
  808. list($location, $query) = explode('?', $location, 2);
  809. } else {
  810. $query = '';
  811. }
  812. $this->uri->setQuery($query);
  813. // Else, if we got just an absolute path, set it
  814. if(strpos($location, '/') === 0) {
  815. $this->uri->setPath($location);
  816. // Else, assume we have a relative path
  817. } else {
  818. // Get the current path directory, removing any trailing slashes
  819. $path = $this->uri->getPath();
  820. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  821. $this->uri->setPath($path . '/' . $location);
  822. }
  823. }
  824. ++$this->redirectCounter;
  825. } else {
  826. // If we didn't get any location, stop redirecting
  827. break;
  828. }
  829. } while ($this->redirectCounter < $this->config['maxredirects']);
  830. return $response;
  831. }
  832. /**
  833. * Prepare the request headers
  834. *
  835. * @return array
  836. */
  837. protected function _prepareHeaders()
  838. {
  839. $headers = array();
  840. // Set the host header
  841. if (! isset($this->headers['host'])) {
  842. $host = $this->uri->getHost();
  843. // If the port is not default, add it
  844. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  845. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  846. $host .= ':' . $this->uri->getPort();
  847. }
  848. $headers[] = "Host: {$host}";
  849. }
  850. // Set the connection header
  851. if (! isset($this->headers['connection'])) {
  852. if (! $this->config['keepalive']) {
  853. $headers[] = "Connection: close";
  854. }
  855. }
  856. // Set the Accept-encoding header if not set - depending on whether
  857. // zlib is available or not.
  858. if (! isset($this->headers['accept-encoding'])) {
  859. if (function_exists('gzinflate')) {
  860. $headers[] = 'Accept-encoding: gzip, deflate';
  861. } else {
  862. $headers[] = 'Accept-encoding: identity';
  863. }
  864. }
  865. // Set the Content-Type header
  866. if ($this->method == self::POST &&
  867. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  868. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  869. }
  870. // Set the user agent header
  871. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  872. $headers[] = "User-Agent: {$this->config['useragent']}";
  873. }
  874. // Set HTTP authentication if needed
  875. if (is_array($this->auth)) {
  876. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  877. $headers[] = "Authorization: {$auth}";
  878. }
  879. // Load cookies from cookie jar
  880. if (isset($this->cookiejar)) {
  881. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  882. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  883. if ($cookstr) {
  884. $headers[] = "Cookie: {$cookstr}";
  885. }
  886. }
  887. // Add all other user defined headers
  888. foreach ($this->headers as $header) {
  889. list($name, $value) = $header;
  890. if (is_array($value)) {
  891. $value = implode(', ', $value);
  892. }
  893. $headers[] = "$name: $value";
  894. }
  895. return $headers;
  896. }
  897. /**
  898. * Prepare the request body (for POST and PUT requests)
  899. *
  900. * @return string
  901. * @throws Zend_Http_Client_Exception
  902. */
  903. protected function _prepareBody()
  904. {
  905. // According to RFC2616, a TRACE request should not have a body.
  906. if ($this->method == self::TRACE) {
  907. return '';
  908. }
  909. // If mbstring overloads substr and strlen functions, we have to
  910. // override it's internal encoding
  911. if (function_exists('mb_internal_encoding') &&
  912. ((int) ini_get('mbstring.func_overload')) & 2) {
  913. $mbIntEnc = mb_internal_encoding();
  914. mb_internal_encoding('ASCII');
  915. }
  916. // If we have raw_post_data set, just use it as the body.
  917. if (isset($this->raw_post_data)) {
  918. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  919. if (isset($mbIntEnc)) {
  920. mb_internal_encoding($mbIntEnc);
  921. }
  922. return $this->raw_post_data;
  923. }
  924. $body = '';
  925. // If we have files to upload, force enctype to multipart/form-data
  926. if (count ($this->files) > 0) {
  927. $this->setEncType(self::ENC_FORMDATA);
  928. }
  929. // If we have POST parameters or files, encode and add them to the body
  930. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  931. switch($this->enctype) {
  932. case self::ENC_FORMDATA:
  933. // Encode body as multipart/form-data
  934. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  935. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  936. // Get POST parameters and encode them
  937. $params = self::_flattenParametersArray($this->paramsPost);
  938. foreach ($params as $pp) {
  939. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  940. }
  941. // Encode files
  942. foreach ($this->files as $file) {
  943. $fhead = array(self::CONTENT_TYPE => $file['ctype']);
  944. $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
  945. }
  946. $body .= "--{$boundary}--\r\n";
  947. break;
  948. case self::ENC_URLENCODED:
  949. // Encode body as application/x-www-form-urlencoded
  950. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  951. $body = http_build_query($this->paramsPost, '', '&');
  952. break;
  953. default:
  954. if (isset($mbIntEnc)) {
  955. mb_internal_encoding($mbIntEnc);
  956. }
  957. /** @see Zend_Http_Client_Exception */
  958. require_once 'Zend/Http/Client/Exception.php';
  959. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  960. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  961. break;
  962. }
  963. }
  964. // Set the Content-Length if we have a body or if request is POST/PUT
  965. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  966. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  967. }
  968. if (isset($mbIntEnc)) {
  969. mb_internal_encoding($mbIntEnc);
  970. }
  971. return $body;
  972. }
  973. /**
  974. * Helper method that gets a possibly multi-level parameters array (get or
  975. * post) and flattens it.
  976. *
  977. * The method returns an array of (key, value) pairs (because keys are not
  978. * necessarily unique. If one of the parameters in as array, it will also
  979. * add a [] suffix to the key.
  980. *
  981. * This method is deprecated since Zend Framework 1.9 in favour of
  982. * self::_flattenParametersArray() and will be dropped in 2.0
  983. *
  984. * @deprecated since 1.9
  985. *
  986. * @param array $parray The parameters array
  987. * @param bool $urlencode Whether to urlencode the name and value
  988. * @return array
  989. */
  990. protected function _getParametersRecursive($parray, $urlencode = false)
  991. {
  992. // Issue a deprecated notice
  993. trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
  994. E_USER_NOTICE);
  995. if (! is_array($parray)) {
  996. return $parray;
  997. }
  998. $parameters = array();
  999. foreach ($parray as $name => $value) {
  1000. if ($urlencode) {
  1001. $name = urlencode($name);
  1002. }
  1003. // If $value is an array, iterate over it
  1004. if (is_array($value)) {
  1005. $name .= ($urlencode ? '%5B%5D' : '[]');
  1006. foreach ($value as $subval) {
  1007. if ($urlencode) {
  1008. $subval = urlencode($subval);
  1009. }
  1010. $parameters[] = array($name, $subval);
  1011. }
  1012. } else {
  1013. if ($urlencode) {
  1014. $value = urlencode($value);
  1015. }
  1016. $parameters[] = array($name, $value);
  1017. }
  1018. }
  1019. return $parameters;
  1020. }
  1021. /**
  1022. * Attempt to detect the MIME type of a file using available extensions
  1023. *
  1024. * This method will try to detect the MIME type of a file. If the fileinfo
  1025. * extension is available, it will be used. If not, the mime_magic
  1026. * extension which is deprected but is still available in many PHP setups
  1027. * will be tried.
  1028. *
  1029. * If neither extension is available, the default application/octet-stream
  1030. * MIME type will be returned
  1031. *
  1032. * @param string $file File path
  1033. * @return string MIME type
  1034. */
  1035. protected function _detectFileMimeType($file)
  1036. {
  1037. $type = null;
  1038. // First try with fileinfo functions
  1039. if (function_exists('finfo_open')) {
  1040. if (self::$_fileInfoDb === null) {
  1041. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1042. }
  1043. if (self::$_fileInfoDb) {
  1044. $type = finfo_file(self::$_fileInfoDb, $file);
  1045. }
  1046. } elseif (function_exists('mime_content_type')) {
  1047. $type = mime_content_type($file);
  1048. }
  1049. // Fallback to the default application/octet-stream
  1050. if (! $type) {
  1051. $type = 'application/octet-stream';
  1052. }
  1053. return $type;
  1054. }
  1055. /**
  1056. * Encode data to a multipart/form-data part suitable for a POST request.
  1057. *
  1058. * @param string $boundary
  1059. * @param string $name
  1060. * @param mixed $value
  1061. * @param string $filename
  1062. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1063. * @return string
  1064. */
  1065. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1066. $ret = "--{$boundary}\r\n" .
  1067. 'Content-Disposition: form-data; name="' . $name .'"';
  1068. if ($filename) {
  1069. $ret .= '; filename="' . $filename . '"';
  1070. }
  1071. $ret .= "\r\n";
  1072. foreach ($headers as $hname => $hvalue) {
  1073. $ret .= "{$hname}: {$hvalue}\r\n";
  1074. }
  1075. $ret .= "\r\n";
  1076. $ret .= "{$value}\r\n";
  1077. return $ret;
  1078. }
  1079. /**
  1080. * Create a HTTP authentication "Authorization:" header according to the
  1081. * specified user, password and authentication method.
  1082. *
  1083. * @see http://www.faqs.org/rfcs/rfc2617.html
  1084. * @param string $user
  1085. * @param string $password
  1086. * @param string $type
  1087. * @return string
  1088. * @throws Zend_Http_Client_Exception
  1089. */
  1090. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1091. {
  1092. $authHeader = null;
  1093. switch ($type) {
  1094. case self::AUTH_BASIC:
  1095. // In basic authentication, the user name cannot contain ":"
  1096. if (strpos($user, ':') !== false) {
  1097. /** @see Zend_Http_Client_Exception */
  1098. require_once 'Zend/Http/Client/Exception.php';
  1099. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1100. }
  1101. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1102. break;
  1103. //case self::AUTH_DIGEST:
  1104. /**
  1105. * @todo Implement digest authentication
  1106. */
  1107. // break;
  1108. default:
  1109. /** @see Zend_Http_Client_Exception */
  1110. require_once 'Zend/Http/Client/Exception.php';
  1111. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1112. }
  1113. return $authHeader;
  1114. }
  1115. /**
  1116. * Convert an array of parameters into a flat array of (key, value) pairs
  1117. *
  1118. * Will flatten a potentially multi-dimentional array of parameters (such
  1119. * as POST parameters) into a flat array of (key, value) paris. In case
  1120. * of multi-dimentional arrays, square brackets ([]) will be added to the
  1121. * key to indicate an array.
  1122. *
  1123. * @since 1.9
  1124. *
  1125. * @param array $parray
  1126. * @param string $prefix
  1127. * @return array
  1128. */
  1129. static protected function _flattenParametersArray($parray, $prefix = null)
  1130. {
  1131. if (! is_array($parray)) {
  1132. return $parray;
  1133. }
  1134. $parameters = array();
  1135. foreach($parray as $name => $value) {
  1136. // Calculate array key
  1137. if ($prefix) {
  1138. if (is_int($name)) {
  1139. $key = $prefix . '[]';
  1140. } else {
  1141. $key = $prefix . "[$name]";
  1142. }
  1143. } else {
  1144. $key = $name;
  1145. }
  1146. if (is_array($value)) {
  1147. $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
  1148. } else {
  1149. $parameters[] = array($key, $value);
  1150. }
  1151. }
  1152. return $parameters;
  1153. }
  1154. }