Client.php 48 KB

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