Client.php 45 KB

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