Client.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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-2008 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-2008 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[$formname] = array(basename($filename), $ctype, $data);
  616. return $this;
  617. }
  618. /**
  619. * Set the encoding type for POST data
  620. *
  621. * @param string $enctype
  622. * @return Zend_Http_Client
  623. */
  624. public function setEncType($enctype = self::ENC_URLENCODED)
  625. {
  626. $this->enctype = $enctype;
  627. return $this;
  628. }
  629. /**
  630. * Set the raw (already encoded) POST data.
  631. *
  632. * This function is here for two reasons:
  633. * 1. For advanced user who would like to set their own data, already encoded
  634. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  635. * this method will be used to set the encoded data.
  636. *
  637. * @param string $data
  638. * @param string $enctype
  639. * @return Zend_Http_Client
  640. */
  641. public function setRawData($data, $enctype = null)
  642. {
  643. $this->raw_post_data = $data;
  644. $this->setEncType($enctype);
  645. return $this;
  646. }
  647. /**
  648. * Clear all GET and POST parameters
  649. *
  650. * Should be used to reset the request parameters if the client is
  651. * used for several concurrent requests.
  652. *
  653. * @return Zend_Http_Client
  654. */
  655. public function resetParameters()
  656. {
  657. // Reset parameter data
  658. $this->paramsGet = array();
  659. $this->paramsPost = array();
  660. $this->files = array();
  661. $this->raw_post_data = null;
  662. // Clear outdated headers
  663. if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
  664. unset($this->headers[strtolower(self::CONTENT_TYPE)]);
  665. }
  666. if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
  667. unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
  668. }
  669. return $this;
  670. }
  671. /**
  672. * Get the last HTTP request as string
  673. *
  674. * @return string
  675. */
  676. public function getLastRequest()
  677. {
  678. return $this->last_request;
  679. }
  680. /**
  681. * Get the last HTTP response received by this client
  682. *
  683. * If $config['storeresponse'] is set to false, or no response was
  684. * stored yet, will return null
  685. *
  686. * @return Zend_Http_Response or null if none
  687. */
  688. public function getLastResponse()
  689. {
  690. return $this->last_response;
  691. }
  692. /**
  693. * Load the connection adapter
  694. *
  695. * While this method is not called more than one for a client, it is
  696. * seperated from ->request() to preserve logic and readability
  697. *
  698. * @param Zend_Http_Client_Adapter_Interface|string $adapter
  699. * @return null
  700. * @throws Zend_Http_Client_Exception
  701. */
  702. public function setAdapter($adapter)
  703. {
  704. if (is_string($adapter)) {
  705. if (!class_exists($adapter)) {
  706. try {
  707. require_once 'Zend/Loader.php';
  708. Zend_Loader::loadClass($adapter);
  709. } catch (Zend_Exception $e) {
  710. /** @see Zend_Http_Client_Exception */
  711. require_once 'Zend/Http/Client/Exception.php';
  712. throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
  713. }
  714. }
  715. $adapter = new $adapter;
  716. }
  717. if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
  718. /** @see Zend_Http_Client_Exception */
  719. require_once 'Zend/Http/Client/Exception.php';
  720. throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  721. }
  722. $this->adapter = $adapter;
  723. $config = $this->config;
  724. unset($config['adapter']);
  725. $this->adapter->setConfig($config);
  726. }
  727. /**
  728. * Send the HTTP request and return an HTTP response object
  729. *
  730. * @param string $method
  731. * @return Zend_Http_Response
  732. * @throws Zend_Http_Client_Exception
  733. */
  734. public function request($method = null)
  735. {
  736. if (! $this->uri instanceof Zend_Uri_Http) {
  737. /** @see Zend_Http_Client_Exception */
  738. require_once 'Zend/Http/Client/Exception.php';
  739. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  740. }
  741. if ($method) {
  742. $this->setMethod($method);
  743. }
  744. $this->redirectCounter = 0;
  745. $response = null;
  746. // Make sure the adapter is loaded
  747. if ($this->adapter == null) {
  748. $this->setAdapter($this->config['adapter']);
  749. }
  750. // Send the first request. If redirected, continue.
  751. do {
  752. // Clone the URI and add the additional GET parameters to it
  753. $uri = clone $this->uri;
  754. if (! empty($this->paramsGet)) {
  755. $query = $uri->getQuery();
  756. if (! empty($query)) {
  757. $query .= '&';
  758. }
  759. $query .= http_build_query($this->paramsGet, null, '&');
  760. $uri->setQuery($query);
  761. }
  762. $body = $this->_prepareBody();
  763. $headers = $this->_prepareHeaders();
  764. // Open the connection, send the request and read the response
  765. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  766. ($uri->getScheme() == 'https' ? true : false));
  767. $this->last_request = $this->adapter->write($this->method,
  768. $uri, $this->config['httpversion'], $headers, $body);
  769. $response = $this->adapter->read();
  770. if (! $response) {
  771. /** @see Zend_Http_Client_Exception */
  772. require_once 'Zend/Http/Client/Exception.php';
  773. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  774. }
  775. $response = Zend_Http_Response::fromString($response);
  776. if ($this->config['storeresponse']) {
  777. $this->last_response = $response;
  778. }
  779. // Load cookies into cookie jar
  780. if (isset($this->cookiejar)) {
  781. $this->cookiejar->addCookiesFromResponse($response, $uri);
  782. }
  783. // If we got redirected, look for the Location header
  784. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  785. // Check whether we send the exact same request again, or drop the parameters
  786. // and send a GET request
  787. if ($response->getStatus() == 303 ||
  788. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  789. $response->getStatus() == 301))) {
  790. $this->resetParameters();
  791. $this->setMethod(self::GET);
  792. }
  793. // If we got a well formed absolute URI
  794. if (Zend_Uri_Http::check($location)) {
  795. $this->setHeaders('host', null);
  796. $this->setUri($location);
  797. } else {
  798. // Split into path and query and set the query
  799. if (strpos($location, '?') !== false) {
  800. list($location, $query) = explode('?', $location, 2);
  801. } else {
  802. $query = '';
  803. }
  804. $this->uri->setQuery($query);
  805. // Else, if we got just an absolute path, set it
  806. if(strpos($location, '/') === 0) {
  807. $this->uri->setPath($location);
  808. // Else, assume we have a relative path
  809. } else {
  810. // Get the current path directory, removing any trailing slashes
  811. $path = $this->uri->getPath();
  812. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  813. $this->uri->setPath($path . '/' . $location);
  814. }
  815. }
  816. ++$this->redirectCounter;
  817. } else {
  818. // If we didn't get any location, stop redirecting
  819. break;
  820. }
  821. } while ($this->redirectCounter < $this->config['maxredirects']);
  822. return $response;
  823. }
  824. /**
  825. * Prepare the request headers
  826. *
  827. * @return array
  828. */
  829. protected function _prepareHeaders()
  830. {
  831. $headers = array();
  832. // Set the host header
  833. if (! isset($this->headers['host'])) {
  834. $host = $this->uri->getHost();
  835. // If the port is not default, add it
  836. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  837. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  838. $host .= ':' . $this->uri->getPort();
  839. }
  840. $headers[] = "Host: {$host}";
  841. }
  842. // Set the connection header
  843. if (! isset($this->headers['connection'])) {
  844. if (! $this->config['keepalive']) {
  845. $headers[] = "Connection: close";
  846. }
  847. }
  848. // Set the Accept-encoding header if not set - depending on whether
  849. // zlib is available or not.
  850. if (! isset($this->headers['accept-encoding'])) {
  851. if (function_exists('gzinflate')) {
  852. $headers[] = 'Accept-encoding: gzip, deflate';
  853. } else {
  854. $headers[] = 'Accept-encoding: identity';
  855. }
  856. }
  857. // Set the Content-Type header
  858. if ($this->method == self::POST &&
  859. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  860. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  861. }
  862. // Set the user agent header
  863. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  864. $headers[] = "User-Agent: {$this->config['useragent']}";
  865. }
  866. // Set HTTP authentication if needed
  867. if (is_array($this->auth)) {
  868. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  869. $headers[] = "Authorization: {$auth}";
  870. }
  871. // Load cookies from cookie jar
  872. if (isset($this->cookiejar)) {
  873. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  874. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  875. if ($cookstr) {
  876. $headers[] = "Cookie: {$cookstr}";
  877. }
  878. }
  879. // Add all other user defined headers
  880. foreach ($this->headers as $header) {
  881. list($name, $value) = $header;
  882. if (is_array($value)) {
  883. $value = implode(', ', $value);
  884. }
  885. $headers[] = "$name: $value";
  886. }
  887. return $headers;
  888. }
  889. /**
  890. * Prepare the request body (for POST and PUT requests)
  891. *
  892. * @return string
  893. * @throws Zend_Http_Client_Exception
  894. */
  895. protected function _prepareBody()
  896. {
  897. // According to RFC2616, a TRACE request should not have a body.
  898. if ($this->method == self::TRACE) {
  899. return '';
  900. }
  901. // If we have raw_post_data set, just use it as the body.
  902. if (isset($this->raw_post_data)) {
  903. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  904. return $this->raw_post_data;
  905. }
  906. $body = '';
  907. // If we have files to upload, force enctype to multipart/form-data
  908. if (count ($this->files) > 0) {
  909. $this->setEncType(self::ENC_FORMDATA);
  910. }
  911. // If we have POST parameters or files, encode and add them to the body
  912. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  913. switch($this->enctype) {
  914. case self::ENC_FORMDATA:
  915. // Encode body as multipart/form-data
  916. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  917. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  918. // Get POST parameters and encode them
  919. $params = $this->_getParametersRecursive($this->paramsPost);
  920. foreach ($params as $pp) {
  921. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  922. }
  923. // Encode files
  924. foreach ($this->files as $name => $file) {
  925. $fhead = array(self::CONTENT_TYPE => $file[1]);
  926. $body .= self::encodeFormData($boundary, $name, $file[2], $file[0], $fhead);
  927. }
  928. $body .= "--{$boundary}--\r\n";
  929. break;
  930. case self::ENC_URLENCODED:
  931. // Encode body as application/x-www-form-urlencoded
  932. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  933. $body = http_build_query($this->paramsPost, '', '&');
  934. break;
  935. default:
  936. /** @see Zend_Http_Client_Exception */
  937. require_once 'Zend/Http/Client/Exception.php';
  938. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  939. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  940. break;
  941. }
  942. }
  943. // Set the Content-Length if we have a body or if request is POST/PUT
  944. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  945. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  946. }
  947. return $body;
  948. }
  949. /**
  950. * Helper method that gets a possibly multi-level parameters array (get or
  951. * post) and flattens it.
  952. *
  953. * The method returns an array of (key, value) pairs (because keys are not
  954. * necessarily unique. If one of the parameters in as array, it will also
  955. * add a [] suffix to the key.
  956. *
  957. * @param array $parray The parameters array
  958. * @param bool $urlencode Whether to urlencode the name and value
  959. * @return array
  960. */
  961. protected function _getParametersRecursive($parray, $urlencode = false)
  962. {
  963. if (! is_array($parray)) {
  964. return $parray;
  965. }
  966. $parameters = array();
  967. foreach ($parray as $name => $value) {
  968. if ($urlencode) {
  969. $name = urlencode($name);
  970. }
  971. // If $value is an array, iterate over it
  972. if (is_array($value)) {
  973. $name .= ($urlencode ? '%5B%5D' : '[]');
  974. foreach ($value as $subval) {
  975. if ($urlencode) {
  976. $subval = urlencode($subval);
  977. }
  978. $parameters[] = array($name, $subval);
  979. }
  980. } else {
  981. if ($urlencode) {
  982. $value = urlencode($value);
  983. }
  984. $parameters[] = array($name, $value);
  985. }
  986. }
  987. return $parameters;
  988. }
  989. /**
  990. * Attempt to detect the MIME type of a file using available extensions
  991. *
  992. * This method will try to detect the MIME type of a file. If the fileinfo
  993. * extension is available, it will be used. If not, the mime_magic
  994. * extension which is deprected but is still available in many PHP setups
  995. * will be tried.
  996. *
  997. * If neither extension is available, the default application/octet-stream
  998. * MIME type will be returned
  999. *
  1000. * @param string $file File path
  1001. * @return string MIME type
  1002. */
  1003. protected function _detectFileMimeType($file)
  1004. {
  1005. $type = null;
  1006. // First try with fileinfo functions
  1007. if (function_exists('finfo_open')) {
  1008. if (self::$_fileInfoDb === null) {
  1009. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1010. }
  1011. if (self::$_fileInfoDb) {
  1012. $type = finfo_file(self::$_fileInfoDb, $file);
  1013. }
  1014. } elseif (function_exists('mime_content_type')) {
  1015. $type = mime_content_type($file);
  1016. }
  1017. // Fallback to the default application/octet-stream
  1018. if (! $type) {
  1019. $type = 'application/octet-stream';
  1020. }
  1021. return $type;
  1022. }
  1023. /**
  1024. * Encode data to a multipart/form-data part suitable for a POST request.
  1025. *
  1026. * @param string $boundary
  1027. * @param string $name
  1028. * @param mixed $value
  1029. * @param string $filename
  1030. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1031. * @return string
  1032. */
  1033. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1034. $ret = "--{$boundary}\r\n" .
  1035. 'Content-Disposition: form-data; name="' . $name .'"';
  1036. if ($filename) {
  1037. $ret .= '; filename="' . $filename . '"';
  1038. }
  1039. $ret .= "\r\n";
  1040. foreach ($headers as $hname => $hvalue) {
  1041. $ret .= "{$hname}: {$hvalue}\r\n";
  1042. }
  1043. $ret .= "\r\n";
  1044. $ret .= "{$value}\r\n";
  1045. return $ret;
  1046. }
  1047. /**
  1048. * Create a HTTP authentication "Authorization:" header according to the
  1049. * specified user, password and authentication method.
  1050. *
  1051. * @see http://www.faqs.org/rfcs/rfc2617.html
  1052. * @param string $user
  1053. * @param string $password
  1054. * @param string $type
  1055. * @return string
  1056. * @throws Zend_Http_Client_Exception
  1057. */
  1058. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1059. {
  1060. $authHeader = null;
  1061. switch ($type) {
  1062. case self::AUTH_BASIC:
  1063. // In basic authentication, the user name cannot contain ":"
  1064. if (strpos($user, ':') !== false) {
  1065. /** @see Zend_Http_Client_Exception */
  1066. require_once 'Zend/Http/Client/Exception.php';
  1067. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1068. }
  1069. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1070. break;
  1071. //case self::AUTH_DIGEST:
  1072. /**
  1073. * @todo Implement digest authentication
  1074. */
  1075. // break;
  1076. default:
  1077. /** @see Zend_Http_Client_Exception */
  1078. require_once 'Zend/Http/Client/Exception.php';
  1079. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1080. }
  1081. return $authHeader;
  1082. }
  1083. }