Client.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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 || $method == self::PUT || $method == self::DELETE) && $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. if (null === $this->adapter) {
  796. $this->setAdapter($this->config['adapter']);
  797. }
  798. return $this->adapter;
  799. }
  800. /**
  801. * Set streaming for received data
  802. *
  803. * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming
  804. * @return Zend_Http_Client
  805. */
  806. public function setStream($streamfile = true)
  807. {
  808. $this->setConfig(array("output_stream" => $streamfile));
  809. return $this;
  810. }
  811. /**
  812. * Get status of streaming for received data
  813. * @return boolean|string
  814. */
  815. public function getStream()
  816. {
  817. return $this->config["output_stream"];
  818. }
  819. /**
  820. * Create temporary stream
  821. *
  822. * @return resource
  823. */
  824. protected function _openTempStream()
  825. {
  826. $this->_stream_name = $this->config['output_stream'];
  827. if(!is_string($this->_stream_name)) {
  828. // If name is not given, create temp name
  829. $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(),
  830. 'Zend_Http_Client');
  831. }
  832. if (false === ($fp = @fopen($this->_stream_name, "w+b"))) {
  833. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  834. $this->adapter->close();
  835. }
  836. require_once 'Zend/Http/Client/Exception.php';
  837. throw new Zend_Http_Client_Exception("Could not open temp file {$this->_stream_name}");
  838. }
  839. return $fp;
  840. }
  841. /**
  842. * Send the HTTP request and return an HTTP response object
  843. *
  844. * @param string $method
  845. * @return Zend_Http_Response
  846. * @throws Zend_Http_Client_Exception
  847. */
  848. public function request($method = null)
  849. {
  850. if (! $this->uri instanceof Zend_Uri_Http) {
  851. /** @see Zend_Http_Client_Exception */
  852. require_once 'Zend/Http/Client/Exception.php';
  853. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  854. }
  855. if ($method) {
  856. $this->setMethod($method);
  857. }
  858. $this->redirectCounter = 0;
  859. $response = null;
  860. // Make sure the adapter is loaded
  861. if ($this->adapter == null) {
  862. $this->setAdapter($this->config['adapter']);
  863. }
  864. // Send the first request. If redirected, continue.
  865. do {
  866. // Clone the URI and add the additional GET parameters to it
  867. $uri = clone $this->uri;
  868. if (! empty($this->paramsGet)) {
  869. $query = $uri->getQuery();
  870. if (! empty($query)) {
  871. $query .= '&';
  872. }
  873. $query .= http_build_query($this->paramsGet, null, '&');
  874. if ($this->config['rfc3986_strict']) {
  875. $query = str_replace('+', '%20', $query);
  876. }
  877. $uri->setQuery($query);
  878. }
  879. $body = $this->_prepareBody();
  880. $headers = $this->_prepareHeaders();
  881. // check that adapter supports streaming before using it
  882. if(is_resource($body) && !($this->adapter instanceof Zend_Http_Client_Adapter_Stream)) {
  883. /** @see Zend_Http_Client_Exception */
  884. require_once 'Zend/Http/Client/Exception.php';
  885. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  886. }
  887. // Open the connection, send the request and read the response
  888. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  889. ($uri->getScheme() == 'https' ? true : false));
  890. if($this->config['output_stream']) {
  891. if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
  892. $stream = $this->_openTempStream();
  893. $this->adapter->setOutputStream($stream);
  894. } else {
  895. /** @see Zend_Http_Client_Exception */
  896. require_once 'Zend/Http/Client/Exception.php';
  897. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  898. }
  899. }
  900. $this->last_request = $this->adapter->write($this->method,
  901. $uri, $this->config['httpversion'], $headers, $body);
  902. $response = $this->adapter->read();
  903. if (! $response) {
  904. /** @see Zend_Http_Client_Exception */
  905. require_once 'Zend/Http/Client/Exception.php';
  906. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  907. }
  908. if($this->config['output_stream']) {
  909. rewind($stream);
  910. // cleanup the adapter
  911. $this->adapter->setOutputStream(null);
  912. $response = Zend_Http_Response_Stream::fromStream($response, $stream);
  913. $response->setStreamName($this->_stream_name);
  914. if(!is_string($this->config['output_stream'])) {
  915. // we used temp name, will need to clean up
  916. $response->setCleanup(true);
  917. }
  918. } else {
  919. $response = Zend_Http_Response::fromString($response);
  920. }
  921. if ($this->config['storeresponse']) {
  922. $this->last_response = $response;
  923. }
  924. // Load cookies into cookie jar
  925. if (isset($this->cookiejar)) {
  926. $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']);
  927. }
  928. // If we got redirected, look for the Location header
  929. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  930. // Avoid problems with buggy servers that add whitespace at the
  931. // end of some headers (See ZF-11283)
  932. $location = trim($location);
  933. // Check whether we send the exact same request again, or drop the parameters
  934. // and send a GET request
  935. if ($response->getStatus() == 303 ||
  936. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  937. $response->getStatus() == 301))) {
  938. $this->resetParameters();
  939. $this->setMethod(self::GET);
  940. }
  941. // If we got a well formed absolute URI
  942. if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:')) {
  943. $this->setHeaders('host', null);
  944. $this->setUri($location);
  945. } else {
  946. // Split into path and query and set the query
  947. if (strpos($location, '?') !== false) {
  948. list($location, $query) = explode('?', $location, 2);
  949. } else {
  950. $query = '';
  951. }
  952. $this->uri->setQuery($query);
  953. // Else, if we got just an absolute path, set it
  954. if(strpos($location, '/') === 0) {
  955. $this->uri->setPath($location);
  956. // Else, assume we have a relative path
  957. } else {
  958. // Get the current path directory, removing any trailing slashes
  959. $path = $this->uri->getPath();
  960. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  961. $this->uri->setPath($path . '/' . $location);
  962. }
  963. }
  964. ++$this->redirectCounter;
  965. } else {
  966. // If we didn't get any location, stop redirecting
  967. break;
  968. }
  969. } while ($this->redirectCounter < $this->config['maxredirects']);
  970. return $response;
  971. }
  972. /**
  973. * Prepare the request headers
  974. *
  975. * @return array
  976. */
  977. protected function _prepareHeaders()
  978. {
  979. $headers = array();
  980. // Set the host header
  981. if (! isset($this->headers['host'])) {
  982. $host = $this->uri->getHost();
  983. // If the port is not default, add it
  984. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  985. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  986. $host .= ':' . $this->uri->getPort();
  987. }
  988. $headers[] = "Host: {$host}";
  989. }
  990. // Set the connection header
  991. if (! isset($this->headers['connection'])) {
  992. if (! $this->config['keepalive']) {
  993. $headers[] = "Connection: close";
  994. }
  995. }
  996. // Set the Accept-encoding header if not set - depending on whether
  997. // zlib is available or not.
  998. if (! isset($this->headers['accept-encoding'])) {
  999. if (function_exists('gzinflate')) {
  1000. $headers[] = 'Accept-encoding: gzip, deflate';
  1001. } else {
  1002. $headers[] = 'Accept-encoding: identity';
  1003. }
  1004. }
  1005. // Set the Content-Type header
  1006. if (($this->method == self::POST || $this->method == self::PUT) &&
  1007. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  1008. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  1009. }
  1010. // Set the user agent header
  1011. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  1012. $headers[] = "User-Agent: {$this->config['useragent']}";
  1013. }
  1014. // Set HTTP authentication if needed
  1015. if (is_array($this->auth)) {
  1016. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  1017. $headers[] = "Authorization: {$auth}";
  1018. }
  1019. // Load cookies from cookie jar
  1020. if (isset($this->cookiejar)) {
  1021. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  1022. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  1023. if ($cookstr) {
  1024. $headers[] = "Cookie: {$cookstr}";
  1025. }
  1026. }
  1027. // Add all other user defined headers
  1028. foreach ($this->headers as $header) {
  1029. list($name, $value) = $header;
  1030. if (is_array($value)) {
  1031. $value = implode(', ', $value);
  1032. }
  1033. $headers[] = "$name: $value";
  1034. }
  1035. return $headers;
  1036. }
  1037. /**
  1038. * Prepare the request body (for POST and PUT requests)
  1039. *
  1040. * @return string
  1041. * @throws Zend_Http_Client_Exception
  1042. */
  1043. protected function _prepareBody()
  1044. {
  1045. // According to RFC2616, a TRACE request should not have a body.
  1046. if ($this->method == self::TRACE) {
  1047. return '';
  1048. }
  1049. if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) {
  1050. return $this->raw_post_data;
  1051. }
  1052. // If mbstring overloads substr and strlen functions, we have to
  1053. // override it's internal encoding
  1054. if (function_exists('mb_internal_encoding') &&
  1055. ((int) ini_get('mbstring.func_overload')) & 2) {
  1056. $mbIntEnc = mb_internal_encoding();
  1057. mb_internal_encoding('ASCII');
  1058. }
  1059. // If we have raw_post_data set, just use it as the body.
  1060. if (isset($this->raw_post_data)) {
  1061. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  1062. if (isset($mbIntEnc)) {
  1063. mb_internal_encoding($mbIntEnc);
  1064. }
  1065. return $this->raw_post_data;
  1066. }
  1067. $body = '';
  1068. // If we have files to upload, force enctype to multipart/form-data
  1069. if (count ($this->files) > 0) {
  1070. $this->setEncType(self::ENC_FORMDATA);
  1071. }
  1072. // If we have POST parameters or files, encode and add them to the body
  1073. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  1074. switch($this->enctype) {
  1075. case self::ENC_FORMDATA:
  1076. // Encode body as multipart/form-data
  1077. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  1078. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  1079. // Encode all files and POST vars in the order they were given
  1080. foreach ($this->body_field_order as $fieldName=>$fieldType) {
  1081. switch ($fieldType) {
  1082. case self::VTYPE_FILE:
  1083. foreach ($this->files as $file) {
  1084. if ($file['formname']===$fieldName) {
  1085. $fhead = array(self::CONTENT_TYPE => $file['ctype']);
  1086. $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
  1087. }
  1088. }
  1089. break;
  1090. case self::VTYPE_SCALAR:
  1091. if (isset($this->paramsPost[$fieldName])) {
  1092. if (is_array($this->paramsPost[$fieldName])) {
  1093. $flattened = self::_flattenParametersArray($this->paramsPost[$fieldName], $fieldName);
  1094. foreach ($flattened as $pp) {
  1095. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  1096. }
  1097. } else {
  1098. $body .= self::encodeFormData($boundary, $fieldName, $this->paramsPost[$fieldName]);
  1099. }
  1100. }
  1101. break;
  1102. }
  1103. }
  1104. $body .= "--{$boundary}--\r\n";
  1105. break;
  1106. case self::ENC_URLENCODED:
  1107. // Encode body as application/x-www-form-urlencoded
  1108. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  1109. $body = http_build_query($this->paramsPost, '', '&');
  1110. break;
  1111. default:
  1112. if (isset($mbIntEnc)) {
  1113. mb_internal_encoding($mbIntEnc);
  1114. }
  1115. /** @see Zend_Http_Client_Exception */
  1116. require_once 'Zend/Http/Client/Exception.php';
  1117. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  1118. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  1119. break;
  1120. }
  1121. }
  1122. // Set the Content-Length if we have a body or if request is POST/PUT
  1123. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  1124. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  1125. }
  1126. if (isset($mbIntEnc)) {
  1127. mb_internal_encoding($mbIntEnc);
  1128. }
  1129. return $body;
  1130. }
  1131. /**
  1132. * Helper method that gets a possibly multi-level parameters array (get or
  1133. * post) and flattens it.
  1134. *
  1135. * The method returns an array of (key, value) pairs (because keys are not
  1136. * necessarily unique. If one of the parameters in as array, it will also
  1137. * add a [] suffix to the key.
  1138. *
  1139. * This method is deprecated since Zend Framework 1.9 in favour of
  1140. * self::_flattenParametersArray() and will be dropped in 2.0
  1141. *
  1142. * @deprecated since 1.9
  1143. *
  1144. * @param array $parray The parameters array
  1145. * @param bool $urlencode Whether to urlencode the name and value
  1146. * @return array
  1147. */
  1148. protected function _getParametersRecursive($parray, $urlencode = false)
  1149. {
  1150. // Issue a deprecated notice
  1151. trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
  1152. E_USER_NOTICE);
  1153. if (! is_array($parray)) {
  1154. return $parray;
  1155. }
  1156. $parameters = array();
  1157. foreach ($parray as $name => $value) {
  1158. if ($urlencode) {
  1159. $name = urlencode($name);
  1160. }
  1161. // If $value is an array, iterate over it
  1162. if (is_array($value)) {
  1163. $name .= ($urlencode ? '%5B%5D' : '[]');
  1164. foreach ($value as $subval) {
  1165. if ($urlencode) {
  1166. $subval = urlencode($subval);
  1167. }
  1168. $parameters[] = array($name, $subval);
  1169. }
  1170. } else {
  1171. if ($urlencode) {
  1172. $value = urlencode($value);
  1173. }
  1174. $parameters[] = array($name, $value);
  1175. }
  1176. }
  1177. return $parameters;
  1178. }
  1179. /**
  1180. * Attempt to detect the MIME type of a file using available extensions
  1181. *
  1182. * This method will try to detect the MIME type of a file. If the fileinfo
  1183. * extension is available, it will be used. If not, the mime_magic
  1184. * extension which is deprected but is still available in many PHP setups
  1185. * will be tried.
  1186. *
  1187. * If neither extension is available, the default application/octet-stream
  1188. * MIME type will be returned
  1189. *
  1190. * @param string $file File path
  1191. * @return string MIME type
  1192. */
  1193. protected function _detectFileMimeType($file)
  1194. {
  1195. $type = null;
  1196. // First try with fileinfo functions
  1197. if (function_exists('finfo_open')) {
  1198. if (self::$_fileInfoDb === null) {
  1199. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1200. }
  1201. if (self::$_fileInfoDb) {
  1202. $type = finfo_file(self::$_fileInfoDb, $file);
  1203. }
  1204. } elseif (function_exists('mime_content_type')) {
  1205. $type = mime_content_type($file);
  1206. }
  1207. // Fallback to the default application/octet-stream
  1208. if (! $type) {
  1209. $type = 'application/octet-stream';
  1210. }
  1211. return $type;
  1212. }
  1213. /**
  1214. * Encode data to a multipart/form-data part suitable for a POST request.
  1215. *
  1216. * @param string $boundary
  1217. * @param string $name
  1218. * @param mixed $value
  1219. * @param string $filename
  1220. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1221. * @return string
  1222. */
  1223. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1224. $ret = "--{$boundary}\r\n" .
  1225. 'Content-Disposition: form-data; name="' . $name .'"';
  1226. if ($filename) {
  1227. $ret .= '; filename="' . $filename . '"';
  1228. }
  1229. $ret .= "\r\n";
  1230. foreach ($headers as $hname => $hvalue) {
  1231. $ret .= "{$hname}: {$hvalue}\r\n";
  1232. }
  1233. $ret .= "\r\n";
  1234. $ret .= "{$value}\r\n";
  1235. return $ret;
  1236. }
  1237. /**
  1238. * Create a HTTP authentication "Authorization:" header according to the
  1239. * specified user, password and authentication method.
  1240. *
  1241. * @see http://www.faqs.org/rfcs/rfc2617.html
  1242. * @param string $user
  1243. * @param string $password
  1244. * @param string $type
  1245. * @return string
  1246. * @throws Zend_Http_Client_Exception
  1247. */
  1248. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1249. {
  1250. $authHeader = null;
  1251. switch ($type) {
  1252. case self::AUTH_BASIC:
  1253. // In basic authentication, the user name cannot contain ":"
  1254. if (strpos($user, ':') !== false) {
  1255. /** @see Zend_Http_Client_Exception */
  1256. require_once 'Zend/Http/Client/Exception.php';
  1257. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1258. }
  1259. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1260. break;
  1261. //case self::AUTH_DIGEST:
  1262. /**
  1263. * @todo Implement digest authentication
  1264. */
  1265. // break;
  1266. default:
  1267. /** @see Zend_Http_Client_Exception */
  1268. require_once 'Zend/Http/Client/Exception.php';
  1269. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1270. }
  1271. return $authHeader;
  1272. }
  1273. /**
  1274. * Convert an array of parameters into a flat array of (key, value) pairs
  1275. *
  1276. * Will flatten a potentially multi-dimentional array of parameters (such
  1277. * as POST parameters) into a flat array of (key, value) paris. In case
  1278. * of multi-dimentional arrays, square brackets ([]) will be added to the
  1279. * key to indicate an array.
  1280. *
  1281. * @since 1.9
  1282. *
  1283. * @param array $parray
  1284. * @param string $prefix
  1285. * @return array
  1286. */
  1287. static protected function _flattenParametersArray($parray, $prefix = null)
  1288. {
  1289. if (! is_array($parray)) {
  1290. return $parray;
  1291. }
  1292. $parameters = array();
  1293. foreach($parray as $name => $value) {
  1294. // Calculate array key
  1295. if ($prefix) {
  1296. if (is_int($name)) {
  1297. $key = $prefix . '[]';
  1298. } else {
  1299. $key = $prefix . "[$name]";
  1300. }
  1301. } else {
  1302. $key = $name;
  1303. }
  1304. if (is_array($value)) {
  1305. $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
  1306. } else {
  1307. $parameters[] = array($key, $value);
  1308. }
  1309. }
  1310. return $parameters;
  1311. }
  1312. }