Client.php 40 KB

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