Client.php 38 KB

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