Client.php 49 KB

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