PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/common/arc2/ARC2_Reader.php

https://github.com/tematres/TemaTres-Vocabulary-Server
PHP | 421 lines | 333 code | 35 blank | 53 comment | 87 complexity | ea47496de4ee73684803de85ff8ececd MD5 | raw file
Possible License(s): LGPL-2.1, MIT, CC-BY-3.0
  1. <?php
  2. /**
  3. * ARC2 Web Client
  4. *
  5. * @author Benjamin Nowack
  6. * @license <http://arc.semsol.org/license>
  7. * @homepage <http://arc.semsol.org/>
  8. * @package ARC2
  9. * @version 2010-11-16
  10. */
  11. ARC2::inc('Class');
  12. class ARC2_Reader extends ARC2_Class {
  13. function __construct($a, &$caller) {
  14. parent::__construct($a, $caller);
  15. }
  16. function __init() {/* inc_path, proxy_host, proxy_port, proxy_skip, http_accept_header, http_user_agent_header, max_redirects */
  17. parent::__init();
  18. $this->http_method = $this->v('http_method', 'GET', $this->a);
  19. $this->message_body = $this->v('message_body', '', $this->a);;
  20. $this->http_accept_header = $this->v('http_accept_header', 'Accept: application/rdf+xml; q=0.9, text/turtle; q=0.8, */*; q=0.1', $this->a);
  21. $this->http_user_agent_header = $this->v('http_user_agent_header', 'User-Agent: ARC Reader (http://arc.semsol.org/)', $this->a);
  22. $this->http_custom_headers = $this->v('http_custom_headers', '', $this->a);
  23. $this->max_redirects = $this->v('max_redirects', 3, $this->a);
  24. $this->format = $this->v('format', false, $this->a);
  25. $this->redirects = array();
  26. $this->stream_id = '';
  27. $this->timeout = $this->v('reader_timeout', 30, $this->a);
  28. $this->response_headers = array();
  29. $this->digest_auth = 0;
  30. $this->auth_infos = $this->v('reader_auth_infos', array(), $this->a);
  31. }
  32. /* */
  33. function setHTTPMethod($v) {
  34. $this->http_method = $v;
  35. }
  36. function setMessageBody($v) {
  37. $this->message_body = $v;
  38. }
  39. function setAcceptHeader($v) {
  40. $this->http_accept_header = $v;
  41. }
  42. function setCustomHeaders($v) {
  43. $this->http_custom_headers = $v;
  44. }
  45. function addCustomHeaders($v) {
  46. if ($this->http_custom_headers) $this->http_custom_headers .= "\r\n";
  47. $this->http_custom_headers .= $v;
  48. }
  49. /* */
  50. function activate($path, $data = '', $ping_only = 0, $timeout = 0) {
  51. $this->setCredentials($path);
  52. $this->ping_only = $ping_only;
  53. if ($timeout) $this->timeout = $timeout;
  54. $id = md5($path . ' ' . $data);
  55. if ($this->stream_id != $id) {
  56. $this->stream_id = $id;
  57. /* data uri? */
  58. if (!$data && preg_match('/^data\:([^\,]+)\,(.*)$/', $path, $m)) {
  59. $path = '';
  60. $data = preg_match('/base64/', $m[1]) ? base64_decode($m[2]) : rawurldecode($m[2]);
  61. }
  62. $this->base = $this->calcBase($path);
  63. $this->uri = $this->calcURI($path, $this->base);
  64. $this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base, $ping_only);
  65. if ($this->stream && !$this->ping_only) {
  66. $this->getFormat();
  67. }
  68. }
  69. }
  70. /*
  71. * HTTP Basic/Digest + Proxy authorization can be defined in the
  72. * arc_reader_credentials config setting:
  73. 'arc_reader_credentials' => array(
  74. 'http://basic.example.com/' => 'user:pass', // shortcut for type=basic
  75. 'http://digest.example.com/' => 'user::pass', // shortcut for type=digest
  76. 'http://proxy.example.com/' => array('type' => 'basic', 'proxy', 'user' => 'user', 'pass' => 'pass'),
  77. ),
  78. */
  79. function setCredentials($url) {
  80. if (!$creds = $this->v('arc_reader_credentials', array(), $this->a)) return 0;
  81. foreach ($creds as $pattern => $creds) {
  82. /* digest shortcut (user::pass) */
  83. if (!is_array($creds) && preg_match('/^(.+)\:\:(.+)$/', $creds, $m)) {
  84. $creds = array('type' => 'digest', 'user' => $m[1], 'pass' => $m[2]);
  85. }
  86. /* basic shortcut (user:pass) */
  87. if (!is_array($creds) && preg_match('/^(.+)\:(.+)$/', $creds, $m)) {
  88. $creds = array('type' => 'basic', 'user' => $m[1], 'pass' => $m[2]);
  89. }
  90. if (!is_array($creds)) return 0;
  91. $regex = '/' . preg_replace('/([\:\/\.\?])/', '\\\\\1', $pattern) . '/';
  92. if (!preg_match($regex, $url)) continue;
  93. $mthd = 'set' . $this->camelCase($creds['type']) . 'AuthCredentials';
  94. if (method_exists($this, $mthd)) $this->$mthd($creds, $url);
  95. }
  96. }
  97. function setBasicAuthCredentials($creds) {
  98. $auth = 'Basic ' . base64_encode($creds['user'] . ':' . $creds['pass']);
  99. $h = in_array('proxy', $creds) ? 'Proxy-Authorization' : 'Authorization';
  100. $this->addCustomHeaders($h . ': ' . $auth);
  101. //echo $h . ': ' . $auth . print_r($creds, 1);
  102. }
  103. function setDigestAuthCredentials($creds, $url) {
  104. $path = $this->v1('path', '/', parse_url($url));
  105. $auth = '';
  106. $hs = $this->getResponseHeaders();
  107. /* initial 401 */
  108. $h = $this->v('www-authenticate', '', $hs);
  109. if ($h && preg_match('/Digest/i', $h)) {
  110. $auth = 'Digest ';
  111. /* Digest realm="$realm", nonce="$nonce", qop="auth", opaque="$opaque" */
  112. $ks = array('realm', 'nonce', 'opaque');/* skipping qop, assuming "auth" */
  113. foreach ($ks as $i => $k) {
  114. $$k = preg_match('/' . $k . '=\"?([^\"]+)\"?/i', $h, $m) ? $m[1] : '';
  115. $auth .= ($i ? ', ' : '') . $k . '="' . $$k . '"';
  116. $this->auth_infos[$k] = $$k;
  117. }
  118. $this->auth_infos['auth'] = $auth;
  119. $this->auth_infos['request_count'] = 1;
  120. }
  121. /* initial 401 or repeated request */
  122. if ($this->v('auth', 0, $this->auth_infos)) {
  123. $qop = 'auth';
  124. $auth = $this->auth_infos['auth'];
  125. $rc = $this->auth_infos['request_count'];
  126. $realm = $this->auth_infos['realm'];
  127. $nonce = $this->auth_infos['nonce'];
  128. $ha1 = md5($creds['user'] . ':' . $realm . ':' . $creds['pass']);
  129. $ha2 = md5($this->http_method . ':' . $path);
  130. $nc = dechex($rc);
  131. $cnonce = dechex($rc * 2);
  132. $resp = md5($ha1 . ':' . $nonce . ':' . $nc . ':' . $cnonce . ':' . $qop . ':' . $ha2);
  133. $auth .= ', username="' . $creds['user'] . '"' .
  134. ', uri="' . $path . '"' .
  135. ', qop=' . $qop . '' .
  136. ', nc=' . $nc .
  137. ', cnonce="' . $cnonce . '"' .
  138. ', uri="' . $path . '"' .
  139. ', response="' . $resp . '"' .
  140. '';
  141. $this->auth_infos['request_count'] = $rc + 1;
  142. }
  143. if (!$auth) return 0;
  144. $h = in_array('proxy', $creds) ? 'Proxy-Authorization' : 'Authorization';
  145. $this->addCustomHeaders($h . ': ' . $auth);
  146. }
  147. /* */
  148. function useProxy($url) {
  149. if (!$this->v1('proxy_host', 0, $this->a)) {
  150. return false;
  151. }
  152. $skips = $this->v1('proxy_skip', array(), $this->a);
  153. foreach ($skips as $skip) {
  154. if (strpos($url, $skip) !== false) {
  155. return false;
  156. }
  157. }
  158. return true;
  159. }
  160. /* */
  161. function createStream($path, $data = '') {
  162. $this->base = $this->calcBase($path);
  163. $this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base);
  164. }
  165. function getDataStream($data) {
  166. return array('type' => 'data', 'pos' => 0, 'headers' => array(), 'size' => strlen($data), 'data' => $data, 'buffer' => '');
  167. }
  168. function getSocketStream($url) {
  169. if ($url == 'file://') {
  170. return $this->addError('Error: file does not exists or is not accessible');
  171. }
  172. $parts = parse_url($url);
  173. $mappings = array('file' => 'File', 'http' => 'HTTP', 'https' => 'HTTP');
  174. if ($scheme = $this->v(strtolower($parts['scheme']), '', $mappings)) {
  175. return $this->m('get' . $scheme . 'Socket', $url, $this->getDataStream(''));
  176. }
  177. }
  178. function getFileSocket($url) {
  179. $parts = parse_url($url);
  180. $s = file_exists($parts['path']) ? @fopen($parts['path'], 'rb') : false;
  181. if (!$s) {
  182. return $this->addError('Socket error: Could not open "' . $parts['path'] . '"');
  183. }
  184. return array('type' => 'socket', 'socket' =>& $s, 'headers' => array(), 'pos' => 0, 'size' => filesize($parts['path']), 'buffer' => '');
  185. }
  186. function getHTTPSocket($url, $redirs = 0, $prev_parts = '') {
  187. $parts = parse_url($url);
  188. /* relative redirect */
  189. if (!isset($parts['scheme']) && $prev_parts) $parts['scheme'] = $prev_parts['scheme'];
  190. if (!isset($parts['host']) && $prev_parts) $parts['host'] = $prev_parts['host'];
  191. if (!isset($parts['port']) && $prev_parts) $parts['port'] = $prev_parts['port'];
  192. /* no scheme */
  193. if (!$this->v('scheme', '', $parts)) return $this->addError('Socket error: Missing URI scheme.');
  194. /* port tweaks */
  195. $parts['port'] = ($parts['scheme'] == 'https') ? $this->v1('port', 443, $parts) : $this->v1('port', 80, $parts);
  196. $nl = "\r\n";
  197. $http_mthd = strtoupper($this->http_method);
  198. if ($this->v1('user', 0, $parts) || $this->useProxy($url)) {
  199. $h_code = $http_mthd . ' ' . $url;
  200. }
  201. else {
  202. $h_code = $http_mthd . ' ' . $this->v1('path', '/', $parts) . (($v = $this->v1('query', 0, $parts)) ? '?' . $v : '') . (($v = $this->v1('fragment', 0, $parts)) ? '#' . $v : '');
  203. }
  204. $scheme_default_port = ($parts['scheme'] == 'https') ? 443 : 80;
  205. $port_code = ($parts['port'] != $scheme_default_port) ? ':' . $parts['port'] : '';
  206. $h_code .= ' HTTP/1.0' . $nl.
  207. 'Host: ' . $parts['host'] . $port_code . $nl .
  208. (($v = $this->http_accept_header) ? $v . $nl : '') .
  209. (($v = $this->http_user_agent_header) && !preg_match('/User\-Agent\:/', $this->http_custom_headers) ? $v . $nl : '') .
  210. (($http_mthd == 'POST') ? 'Content-Length: ' . strlen($this->message_body) . $nl : '') .
  211. ($this->http_custom_headers ? trim($this->http_custom_headers) . $nl : '') .
  212. $nl .
  213. '';
  214. /* post body */
  215. if ($http_mthd == 'POST') {
  216. $h_code .= $this->message_body . $nl;
  217. }
  218. /* connect */
  219. if ($this->useProxy($url)) {
  220. $s = @fsockopen($this->a['proxy_host'], $this->a['proxy_port'], $errno, $errstr, $this->timeout);
  221. }
  222. elseif (($parts['scheme'] == 'https') && function_exists('stream_socket_client')) {
  223. // SSL options via config array, code by Hannes Muehleisen (muehleis@informatik.hu-berlin.de)
  224. $context = stream_context_create();
  225. foreach ($this->a as $k => $v) {
  226. if (preg_match('/^arc_reader_ssl_(.+)$/', $k, $m)) {
  227. stream_context_set_option($context, 'ssl', $m[1], $v);
  228. }
  229. }
  230. $s = stream_socket_client('ssl://' . $parts['host'] . ":" . $parts['port'], $errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $context);
  231. }
  232. elseif ($parts['scheme'] == 'https') {
  233. $s = @fsockopen('ssl://' . $parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
  234. }
  235. elseif ($parts['scheme'] == 'http') {
  236. $s = @fsockopen($parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
  237. }
  238. if (!$s) {
  239. return $this->addError('Socket error: Could not connect to "' . $url . '" (proxy: ' . ($this->useProxy($url) ? '1' : '0') . '): ' . $errstr);
  240. }
  241. /* request */
  242. fwrite($s, $h_code);
  243. /* timeout */
  244. if ($this->timeout) {
  245. //stream_set_blocking($s, false);
  246. stream_set_timeout($s, $this->timeout);
  247. }
  248. /* response headers */
  249. $h = array();
  250. $this->response_headers = $h;
  251. if (!$this->ping_only) {
  252. do {
  253. $line = trim(fgets($s, 4096));
  254. $info = stream_get_meta_data($s);
  255. if (preg_match("/^HTTP[^\s]+\s+([0-9]{1})([0-9]{2})(.*)$/i", $line, $m)) {/* response code */
  256. $error = in_array($m[1], array('4', '5')) ? $m[1] . $m[2] . ' ' . $m[3] : '';
  257. $error = ($m[1].$m[2] == '304') ? '304 '.$m[3] : $error;
  258. $h['response-code'] = $m[1] . $m[2];
  259. $h['error'] = $error;
  260. $h['redirect'] = ($m[1] == '3') ? true : false;
  261. }
  262. elseif (preg_match('/^([^\:]+)\:\s*(.*)$/', $line, $m)) {/* header */
  263. $h_name = strtolower($m[1]);
  264. if (!isset($h[$h_name])) {/* 1st value */
  265. $h[$h_name] = trim($m[2]);
  266. }
  267. elseif (!is_array($h[$h_name])) {/* 2nd value */
  268. $h[$h_name] = array($h[$h_name], trim($m[2]));
  269. }
  270. else {/* more values */
  271. $h[$h_name][] = trim($m[2]);
  272. }
  273. }
  274. } while(!$info['timed_out'] && !feof($s) && $line);
  275. $h['format'] = strtolower(preg_replace('/^([^\s]+).*$/', '\\1', $this->v('content-type', '', $h)));
  276. $h['encoding'] = preg_match('/(utf\-8|iso\-8859\-1|us\-ascii)/', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : '';
  277. $h['encoding'] = preg_match('/charset=\s*([^\s]+)/si', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : $h['encoding'];
  278. $this->response_headers = $h;
  279. /* result */
  280. if ($info['timed_out']) {
  281. return $this->addError('Connection timed out after ' . $this->timeout . ' seconds');
  282. }
  283. /* error */
  284. if ($v = $this->v('error', 0, $h)) {
  285. /* digest auth */
  286. /* 401 received */
  287. if (preg_match('/Digest/i', $this->v('www-authenticate', '', $h)) && !$this->digest_auth) {
  288. $this->setCredentials($url);
  289. $this->digest_auth = 1;
  290. return $this->getHTTPSocket($url);
  291. }
  292. return $this->addError($error . ' "' . (!feof($s) ? trim(strip_tags(fread($s, 128))) . '..."' : ''));
  293. }
  294. /* redirect */
  295. if ($this->v('redirect', 0, $h) && ($new_url = $this->v1('location', 0, $h))) {
  296. fclose($s);
  297. $this->redirects[$url] = $new_url;
  298. $this->base = $new_url;
  299. if ($redirs > $this->max_redirects) {
  300. return $this->addError('Max numbers of redirects exceeded.');
  301. }
  302. return $this->getHTTPSocket($new_url, $redirs+1, $parts);
  303. }
  304. }
  305. if ($this->timeout) {
  306. stream_set_blocking($s, true);
  307. }
  308. return array('type' => 'socket', 'url' => $url, 'socket' =>& $s, 'headers' => $h, 'pos' => 0, 'size' => $this->v('content-length', 0, $h), 'buffer' => '');
  309. }
  310. function readStream($buffer_xml = true, $d_size = 1024) {
  311. //if (!$s = $this->v('stream')) return '';
  312. if (!$s = $this->v('stream')) return $this->addError('missing stream in "readStream" ' . $this->uri);
  313. $s_type = $this->v('type', '', $s);
  314. $r = $s['buffer'];
  315. $s['buffer'] = '';
  316. if ($s['size']) $d_size = min($d_size, $s['size'] - $s['pos']);
  317. /* data */
  318. if ($s_type == 'data') {
  319. $d = ($d_size > 0) ? substr($s['data'], $s['pos'], $d_size) : '';
  320. }
  321. /* socket */
  322. elseif ($s_type == 'socket') {
  323. $d = ($d_size > 0) && !feof($s['socket']) ? fread($s['socket'], $d_size) : '';
  324. }
  325. $eof = $d ? false : true;
  326. /* chunked despite HTTP 1.0 request */
  327. if (isset($s['headers']) && isset($s['headers']['transfer-encoding']) && ($s['headers']['transfer-encoding'] == 'chunked')) {
  328. $d = preg_replace('/(^|[\r\n]+)[0-9a-f]{1,4}[\r\n]+/', '', $d);
  329. }
  330. $s['pos'] += strlen($d);
  331. if ($buffer_xml) {/* stop after last closing xml tag (if available) */
  332. if (preg_match('/^(.*\>)([^\>]*)$/s', $d, $m)) {
  333. $d = $m[1];
  334. $s['buffer'] = $m[2];
  335. }
  336. elseif (!$eof) {
  337. $s['buffer'] = $r . $d;
  338. $this->stream = $s;
  339. return $this->readStream(true, $d_size);
  340. }
  341. }
  342. $this->stream = $s;
  343. return $r . $d;
  344. }
  345. function closeStream() {
  346. if (isset($this->stream)) {
  347. if ($this->v('type', 0, $this->stream) == 'socket' && !empty($this->stream['socket'])) {
  348. @fclose($this->stream['socket']);
  349. }
  350. unset($this->stream);
  351. }
  352. }
  353. /* */
  354. function getFormat() {
  355. if (!$this->format) {
  356. if (!$this->v('stream')) {
  357. return $this->addError('missing stream in "getFormat"');
  358. }
  359. $v = $this->readStream(false);
  360. $mtype = $this->v('format', '', $this->stream['headers']);
  361. $this->stream['buffer'] = $v . $this->stream['buffer'];
  362. $ext = preg_match('/\.([^\.]+)$/', $this->uri, $m) ? $m[1] : '';
  363. $this->format = ARC2::getFormat($v, $mtype, $ext);
  364. }
  365. return $this->format;
  366. }
  367. /* */
  368. function getResponseHeaders() {
  369. if (isset($this->stream) && isset($this->stream['headers'])) {
  370. return $this->stream['headers'];
  371. }
  372. return $this->response_headers;
  373. }
  374. function getEncoding($default = 'UTF-8') {
  375. return $this->v1('encoding', $default, $this->stream['headers']);
  376. }
  377. function getRedirects() {
  378. return $this->redirects;
  379. }
  380. function getAuthInfos() {
  381. return $this->auth_infos;
  382. }
  383. /* */
  384. }