Resty.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. <?php
  2. /**
  3. * A simple PHP library for doing RESTful HTTP stuff. Does *not* require the curl extension.
  4. * @link https://github.com/fictivekin/resty.php
  5. */
  6. class Resty
  7. {
  8. /**
  9. * The version of this lib
  10. */
  11. const VERSION = '0.3.8';
  12. const DEFAULT_TIMEOUT = 240;
  13. /**
  14. * @var bool enables debugging output
  15. */
  16. protected $debug = false;
  17. /**
  18. * logging function (should be a Closure)
  19. * @var Closure
  20. */
  21. protected $logger = null;
  22. /**
  23. * @var bool whether or not to auto-parse the response body as JSON or XML
  24. */
  25. protected $parse_body = true;
  26. /**
  27. * @var string
  28. * @see Resty::getUserAgent()
  29. */
  30. protected $user_agent = null;
  31. /**
  32. * @var string
  33. */
  34. protected $base_url;
  35. /**
  36. * Stores the last request hash
  37. * @var array
  38. */
  39. protected $last_request;
  40. /**
  41. * Stores the last response hash
  42. * @var array
  43. */
  44. protected $last_response;
  45. /**
  46. * stores anon func callbacks (because you can't store them as obj props
  47. * @var array
  48. */
  49. protected $callbacks = array();
  50. /**
  51. * username for basic auth
  52. * @var string
  53. */
  54. protected $username;
  55. /**
  56. * password for basic auth
  57. * @var string
  58. */
  59. protected $password;
  60. /**
  61. * by default, silence the fopen warning if we can't open the stream
  62. */
  63. protected $silence_fopen_warning = true;
  64. /**
  65. * by default, don't raise an exception if fopen() fails
  66. * @var boolean
  67. */
  68. protected $raise_fopen_exception = false;
  69. /**
  70. * content-types that will trigger JSON parsing of body
  71. * @var array
  72. */
  73. public static $JSON_TYPES = array(
  74. 'application/json',
  75. 'text/json',
  76. 'text/x-json',
  77. );
  78. /**
  79. * content-types that will trigger XML parsing
  80. * @var array
  81. */
  82. public static $XML_TYPES = array(
  83. 'application/xml',
  84. 'text/xml',
  85. 'application/rss+xml',
  86. 'application/xhtml+xml',
  87. 'application/atom+xml',
  88. 'application/xslt+xml',
  89. 'application/mathml+xml',
  90. );
  91. /**
  92. * Passed opts can include
  93. * $opts['onRequestLog'] - an anonymous function that takes the Resty::last_request property as arg
  94. * $opts['onResponseLog'] - an anonymous function that takes the Resty::last_response property as arg
  95. *
  96. * @see Resty::last_request
  97. * @see Resty::last_response
  98. * @see Resty::sendRequest()
  99. * @param array $opts OPTIONAL array of options
  100. */
  101. function __construct($opts=null) {
  102. if (!empty($opts['onRequestLog']) && ($opts['onRequestLog'] instanceof Closure)) {
  103. $this->callbacks['onRequestLog'] = $opts['onRequestLog'];
  104. }
  105. if (!empty($opts['onResponseLog']) && ($opts['onResponseLog'] instanceof Closure)) {
  106. $this->callbacks['onResponseLog'] = $opts['onResponseLog'];
  107. }
  108. if (isset($opts['silence_fopen_warning'])) {
  109. $this->silenceFopenWarning((bool)$opts['silence_fopen_warning']);
  110. }
  111. if (isset($opts['raise_fopen_exception'])) {
  112. $this->raiseFopenException((bool)$opts['raise_fopen_exception']);
  113. }
  114. }
  115. /**
  116. * retrieve the last request we sent
  117. *
  118. * valid keys are ['url', 'method', 'querydata', 'headers', 'options', 'opts']
  119. *
  120. * @param string $key just retrieve a given field from the hash
  121. * @return mixed
  122. */
  123. public function getLastRequest($key=null) {
  124. if (!isset($key)) {
  125. return $this->last_request;
  126. }
  127. return $this->last_request[$key];
  128. }
  129. /**
  130. * retrieve the last response we got
  131. *
  132. * valid keys are ['meta', 'status', 'headers', 'body']
  133. *
  134. * @param string $key just retrieve a given field from the hash
  135. * @return mixed
  136. */
  137. public function getLastResponse($key=null) {
  138. if (!isset($key)) {
  139. return $this->last_response;
  140. }
  141. return $this->last_response[$key];
  142. }
  143. /**
  144. * make a GET request
  145. *
  146. * @param string the URL. This will be appended to the base_url, if any set
  147. * @param array $querydata hash of key/val pairs
  148. * @param array $headers hash of key/val pairs
  149. * @param array $options hash of key/val pairs ('timeout')
  150. * @return array the response hash
  151. * @see Resty::sendRequest()
  152. */
  153. public function get($url, $querydata=null, $headers=null, $options=null) {
  154. return $this->sendRequest($url, 'GET', $querydata, $headers, $options);
  155. }
  156. /**
  157. * make a POST request
  158. *
  159. * @param string the URL. This will be appended to the base_url, if any set
  160. * @param array $querydata hash of key/val pairs
  161. * @param array $headers hash of key/val pairs
  162. * @param array $options hash of key/val pairs ('timeout')
  163. * @return array the response hash
  164. * @see Resty::sendRequest()
  165. */
  166. public function post($url, $querydata=null, $headers=null, $options=null) {
  167. return $this->sendRequest($url, 'POST', $querydata, $headers, $options);
  168. }
  169. /**
  170. * make a PUT request
  171. *
  172. * @param string the URL. This will be appended to the base_url, if any set
  173. * @param array $querydata hash of key/val pairs
  174. * @param array $headers hash of key/val pairs
  175. * @param array $options hash of key/val pairs ('timeout')
  176. * @return array the response hash
  177. * @see Resty::sendRequest()
  178. */
  179. public function put($url, $querydata=null, $headers=null, $options=null) {
  180. return $this->sendRequest($url, 'PUT', $querydata, $headers, $options);
  181. }
  182. /**
  183. * make a DELETE request
  184. *
  185. * @param string the URL. This will be appended to the base_url, if any set
  186. * @param array $querydata hash of key/val pairs
  187. * @param array $headers hash of key/val pairs
  188. * @param array $options hash of key/val pairs ('timeout')
  189. * @return array the response hash
  190. * @see Resty::sendRequest()
  191. */
  192. public function delete($url, $querydata=null, $headers=null, $options=null) {
  193. return $this->sendRequest($url, 'DELETE', $querydata, $headers, $options);
  194. }
  195. /**
  196. * @param string $url
  197. * @param array $files
  198. * @param array $params
  199. * @param array $headers
  200. * @param array $options
  201. *
  202. * The $files array should be a set of key/val pairs, with the key being
  203. * the field name, and the val the file path. ex:
  204. * $files['avatar'] = '/path/to/file.jpg';
  205. * $files['background'] = '/path/to/file2.jpg';
  206. *
  207. */
  208. public function postFiles($url, $files, $params=null, $headers=null, $options=null) {
  209. $datastr = "";
  210. $boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
  211. // build params
  212. if (isset($params)) {
  213. foreach($params as $key => $val) {
  214. $datastr .= "--$boundary\n";
  215. $datastr .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
  216. }
  217. }
  218. $datastr .= "--$boundary\n";
  219. // build files
  220. foreach($files as $key => $file)
  221. {
  222. $filename = pathinfo($file, PATHINFO_BASENAME);
  223. $content_type = $this->getMimeType($file);
  224. $fileContents = file_get_contents($file);
  225. $datastr .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$filename}\"\n";
  226. $datastr .= "Content-Type: {$content_type}\n";
  227. $datastr .= "Content-Transfer-Encoding: binary\n\n";
  228. $datastr .= $fileContents."\n";
  229. $datastr .= "--$boundary\n";
  230. }
  231. if (!isset($headers)) {
  232. $headers = array();
  233. }
  234. $headers['Content-Type'] = 'multipart/form-data; boundary='.$boundary;
  235. return $this->post($url, $datastr, $headers, $options);
  236. }
  237. /**
  238. * @param string $url
  239. * @param array $binary_data
  240. * @param array $params
  241. * @param array $headers
  242. * @param array $options
  243. *
  244. * The $binary_data array should be a set of key/val pairs, with the key being
  245. * the field name, and the val the binary data. ex:
  246. * $files['avatar'] = <BINARY>;
  247. * $files['background'] = <BINARY>;
  248. *
  249. * with that data, a multipart POST body is created, identical to a file
  250. * upload, just without reading the data from a file
  251. *
  252. */
  253. public function postBinary($url, $binary_data, $params=null, $headers=null, $options=null) {
  254. $datastr = "";
  255. $boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
  256. // build params
  257. if (isset($params)) {
  258. foreach($params as $key => $val) {
  259. $datastr .= "--$boundary\n";
  260. $datastr .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
  261. }
  262. }
  263. $datastr .= "--$boundary\n";
  264. // build files
  265. foreach($binary_data as $key => $bdata)
  266. {
  267. $filename = 'bdata';
  268. $content_type = 'application/octet-stream';
  269. $datastr .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$filename}\"\n";
  270. $datastr .= "Content-Type: {$content_type}\n";
  271. $datastr .= "Content-Transfer-Encoding: binary\n\n";
  272. $datastr .= $bdata."\n";
  273. $datastr .= "--$boundary\n";
  274. }
  275. if (!isset($headers)) {
  276. $headers = array();
  277. }
  278. $headers['Content-Type'] = 'multipart/form-data; boundary='.$boundary;
  279. return $this->post($url, $datastr, $headers, $options);
  280. }
  281. /**
  282. * @see Resty::postFiles()
  283. *
  284. * Stole this from the Amazon S3 class:
  285. *
  286. * Copyright (c) 2008, Donovan Schönknecht. All rights reserved.
  287. *
  288. * Redistribution and use in source and binary forms, with or without
  289. * modification, are permitted provided that the following conditions are met:
  290. *
  291. * - Redistributions of source code must retain the above copyright notice,
  292. * this list of conditions and the following disclaimer.
  293. * - Redistributions in binary form must reproduce the above copyright
  294. * notice, this list of conditions and the following disclaimer in the
  295. * documentation and/or other materials provided with the distribution.
  296. *
  297. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  298. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  299. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  300. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  301. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  302. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  303. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  304. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  305. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  306. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  307. * POSSIBILITY OF SUCH DAMAGE.
  308. *
  309. * Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates.
  310. *
  311. */
  312. protected function getMimeType($filepath) {
  313. if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
  314. ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
  315. if (($type = finfo_file($finfo, $filepath)) !== false) {
  316. // Remove the charset and grab the last content-type
  317. $type = explode(' ', str_replace('; charset=', ';charset=', $type));
  318. $type = array_pop($type);
  319. $type = explode(';', $type);
  320. $type = trim(array_shift($type));
  321. }
  322. finfo_close($finfo);
  323. // If anyone is still using mime_content_type()
  324. } elseif (function_exists('mime_content_type')) {
  325. $type = trim(mime_content_type($filepath));
  326. }
  327. if ($type !== false && strlen($type) > 0) { return $type; }
  328. // Otherwise do it the old fashioned way
  329. static $exts = array(
  330. 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
  331. 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
  332. 'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
  333. 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
  334. 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
  335. 'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
  336. 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
  337. 'css' => 'text/css', 'js' => 'text/javascript',
  338. 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
  339. 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
  340. 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
  341. 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
  342. );
  343. $ext = strtolower(pathInfo($filepath, PATHINFO_EXTENSION));
  344. return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
  345. }
  346. /**
  347. * bc wrapper
  348. */
  349. public function enableDebugging($state=false) {
  350. $this->debug($state);
  351. }
  352. /**
  353. * enable or disable debugging. If no arg passed, just returns current state
  354. * @param bool $state=null if not passed, state not changed
  355. * @return boolean the current state
  356. */
  357. public function debug($state=null) {
  358. if (isset($state)) {
  359. $this->debug = (bool)$state;
  360. }
  361. return $this->debug;
  362. }
  363. /**
  364. * raise an exception from fopen if trying to open stream fails
  365. * @param boolean $state=null optional, set the state
  366. * @return boolean the current state
  367. */
  368. public function raiseFopenException($state=null) {
  369. if (isset($state)) {
  370. $this->raise_fopen_exception = (bool)$state;
  371. }
  372. return $this->raise_fopen_exception;
  373. }
  374. /**
  375. * silence warnings from fopen when trying to open stream
  376. * @param boolean $state=null optional, set the state
  377. * @return boolean the current state
  378. */
  379. public function silenceFopenWarning($state=null) {
  380. if (isset($state)) {
  381. $this->silence_fopen_warning = (bool)$state;
  382. }
  383. return $this->silence_fopen_warning;
  384. }
  385. /**
  386. * sets an alternate logging method
  387. * @param Closure $logger
  388. */
  389. public function setLogger(Closure $logger) {
  390. $this->logger = $logger;
  391. }
  392. /**
  393. * enable or disable automatic parsing of body. default is true
  394. * @param bool $state default TRUE
  395. */
  396. public function parseBody($state=true) {
  397. $state = (bool)$state;
  398. $this->parse_body = $state;
  399. }
  400. /**
  401. * Sets the base URL for all subsequent requests
  402. * @param string $base_url
  403. */
  404. public function setBaseURL($base_url) {
  405. $this->base_url = $base_url;
  406. }
  407. /**
  408. * retrieves the current Resty::$base_url
  409. * @return string
  410. */
  411. public function getBaseURL() {
  412. return $this->base_url;
  413. }
  414. /**
  415. * Sets the user-agent
  416. * @param string $user_agent
  417. */
  418. public function setUserAgent($user_agent) {
  419. $this->user_agent = $user_agent;
  420. }
  421. /**
  422. * Gets the current user agent. if Resty::$user_agent is not set, uses a default
  423. * @return string
  424. */
  425. public function getUserAgent() {
  426. if (empty($this->user_agent)) {
  427. $this->user_agent = 'Resty ' . static::VERSION;
  428. }
  429. return $this->user_agent;
  430. }
  431. /**
  432. * Sets credentials for http basic auth
  433. * @param string $username
  434. * @param string $password
  435. */
  436. public function setCredentials($username, $password) {
  437. $this->username = $username;
  438. $this->password = $password;
  439. }
  440. /**
  441. * removes current credentials
  442. */
  443. public function clearCredentials() {
  444. $this->username = null;
  445. $this->password = null;
  446. }
  447. /**
  448. * takes a set of key/val pairs and builds an array of raw header strings
  449. *
  450. * @param string $headers
  451. * @return void
  452. * @author Ed Finkler
  453. */
  454. protected function buildHeadersArray($headers) {
  455. $str_headers = array();
  456. foreach ($headers as $key => $value) {
  457. $str_headers[] = "{$key}: {$value}";
  458. }
  459. return $str_headers;
  460. }
  461. /**
  462. * Extracts the headers of a response from the stream's meta data
  463. * @param array $meta
  464. * @return array
  465. */
  466. protected function metaToHeaders($meta) {
  467. $headers = array();
  468. if (!isset($meta['wrapper_data'])) {
  469. return $headers;
  470. }
  471. foreach ($meta['wrapper_data'] as $value) {
  472. if (strpos($value, 'HTTP') !== 0) {
  473. preg_match("|^([^:]+):\s?(.+)$|", $value, $matches);
  474. if (is_array($matches) && isset($matches[2])) {
  475. $headers[trim($matches[1])] = trim($matches[2], " \t\n\r\0\x0B\"");
  476. }
  477. }
  478. }
  479. return $headers;
  480. }
  481. /**
  482. * extracts the status code from the stream meta data
  483. * @param array $meta
  484. * @return integer
  485. */
  486. protected function getStatusCode($meta) {
  487. $matches = array();
  488. $status = 0;
  489. preg_match("|\s(\d\d\d)\s?|", $meta['wrapper_data'][0], $matches);
  490. if (is_array($matches) && isset($matches[1])) {
  491. $status = (int)trim($matches[1]);
  492. }
  493. return $status;
  494. }
  495. /**
  496. * Sends the HTTP request and retrieves/parses the response
  497. *
  498. * @param string $url
  499. * @param string $method
  500. * @param array $querydata OPTIONAL
  501. * @param array $headers OPTIONAL
  502. * @param array $options OPTIONAL
  503. * @return array
  504. * @author Ed Finkler
  505. */
  506. public function sendRequest($url, $method='GET', $querydata=null, $headers=null, $options=null) {
  507. $resp = array();
  508. if ($this->base_url) {
  509. $url = $this->base_url.$url;
  510. }
  511. // we need to supply a default content-type
  512. if (!isset($headers['Content-Type'])) {
  513. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  514. }
  515. // by default, pass the header "Connection: close"
  516. if (!isset($headers['Connection'])) {
  517. $headers['Connection'] = 'close';
  518. }
  519. // if we have a username and password, use it
  520. if (isset($this->username) && isset($this->password) && !isset($headers['Authorization'])) {
  521. $this->log("{$this->username}:{$this->password}");
  522. $headers['Authorization'] = 'Basic '.base64_encode("{$this->username}:{$this->password}");
  523. }
  524. // default timeout
  525. $timeout = isset($options['timeout']) ? $options['timeout'] : static::DEFAULT_TIMEOUT;
  526. $content = null;
  527. // if querydata is a string, just pass it as-is
  528. if (isset($querydata) && is_string($querydata)) {
  529. $content = $querydata;
  530. // else if it's an array, make an http query
  531. } elseif (isset($querydata) && is_array($querydata)) {
  532. $content = http_build_query($querydata);
  533. }
  534. // create an array of header strings from the hash
  535. $headerarr = isset($headers) ? $this->buildHeadersArray($headers) : array();
  536. // GET and DELETE should use the URL to pass data
  537. $urlcontent = ('GET' === $method || 'DELETE' === $method);
  538. // if this is a GET or DELETE and we have some $content, append to URL
  539. if ($urlcontent && isset($content)) {
  540. $url .= '?'.$content;
  541. }
  542. $opts = array(
  543. 'http'=>array(
  544. 'timeout'=>$timeout,
  545. 'method'=>$method,
  546. 'content'=> (!$urlcontent) ? $content : null,
  547. 'user_agent'=>$this->getUserAgent(),
  548. 'header'=>$headerarr,
  549. 'ignore_errors'=>1
  550. )
  551. );
  552. $this->log('URL =================');
  553. $this->log($url);
  554. $this->log('METHOD =================');
  555. $this->log($method);
  556. $this->log('QUERYDATA =================');
  557. $this->log($querydata);
  558. $this->log('HEADERS =================');
  559. $this->log($headers);
  560. $this->log('OPTIONS =================');
  561. $this->log($options);
  562. $this->log('OPTS =================');
  563. $this->log($opts);
  564. $this->last_request = compact('url', 'method', 'querydata', 'headers', 'options', 'opts');
  565. // call custom req log callback
  566. if (!empty($this->callbacks['onRequestLog'])) {
  567. $this->callbacks['onRequestLog']($this->last_request);
  568. }
  569. $resp_data = $this->makeStreamRequest($url, $opts);
  570. $resp['meta'] = $resp_data['meta'];
  571. $resp['body'] = $resp_data['body'];
  572. $resp['error'] = $resp_data['error'];
  573. $resp['error_msg'] = $resp_data['error_msg'];
  574. $resp['status'] = $this->getStatusCode($resp['meta']);
  575. $resp['headers'] = $this->metaToHeaders($resp['meta']);
  576. $this->log($resp);
  577. $this->log("Processing response body…");
  578. $resp = $this->processResponseBody($resp);
  579. $this->log($resp['body']);
  580. $this->last_response = $resp;
  581. // call custom resp log callback
  582. if (!empty($this->callbacks['onResponseLog'])) {
  583. $this->callbacks['onResponseLog']($this->last_response);
  584. }
  585. return $resp;
  586. }
  587. /**
  588. * opens an http stream, sends the request, and returns result
  589. * @param [type] $url [description]
  590. * @param [type] $opts [description]
  591. * @return [type] [description]
  592. */
  593. protected function makeStreamRequest($url, $opts) {
  594. $resp_data = array(
  595. 'meta' => null,
  596. 'body' => null,
  597. 'error' => true,
  598. 'error_msg' => null,
  599. );
  600. $context = stream_context_create($opts);
  601. $this->log("Sending…");
  602. $start_time = microtime(true);
  603. $this->log("Opening stream…");
  604. if ($this->silence_fopen_warning) {
  605. $stream = @fopen($url, 'r', false, $context);
  606. } else {
  607. $stream = fopen($url, 'r', false, $context);
  608. }
  609. if (!$stream) {
  610. $req_time = static::calc_time_passed($start_time);
  611. $opts_json = !empty($opts) ? json_encode($opts) : 'null';
  612. $msg = "Stream open failed for '{$url}'; req_time: {$req_time}; opts: {$opts_json}";
  613. $this->log($msg);
  614. if ($this->raise_fopen_exception) {
  615. throw new Exception($msg);
  616. } else {
  617. $resp_data['error'] = true;
  618. $resp_data['error_msg'] = $msg;
  619. }
  620. } else {
  621. $this->log("Getting metadata…");
  622. $resp_data['meta'] = stream_get_meta_data($stream);
  623. $this->log("Getting response…");
  624. $resp_data['body'] = stream_get_contents($stream);
  625. $this->log("Closing stream…");
  626. fclose($stream);
  627. }
  628. if ($this->debug) {
  629. $req_time = static::calc_time_passed($start_time);
  630. $this->log(sprintf("Request time for \"%s %s\": %f", $opts['http']['method'], $url, $req_time));
  631. }
  632. return $resp_data;
  633. }
  634. /**
  635. * If we get back something that claims to be XML or JSON, parse it as such and assign to $resp['body']
  636. *
  637. * @param string $resp
  638. * @return string|object
  639. * @see Resty::$JSON_TYPES
  640. * @see Resty::$XML_TYPES
  641. */
  642. protected function processResponseBody($resp) {
  643. if ($this->parse_body === true) {
  644. $header_content_type = isset($resp['headers']['Content-Type']) ? $resp['headers']['Content-Type'] : null;
  645. $content_type = preg_split('/[;\s]+/', $header_content_type);
  646. $content_type = $content_type[0];
  647. if (in_array($content_type, static::$JSON_TYPES)) {
  648. $this->log("Response body is JSON");
  649. $resp['body_raw'] = $resp['body'];
  650. $resp['body'] = json_decode($resp['body']);
  651. return $resp;
  652. } elseif (in_array($content_type, static::$XML_TYPES)) {
  653. $this->log("Response body is XML");
  654. $resp['body_raw'] = $resp['body'];
  655. $resp['body'] = new \SimpleXMLElement($resp['body']);
  656. return $resp;
  657. }
  658. }
  659. $this->log("Response body not parsed");
  660. return $resp;
  661. }
  662. /**
  663. * calculate time passed in microtime
  664. * @param float $start_time should be result of microtime(true)
  665. * @return float the diff between passed microtime and current microtime
  666. */
  667. protected static function calc_time_passed($start_time) {
  668. $stop_time = microtime(true);
  669. $req_time = $stop_time - $start_time;
  670. return $req_time;
  671. }
  672. protected function log($msg) {
  673. if (!$this->debug) { return; }
  674. if (is_callable($this->logger)) {
  675. $logger = $this->logger;
  676. return $logger($msg);
  677. }
  678. return $this->default_logger($msg);
  679. }
  680. /**
  681. * logging helper
  682. *
  683. * @param mixed $msg
  684. */
  685. protected function default_logger($msg) {
  686. $line = date(\DateTime::RFC822) . " :: ";
  687. if (is_string($msg)) {
  688. $line .= "{$msg}\n";
  689. } else {
  690. ob_start();
  691. var_dump($msg);
  692. $line = ob_get_clean();
  693. $line .= "\n";
  694. }
  695. if (PHP_SAPI !== 'cli') {
  696. $line = "<pre>$line</pre>\n";
  697. }
  698. return error_log($line);
  699. }
  700. }