Client.php 41 KB

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