Client.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. // Cast integers and floats to strings for purposes of header representation.
  1393. if (is_int($value) || is_float($value)) {
  1394. $value = (string) $value;
  1395. }
  1396. if (! is_string($value) && (! is_object($value) || ! method_exists($value, '__toString'))) {
  1397. #require_once 'Zend/Http/Exception.php';
  1398. throw new Zend_Http_Exception('Invalid header value detected');
  1399. }
  1400. Zend_Http_Header_HeaderValue::assertValid($value);
  1401. }
  1402. }