PageRenderTime 97ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/arc/ARC2_Reader.php

https://github.com/damz/foafssl-drupal
PHP | 354 lines | 287 code | 32 blank | 35 comment | 65 complexity | 1f76d3c03723da4b6f4e3c3ecf777e26 MD5 | raw file
  1. <?php
  2. /*
  3. homepage: http://arc.semsol.org/
  4. license: http://arc.semsol.org/license
  5. class: ARC2 Web Reader
  6. author: Benjamin Nowack
  7. version: 2009-08-17
  8. */
  9. ARC2::inc('Class');
  10. class ARC2_Reader extends ARC2_Class {
  11. function __construct($a = '', &$caller) {
  12. parent::__construct($a, $caller);
  13. }
  14. function ARC2_Reader($a = '', &$caller) {
  15. $this->__construct($a, $caller);
  16. }
  17. function __init() {/* inc_path, proxy_host, proxy_port, proxy_skip, http_accept_header, http_user_agent_header, max_redirects */
  18. parent::__init();
  19. $this->http_method = $this->v('http_method', 'GET', $this->a);
  20. $this->message_body = $this->v('message_body', '', $this->a);;
  21. $this->http_accept_header = $this->v('http_accept_header', 'Accept: application/rdf+xml; q=0.9, */*; q=0.1', $this->a);
  22. $this->http_user_agent_header = $this->v('http_user_agent_header', 'User-Agent: ARC Reader (http://arc.semsol.org/)', $this->a);
  23. $this->http_custom_headers = $this->v('http_custom_headers', '', $this->a);
  24. $this->max_redirects = $this->v('max_redirects', 3, $this->a);
  25. $this->format = $this->v('format', false, $this->a);
  26. $this->redirects = array();
  27. $this->stream_id = '';
  28. $this->timeout = $this->v('reader_timeout', 30, $this->a);
  29. $this->response_headers = array();
  30. $this->digest_auth = 0;
  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. $this->base = $this->calcBase($path);
  58. $this->uri = $this->calcURI($path, $this->base);
  59. $this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base, $ping_only);
  60. if ($this->stream && !$this->ping_only) {
  61. $this->getFormat();
  62. }
  63. }
  64. }
  65. function setCredentials($url) {
  66. if (!$creds = $this->v('arc_reader_credentials', array(), $this->a)) return 0;
  67. foreach ($creds as $pattern => $cred) {
  68. $regex = '/' . preg_replace('/([\:\/\.\?])/', '\\\\\1', $pattern) . '/';
  69. if (!preg_match($regex, $url)) continue;
  70. $parts = parse_url($url);
  71. $path = $this->v1('path', '/', $parts);
  72. /* Basic auth */
  73. $auth = 'Basic ' . base64_encode($cred);
  74. /* Digest auth */
  75. if (preg_match('/(.*)\:\:(.*)/', $cred, $m)) {
  76. $username = $m[1];
  77. $pwd = $m[2];
  78. $auth = '';
  79. $h = $this->v('www-authenticate', '', $this->getResponseHeaders());
  80. /* 401 received */
  81. if ($h && preg_match('/Digest/i', $h)) {
  82. $auth = 'Digest ';
  83. /* Digest realm="$realm", nonce="$nonce", qop="auth", opaque="$opaque" */
  84. $ks = array('realm', 'nonce', 'opaque');/* skipping qop, assuming "auth" */
  85. $qop = 'auth';
  86. foreach ($ks as $i => $k) {
  87. $$k = preg_match('/' . $k . '=\"?([^\"]+)\"?/i', $h, $m) ? $m[1] : '';
  88. $auth .= ($i ? ', ' : '') . $k . '="' . $$k . '"';
  89. }
  90. $ha1 = md5($username . ':' . $realm . ':' . $pwd);
  91. $ha2 = md5($this->http_method . ':' . $path);
  92. $nc = '0001'; /* @@todo proper request counting */
  93. $cnonce = '0123'; /* @@todo proper request counting */
  94. $resp = md5($ha1 . ':' . $nonce . ':' . $nc . ':' . $cnonce . ':' . $qop . ':' . $ha2);
  95. $auth .= ', username="' . $username . '"' .
  96. ', uri="' . $path . '"' .
  97. ', qop=' . $qop . '' .
  98. ', nc=' . $nc .
  99. ', cnonce="' . $cnonce . '"' . /* @@todo proper request counting */
  100. ', uri="' . $path . '"' .
  101. ', response="' . $resp . '"' .
  102. '';
  103. }
  104. }
  105. /* add header */
  106. if ($auth) {
  107. $this->setCustomHeaders('Authorization: ' . $auth);
  108. break;
  109. }
  110. }
  111. }
  112. /* */
  113. function useProxy($url) {
  114. if (!$this->v1('proxy_host', 0, $this->a)) {
  115. return false;
  116. }
  117. $skips = $this->v1('proxy_skip', array(), $this->a);
  118. foreach ($skips as $skip) {
  119. if (strpos($url, $skip) !== false) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. }
  125. /* */
  126. function createStream($path, $data = '') {
  127. $this->base = $this->calcBase($path);
  128. $this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base);
  129. }
  130. function getDataStream($data) {
  131. return array('type' => 'data', 'pos' => 0, 'headers' => array(), 'size' => strlen($data), 'data' => $data, 'buffer' => '');
  132. }
  133. function getSocketStream($url) {
  134. if ($url == 'file://') {
  135. return $this->addError('Error: file does not exists or is not accessible');
  136. }
  137. $parts = parse_url($url);
  138. $mappings = array('file' => 'File', 'http' => 'HTTP', 'https' => 'HTTP');
  139. if ($scheme = $this->v(strtolower($parts['scheme']), '', $mappings)) {
  140. return $this->m('get' . $scheme . 'Socket', $url, $this->getDataStream(''));
  141. }
  142. }
  143. function getFileSocket($url) {
  144. $parts = parse_url($url);
  145. $s = file_exists($parts['path']) ? @fopen($parts['path'], 'rb') : false;
  146. if (!$s) {
  147. return $this->addError('Socket error: Could not open "' . $parts['path'] . '"');
  148. }
  149. return array('type' => 'socket', 'socket' =>& $s, 'headers' => array(), 'pos' => 0, 'size' => filesize($parts['path']), 'buffer' => '');
  150. }
  151. function getHTTPSocket($url, $redirs = 0) {
  152. $parts = parse_url($url);
  153. if (!isset($parts['scheme'])) {
  154. return $this->addError('Socket error: No supported URI scheme detected.');
  155. }
  156. $parts['port'] = ($parts['scheme'] == 'https') ? $this->v1('port', 443, $parts) : $this->v1('port', 80, $parts);
  157. $nl = "\r\n";
  158. $http_mthd = strtoupper($this->http_method);
  159. if ($this->v1('user', 0, $parts) || $this->useProxy($url)) {
  160. $h_code = $http_mthd . ' ' . $url;
  161. }
  162. else {
  163. $h_code = $http_mthd . ' ' . $this->v1('path', '/', $parts) . (($v = $this->v1('query', 0, $parts)) ? '?' . $v : '') . (($v = $this->v1('fragment', 0, $parts)) ? '#' . $v : '');
  164. }
  165. $h_code .= ' HTTP/1.0' . $nl.
  166. 'Host: ' . $parts['host'] . ':' . $parts['port'] . $nl .
  167. (($v = $this->http_accept_header) ? $v . $nl : '') .
  168. (($v = $this->http_user_agent_header) && !preg_match('/User\-Agent\:/', $this->http_custom_headers) ? $v . $nl : '') .
  169. (($http_mthd == 'POST') ? 'Content-Length: ' . strlen($this->message_body) . $nl : '') .
  170. ($this->http_custom_headers ? trim($this->http_custom_headers) . $nl : '') .
  171. $nl .
  172. '';
  173. /* post body */
  174. if ($http_mthd == 'POST') {
  175. $h_code .= $this->message_body . $nl;
  176. }
  177. /* connect */
  178. if ($this->useProxy($url)) {
  179. $s = @fsockopen($this->a['proxy_host'], $this->a['proxy_port'], $errno, $errstr, $this->timeout);
  180. }
  181. elseif ($parts['scheme'] == 'https') {
  182. $s = @fsockopen('ssl://' . $parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
  183. }
  184. elseif ($parts['scheme'] == 'http') {
  185. $s = fsockopen($parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
  186. }
  187. if (!$s) {
  188. return $this->addError('Socket error: Could not connect to "' . $url . '" (proxy: ' . ($this->useProxy($url) ? '1' : '0') . '): ' . $errstr);
  189. }
  190. /* request */
  191. fwrite($s, $h_code);
  192. /* timeout */
  193. if ($this->timeout) {
  194. //stream_set_blocking($s, false);
  195. stream_set_timeout($s, $this->timeout);
  196. }
  197. /* response headers */
  198. $h = array();
  199. $this->response_headers = $h;
  200. if (!$this->ping_only) {
  201. do {
  202. $line = trim(fgets($s, 256));
  203. $info = stream_get_meta_data($s);
  204. if (preg_match("/^HTTP[^\s]+\s+([0-9]{1})([0-9]{2})(.*)$/i", $line, $m)) {/* response code */
  205. $error = in_array($m[1], array('4', '5')) ? $m[1] . $m[2] . ' ' . $m[3] : '';
  206. $error = ($m[1].$m[2] == '304') ? '304 '.$m[3] : $error;
  207. $h['response-code'] = $m[1] . $m[2];
  208. $h['error'] = $error;
  209. $h['redirect'] = ($m[1] == '3') ? true : false;
  210. }
  211. elseif (preg_match('/^([^\:]+)\:\s*(.*)$/', $line, $m)) {/* header */
  212. $h[strtolower($m[1])] = trim($m[2]);
  213. }
  214. } while(!$info['timed_out'] && !feof($s) && $line);
  215. $h['format'] = strtolower(preg_replace('/^([^\s]+).*$/', '\\1', $this->v('content-type', '', $h)));
  216. $h['encoding'] = preg_match('/(utf\-8|iso\-8859\-1|us\-ascii)/', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : '';
  217. $h['encoding'] = preg_match('/charset=\s*([^\s]+)/si', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : $h['encoding'];
  218. $this->response_headers = $h;
  219. /* result */
  220. if ($info['timed_out']) {
  221. return $this->addError('Connection timed out after ' . $this->timeout . ' seconds');
  222. }
  223. /* error */
  224. if ($v = $this->v('error', 0, $h)) {
  225. /* digest auth */
  226. /* 401 received */
  227. if (preg_match('/Digest/i', $this->v('www-authenticate', '', $h)) && !$this->digest_auth) {
  228. $this->setCredentials($url);
  229. $this->digest_auth = 1;
  230. return $this->getHTTPSocket($url);
  231. }
  232. return $this->addError($error . ' "' . (!feof($s) ? trim(strip_tags(fread($s, 64))) . '..."' : ''));
  233. }
  234. /* redirect */
  235. if ($this->v('redirect', 0, $h) && ($new_url = $this->v1('location', 0, $h))) {
  236. fclose($s);
  237. $this->redirects[$url] = $new_url;
  238. $this->base = $new_url;
  239. if ($redirs > $this->max_redirects) {
  240. return $this->addError('Max numbers of redirects exceeded.');
  241. }
  242. return $this->getHTTPSocket($new_url, $redirs+1);
  243. }
  244. }
  245. if ($this->timeout) {
  246. stream_set_blocking($s, true);
  247. }
  248. return array('type' => 'socket', 'url' => $url, 'socket' =>& $s, 'headers' => $h, 'pos' => 0, 'size' => $this->v('content-length', 0, $h), 'buffer' => '');
  249. }
  250. function readStream($buffer_xml = true, $d_size = 1024) {
  251. //if (!$s = $this->v('stream')) return '';
  252. if (!$s = $this->v('stream')) return $this->addError('missing stream in "readStream" ' . $this->uri);
  253. $s_type = $this->v('type', '', $s);
  254. $r = $s['buffer'];
  255. $s['buffer'] = '';
  256. if ($s['size']) $d_size = min($d_size, $s['size'] - $s['pos']);
  257. /* data */
  258. if ($s_type == 'data') {
  259. $d = ($d_size > 0) ? substr($s['data'], $s['pos'], $d_size) : '';
  260. }
  261. /* socket */
  262. elseif ($s_type == 'socket') {
  263. $d = ($d_size > 0) && !feof($s['socket']) ? fread($s['socket'], $d_size) : '';
  264. }
  265. $eof = $d ? false : true;
  266. /* chunked despite HTTP 1.0 request */
  267. if (isset($s['headers']) && isset($s['headers']['transfer-encoding']) && ($s['headers']['transfer-encoding'] == 'chunked')) {
  268. $d = preg_replace('/(^|[\r\n]+)[0-9a-f]{1,4}[\r\n]+/', '', $d);
  269. }
  270. $s['pos'] += strlen($d);
  271. if ($buffer_xml) {/* stop after last closing xml tag (if available) */
  272. if (preg_match('/^(.*\>)([^\>]*)$/s', $d, $m)) {
  273. $d = $m[1];
  274. $s['buffer'] = $m[2];
  275. }
  276. elseif (!$eof) {
  277. $s['buffer'] = $r . $d;
  278. $this->stream = $s;
  279. return $this->readStream(true, $d_size);
  280. }
  281. }
  282. $this->stream = $s;
  283. return $r . $d;
  284. }
  285. function closeStream() {
  286. if (isset($this->stream)) {
  287. if ($this->v('type', 0, $this->stream) == 'socket') {
  288. @fclose($this->stream['socket']);
  289. }
  290. unset($this->stream);
  291. }
  292. }
  293. /* */
  294. function getFormat() {
  295. if (!$this->format) {
  296. if (!$this->v('stream')) {
  297. return $this->addError('missing stream in "getFormat"');
  298. }
  299. $v = $this->readStream(false);
  300. $mtype = $this->v('format', '', $this->stream['headers']);
  301. $this->stream['buffer'] = $v . $this->stream['buffer'];
  302. $ext = preg_match('/\.([^\.]+)$/', $this->uri, $m) ? $m[1] : '';
  303. $this->format = ARC2::getFormat($v, $mtype, $ext);
  304. }
  305. return $this->format;
  306. }
  307. /* */
  308. function getResponseHeaders() {
  309. if (isset($this->stream) && isset($this->stream['headers'])) {
  310. return $this->stream['headers'];
  311. }
  312. return $this->response_headers;
  313. }
  314. function getEncoding($default = 'UTF-8') {
  315. return $this->v1('encoding', $default, $this->stream['headers']);
  316. }
  317. function getRedirects() {
  318. return $this->redirects;
  319. }
  320. /* */
  321. }