2
0

Client.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. * Send the HTTP request and return an HTTP response object
  744. *
  745. * @param string $method
  746. * @return Zend_Http_Response
  747. * @throws Zend_Http_Client_Exception
  748. */
  749. public function request($method = null)
  750. {
  751. if (! $this->uri instanceof Zend_Uri_Http) {
  752. /** @see Zend_Http_Client_Exception */
  753. require_once 'Zend/Http/Client/Exception.php';
  754. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  755. }
  756. if ($method) {
  757. $this->setMethod($method);
  758. }
  759. $this->redirectCounter = 0;
  760. $response = null;
  761. // Make sure the adapter is loaded
  762. if ($this->adapter == null) {
  763. $this->setAdapter($this->config['adapter']);
  764. }
  765. // Send the first request. If redirected, continue.
  766. do {
  767. // Clone the URI and add the additional GET parameters to it
  768. $uri = clone $this->uri;
  769. if (! empty($this->paramsGet)) {
  770. $query = $uri->getQuery();
  771. if (! empty($query)) {
  772. $query .= '&';
  773. }
  774. $query .= http_build_query($this->paramsGet, null, '&');
  775. $uri->setQuery($query);
  776. }
  777. $body = $this->_prepareBody();
  778. $headers = $this->_prepareHeaders();
  779. // Open the connection, send the request and read the response
  780. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  781. ($uri->getScheme() == 'https' ? true : false));
  782. $this->last_request = $this->adapter->write($this->method,
  783. $uri, $this->config['httpversion'], $headers, $body);
  784. $response = $this->adapter->read();
  785. if (! $response) {
  786. /** @see Zend_Http_Client_Exception */
  787. require_once 'Zend/Http/Client/Exception.php';
  788. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  789. }
  790. $response = Zend_Http_Response::fromString($response);
  791. if ($this->config['storeresponse']) {
  792. $this->last_response = $response;
  793. }
  794. // Load cookies into cookie jar
  795. if (isset($this->cookiejar)) {
  796. $this->cookiejar->addCookiesFromResponse($response, $uri);
  797. }
  798. // If we got redirected, look for the Location header
  799. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  800. // Check whether we send the exact same request again, or drop the parameters
  801. // and send a GET request
  802. if ($response->getStatus() == 303 ||
  803. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  804. $response->getStatus() == 301))) {
  805. $this->resetParameters();
  806. $this->setMethod(self::GET);
  807. }
  808. // If we got a well formed absolute URI
  809. if (Zend_Uri_Http::check($location)) {
  810. $this->setHeaders('host', null);
  811. $this->setUri($location);
  812. } else {
  813. // Split into path and query and set the query
  814. if (strpos($location, '?') !== false) {
  815. list($location, $query) = explode('?', $location, 2);
  816. } else {
  817. $query = '';
  818. }
  819. $this->uri->setQuery($query);
  820. // Else, if we got just an absolute path, set it
  821. if(strpos($location, '/') === 0) {
  822. $this->uri->setPath($location);
  823. // Else, assume we have a relative path
  824. } else {
  825. // Get the current path directory, removing any trailing slashes
  826. $path = $this->uri->getPath();
  827. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  828. $this->uri->setPath($path . '/' . $location);
  829. }
  830. }
  831. ++$this->redirectCounter;
  832. } else {
  833. // If we didn't get any location, stop redirecting
  834. break;
  835. }
  836. } while ($this->redirectCounter < $this->config['maxredirects']);
  837. return $response;
  838. }
  839. /**
  840. * Prepare the request headers
  841. *
  842. * @return array
  843. */
  844. protected function _prepareHeaders()
  845. {
  846. $headers = array();
  847. // Set the host header
  848. if (! isset($this->headers['host'])) {
  849. $host = $this->uri->getHost();
  850. // If the port is not default, add it
  851. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  852. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  853. $host .= ':' . $this->uri->getPort();
  854. }
  855. $headers[] = "Host: {$host}";
  856. }
  857. // Set the connection header
  858. if (! isset($this->headers['connection'])) {
  859. if (! $this->config['keepalive']) {
  860. $headers[] = "Connection: close";
  861. }
  862. }
  863. // Set the Accept-encoding header if not set - depending on whether
  864. // zlib is available or not.
  865. if (! isset($this->headers['accept-encoding'])) {
  866. if (function_exists('gzinflate')) {
  867. $headers[] = 'Accept-encoding: gzip, deflate';
  868. } else {
  869. $headers[] = 'Accept-encoding: identity';
  870. }
  871. }
  872. // Set the Content-Type header
  873. if ($this->method == self::POST &&
  874. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  875. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  876. }
  877. // Set the user agent header
  878. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  879. $headers[] = "User-Agent: {$this->config['useragent']}";
  880. }
  881. // Set HTTP authentication if needed
  882. if (is_array($this->auth)) {
  883. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  884. $headers[] = "Authorization: {$auth}";
  885. }
  886. // Load cookies from cookie jar
  887. if (isset($this->cookiejar)) {
  888. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  889. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  890. if ($cookstr) {
  891. $headers[] = "Cookie: {$cookstr}";
  892. }
  893. }
  894. // Add all other user defined headers
  895. foreach ($this->headers as $header) {
  896. list($name, $value) = $header;
  897. if (is_array($value)) {
  898. $value = implode(', ', $value);
  899. }
  900. $headers[] = "$name: $value";
  901. }
  902. return $headers;
  903. }
  904. /**
  905. * Prepare the request body (for POST and PUT requests)
  906. *
  907. * @return string
  908. * @throws Zend_Http_Client_Exception
  909. */
  910. protected function _prepareBody()
  911. {
  912. // According to RFC2616, a TRACE request should not have a body.
  913. if ($this->method == self::TRACE) {
  914. return '';
  915. }
  916. // If mbstring overloads substr and strlen functions, we have to
  917. // override it's internal encoding
  918. if (function_exists('mb_internal_encoding') &&
  919. ((int) ini_get('mbstring.func_overload')) & 2) {
  920. $mbIntEnc = mb_internal_encoding();
  921. mb_internal_encoding('ASCII');
  922. }
  923. // If we have raw_post_data set, just use it as the body.
  924. if (isset($this->raw_post_data)) {
  925. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  926. if (isset($mbIntEnc)) {
  927. mb_internal_encoding($mbIntEnc);
  928. }
  929. return $this->raw_post_data;
  930. }
  931. $body = '';
  932. // If we have files to upload, force enctype to multipart/form-data
  933. if (count ($this->files) > 0) {
  934. $this->setEncType(self::ENC_FORMDATA);
  935. }
  936. // If we have POST parameters or files, encode and add them to the body
  937. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  938. switch($this->enctype) {
  939. case self::ENC_FORMDATA:
  940. // Encode body as multipart/form-data
  941. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  942. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  943. // Get POST parameters and encode them
  944. $params = self::_flattenParametersArray($this->paramsPost);
  945. foreach ($params as $pp) {
  946. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  947. }
  948. // Encode files
  949. foreach ($this->files as $file) {
  950. $fhead = array(self::CONTENT_TYPE => $file['ctype']);
  951. $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
  952. }
  953. $body .= "--{$boundary}--\r\n";
  954. break;
  955. case self::ENC_URLENCODED:
  956. // Encode body as application/x-www-form-urlencoded
  957. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  958. $body = http_build_query($this->paramsPost, '', '&');
  959. break;
  960. default:
  961. if (isset($mbIntEnc)) {
  962. mb_internal_encoding($mbIntEnc);
  963. }
  964. /** @see Zend_Http_Client_Exception */
  965. require_once 'Zend/Http/Client/Exception.php';
  966. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  967. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  968. break;
  969. }
  970. }
  971. // Set the Content-Length if we have a body or if request is POST/PUT
  972. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  973. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  974. }
  975. if (isset($mbIntEnc)) {
  976. mb_internal_encoding($mbIntEnc);
  977. }
  978. return $body;
  979. }
  980. /**
  981. * Helper method that gets a possibly multi-level parameters array (get or
  982. * post) and flattens it.
  983. *
  984. * The method returns an array of (key, value) pairs (because keys are not
  985. * necessarily unique. If one of the parameters in as array, it will also
  986. * add a [] suffix to the key.
  987. *
  988. * This method is deprecated since Zend Framework 1.9 in favour of
  989. * self::_flattenParametersArray() and will be dropped in 2.0
  990. *
  991. * @deprecated since 1.9
  992. *
  993. * @param array $parray The parameters array
  994. * @param bool $urlencode Whether to urlencode the name and value
  995. * @return array
  996. */
  997. protected function _getParametersRecursive($parray, $urlencode = false)
  998. {
  999. // Issue a deprecated notice
  1000. trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
  1001. E_USER_NOTICE);
  1002. if (! is_array($parray)) {
  1003. return $parray;
  1004. }
  1005. $parameters = array();
  1006. foreach ($parray as $name => $value) {
  1007. if ($urlencode) {
  1008. $name = urlencode($name);
  1009. }
  1010. // If $value is an array, iterate over it
  1011. if (is_array($value)) {
  1012. $name .= ($urlencode ? '%5B%5D' : '[]');
  1013. foreach ($value as $subval) {
  1014. if ($urlencode) {
  1015. $subval = urlencode($subval);
  1016. }
  1017. $parameters[] = array($name, $subval);
  1018. }
  1019. } else {
  1020. if ($urlencode) {
  1021. $value = urlencode($value);
  1022. }
  1023. $parameters[] = array($name, $value);
  1024. }
  1025. }
  1026. return $parameters;
  1027. }
  1028. /**
  1029. * Attempt to detect the MIME type of a file using available extensions
  1030. *
  1031. * This method will try to detect the MIME type of a file. If the fileinfo
  1032. * extension is available, it will be used. If not, the mime_magic
  1033. * extension which is deprected but is still available in many PHP setups
  1034. * will be tried.
  1035. *
  1036. * If neither extension is available, the default application/octet-stream
  1037. * MIME type will be returned
  1038. *
  1039. * @param string $file File path
  1040. * @return string MIME type
  1041. */
  1042. protected function _detectFileMimeType($file)
  1043. {
  1044. $type = null;
  1045. // First try with fileinfo functions
  1046. if (function_exists('finfo_open')) {
  1047. if (self::$_fileInfoDb === null) {
  1048. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1049. }
  1050. if (self::$_fileInfoDb) {
  1051. $type = finfo_file(self::$_fileInfoDb, $file);
  1052. }
  1053. } elseif (function_exists('mime_content_type')) {
  1054. $type = mime_content_type($file);
  1055. }
  1056. // Fallback to the default application/octet-stream
  1057. if (! $type) {
  1058. $type = 'application/octet-stream';
  1059. }
  1060. return $type;
  1061. }
  1062. /**
  1063. * Encode data to a multipart/form-data part suitable for a POST request.
  1064. *
  1065. * @param string $boundary
  1066. * @param string $name
  1067. * @param mixed $value
  1068. * @param string $filename
  1069. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1070. * @return string
  1071. */
  1072. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1073. $ret = "--{$boundary}\r\n" .
  1074. 'Content-Disposition: form-data; name="' . $name .'"';
  1075. if ($filename) {
  1076. $ret .= '; filename="' . $filename . '"';
  1077. }
  1078. $ret .= "\r\n";
  1079. foreach ($headers as $hname => $hvalue) {
  1080. $ret .= "{$hname}: {$hvalue}\r\n";
  1081. }
  1082. $ret .= "\r\n";
  1083. $ret .= "{$value}\r\n";
  1084. return $ret;
  1085. }
  1086. /**
  1087. * Create a HTTP authentication "Authorization:" header according to the
  1088. * specified user, password and authentication method.
  1089. *
  1090. * @see http://www.faqs.org/rfcs/rfc2617.html
  1091. * @param string $user
  1092. * @param string $password
  1093. * @param string $type
  1094. * @return string
  1095. * @throws Zend_Http_Client_Exception
  1096. */
  1097. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1098. {
  1099. $authHeader = null;
  1100. switch ($type) {
  1101. case self::AUTH_BASIC:
  1102. // In basic authentication, the user name cannot contain ":"
  1103. if (strpos($user, ':') !== false) {
  1104. /** @see Zend_Http_Client_Exception */
  1105. require_once 'Zend/Http/Client/Exception.php';
  1106. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1107. }
  1108. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1109. break;
  1110. //case self::AUTH_DIGEST:
  1111. /**
  1112. * @todo Implement digest authentication
  1113. */
  1114. // break;
  1115. default:
  1116. /** @see Zend_Http_Client_Exception */
  1117. require_once 'Zend/Http/Client/Exception.php';
  1118. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1119. }
  1120. return $authHeader;
  1121. }
  1122. /**
  1123. * Convert an array of parameters into a flat array of (key, value) pairs
  1124. *
  1125. * Will flatten a potentially multi-dimentional array of parameters (such
  1126. * as POST parameters) into a flat array of (key, value) paris. In case
  1127. * of multi-dimentional arrays, square brackets ([]) will be added to the
  1128. * key to indicate an array.
  1129. *
  1130. * @since 1.9
  1131. *
  1132. * @param array $parray
  1133. * @param string $prefix
  1134. * @return array
  1135. */
  1136. static protected function _flattenParametersArray($parray, $prefix = null)
  1137. {
  1138. if (! is_array($parray)) {
  1139. return $parray;
  1140. }
  1141. $parameters = array();
  1142. foreach($parray as $name => $value) {
  1143. // Calculate array key
  1144. if ($prefix) {
  1145. if (is_int($name)) {
  1146. $key = $prefix . '[]';
  1147. } else {
  1148. $key = $prefix . "[$name]";
  1149. }
  1150. } else {
  1151. $key = $name;
  1152. }
  1153. if (is_array($value)) {
  1154. $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
  1155. } else {
  1156. $parameters[] = array($key, $value);
  1157. }
  1158. }
  1159. return $parameters;
  1160. }
  1161. }