Client.php 49 KB

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