Client.php 45 KB

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