Client.php 50 KB

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