You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

470 lines
14 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. <?php
  2. namespace XRay\Formats;
  3. use HTMLPurifier, HTMLPurifier_Config;
  4. class Mf2 {
  5. private static function _debug($msg) {
  6. syslog(LOG_INFO, $msg);
  7. if(array_key_exists('REMOTE_ADDR', $_SERVER))
  8. header("X-Parse-Debug: " . $msg);
  9. }
  10. public static function parse($mf2, $url, $http) {
  11. if(count($mf2['items']) == 0)
  12. return false;
  13. // Check if the list of items is a bunch of h-entrys and return as a feed
  14. // Unless this page's URL matches one of the entries, then treat it as a permalink
  15. $hentrys = 0;
  16. $lastSeenEntry = false;
  17. foreach($mf2['items'] as $item) {
  18. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  19. if(array_key_exists('url', $item['properties'])) {
  20. $urls = $item['properties']['url'];
  21. $urls = array_map('\normalize_url', $urls);
  22. if(in_array($url, $urls)) {
  23. self::_debug("1: Recognized $url as an h-entry because an h-entry on the page matched the URL of the request");
  24. return self::parseAsHEntry($mf2, $item, $http, $url);
  25. }
  26. $lastSeenEntry = $item;
  27. }
  28. $hentrys++;
  29. }
  30. }
  31. // If there was more than one h-entry on the page, treat the whole page as a feed
  32. if($hentrys > 1) {
  33. self::_debug("2: Recognized $url as an h-feed because there are more than one h-entry on the page");
  34. return self::parseAsHFeed($mf2, $http);
  35. }
  36. // If the first item is an h-feed, parse as a feed
  37. $first = $mf2['items'][0];
  38. if(in_array('h-feed', $first['type'])) {
  39. self::_debug("3: Recognized $url as an h-feed because the first item is an h-feed");
  40. return self::parseAsHFeed($mf2, $http);
  41. }
  42. // Check each top-level h-card, and if there is one that matches this URL, the page is an h-card
  43. foreach($mf2['items'] as $item) {
  44. if(in_array('h-card', $item['type'])
  45. and array_key_exists('url', $item['properties'])
  46. ) {
  47. $urls = $item['properties']['url'];
  48. $urls = array_map('\normalize_url', $urls);
  49. if(in_array($url, $urls)) {
  50. // TODO: check for children h-entrys (like tantek.com), or sibling h-entries (like aaronparecki.com)
  51. // and return the result as a feed instead
  52. self::_debug("4: Recognized $url as an h-card because an h-card on the page matched the URL of the request");
  53. return self::parseAsHCard($item, $http, $url);
  54. }
  55. }
  56. }
  57. // If there was only one h-entry, but the URL for it is not the same as this page, then treat as a feed
  58. if($hentrys == 1) {
  59. if($lastSeenEntry) {
  60. $urls = $lastSeenEntry['properties']['url'];
  61. $urls = array_map('\normalize_url', $urls);
  62. if(count($urls) && !in_array($url, $urls)) {
  63. self::_debug("5: Recognized $url as an h-feed no h-entrys on the page matched the URL of the request");
  64. return self::parseAsHFeed($mf2, $http);
  65. }
  66. }
  67. }
  68. // Fallback case, but hopefully we have found something before this point
  69. foreach($mf2['items'] as $item) {
  70. // Otherwise check for an h-entry
  71. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  72. self::_debug("6: $url is falling back to the first h-entry on the page");
  73. return self::parseAsHEntry($mf2, $item, $http);
  74. }
  75. }
  76. self::_debug("E: No object at $url was recognized");
  77. return false;
  78. }
  79. private static function parseAsHEntry($mf2, $item, $http) {
  80. $data = [
  81. 'type' => 'entry'
  82. ];
  83. $refs = [];
  84. // Single plaintext values
  85. $properties = ['url','published','summary','rsvp'];
  86. foreach($properties as $p) {
  87. if($v = self::getPlaintext($item, $p))
  88. $data[$p] = $v;
  89. }
  90. // Always arrays
  91. $properties = ['photo','video','syndication'];
  92. foreach($properties as $p) {
  93. if(array_key_exists($p, $item['properties'])) {
  94. $data[$p] = [];
  95. foreach($item['properties'][$p] as $v) {
  96. if(is_string($v))
  97. $data[$p][] = $v;
  98. elseif(is_array($v) and array_key_exists('value', $v))
  99. $data[$p][] = $v['value'];
  100. }
  101. }
  102. }
  103. // Always returned as arrays, and may also create external references
  104. $properties = ['in-reply-to','like-of','repost-of','bookmark-of','category','invitee'];
  105. foreach($properties as $p) {
  106. if(array_key_exists($p, $item['properties'])) {
  107. $data[$p] = [];
  108. foreach($item['properties'][$p] as $v) {
  109. if(is_string($v))
  110. $data[$p][] = $v;
  111. elseif(self::isMicroformat($v) && ($u=self::getPlaintext($v, 'url'))) {
  112. $data[$p][] = $u;
  113. // parse the object and put the result in the "refs" object
  114. $ref = self::parse(['items'=>[$v]], $u, $http);
  115. if($ref) {
  116. $refs[$u] = $ref['data'];
  117. }
  118. }
  119. }
  120. }
  121. }
  122. // Determine if the name is distinct from the content
  123. $name = self::getPlaintext($item, 'name');
  124. $content = null;
  125. $textContent = null;
  126. $htmlContent = null;
  127. if(array_key_exists('content', $item['properties'])) {
  128. $content = $item['properties']['content'][0];
  129. if(is_string($content)) {
  130. $textContent = $content;
  131. } elseif(!is_string($content) && is_array($content) && array_key_exists('value', $content)) {
  132. if(array_key_exists('html', $content)) {
  133. $htmlContent = trim(self::sanitizeHTML($content['html']));
  134. $textContent = trim(str_replace("&#xD;","\r",strip_tags($htmlContent)));
  135. $textContent = trim(str_replace("&#xD;","\r",$content['value']));
  136. } else {
  137. $textContent = trim($content['value']);
  138. }
  139. }
  140. // Trim ellipses from the name
  141. $name = preg_replace('/ ?(\.\.\.|…)$/', '', $name);
  142. // Remove all whitespace when checking equality
  143. $nameCompare = preg_replace('/\s/','',trim($name));
  144. $contentCompare = preg_replace('/\s/','',trim($textContent));
  145. // Check if the name is a prefix of the content
  146. if($contentCompare && $nameCompare && strpos($contentCompare, $nameCompare) === 0) {
  147. $name = null;
  148. }
  149. }
  150. if($name) {
  151. $data['name'] = $name;
  152. }
  153. // If there is content, always return the plaintext content, and return HTML content if it's different
  154. if($content) {
  155. $data['content'] = [
  156. 'text' => $textContent
  157. ];
  158. if($htmlContent && $textContent != $htmlContent) {
  159. $data['content']['html'] = $htmlContent;
  160. }
  161. }
  162. if($author = self::findAuthor($mf2, $item, $http))
  163. $data['author'] = $author;
  164. $response = [
  165. 'data' => $data
  166. ];
  167. if(count($refs)) {
  168. $response['refs'] = $refs;
  169. }
  170. return $response;
  171. }
  172. private static function parseAsHFeed($mf2, $http) {
  173. $data = [
  174. 'type' => 'feed',
  175. 'author' => [
  176. 'type' => 'card',
  177. 'name' => null,
  178. 'url' => null,
  179. 'photo' => null
  180. ],
  181. 'todo' => 'Not yet implemented. Please see https://github.com/aaronpk/XRay/issues/1'
  182. ];
  183. return [
  184. 'data' => $data,
  185. 'entries' => []
  186. ];
  187. }
  188. private static function parseAsHCard($item, $http, $authorURL=false) {
  189. $data = [
  190. 'type' => 'card',
  191. 'name' => null,
  192. 'url' => null,
  193. 'photo' => null
  194. ];
  195. $properties = ['url','name','photo'];
  196. foreach($properties as $p) {
  197. if($p == 'url' && $authorURL) {
  198. // If there is a matching author URL, use that one
  199. $found = false;
  200. foreach($item['properties']['url'] as $url) {
  201. $url = \normalize_url($url);
  202. if($url == $authorURL) {
  203. $data['url'] = $url;
  204. $found = true;
  205. }
  206. }
  207. if(!$found) $data['url'] = $item['properties']['url'][0];
  208. } else if($v = self::getPlaintext($item, $p)) {
  209. $data[$p] = $v;
  210. }
  211. }
  212. $response = [
  213. 'data' => $data
  214. ];
  215. return $response;
  216. }
  217. private static function findAuthor($mf2, $item, $http) {
  218. $author = [
  219. 'type' => 'card',
  220. 'name' => null,
  221. 'url' => null,
  222. 'photo' => null
  223. ];
  224. // Author Discovery
  225. // http://indiewebcamp.com/authorship
  226. $authorPage = false;
  227. if(array_key_exists('author', $item['properties'])) {
  228. // Check if any of the values of the author property are an h-card
  229. foreach($item['properties']['author'] as $a) {
  230. if(self::isHCard($a)) {
  231. // 5.1 "if it has an h-card, use it, exit."
  232. return self::parseAsHCard($a, $http)['data'];
  233. } elseif(is_string($a)) {
  234. if(self::isURL($a)) {
  235. // 5.2 "otherwise if author property is an http(s) URL, let the author-page have that URL"
  236. $authorPage = $a;
  237. } else {
  238. // 5.3 "otherwise use the author property as the author name, exit"
  239. // We can only set the name, no h-card or URL was found
  240. $author['name'] = self::getPlaintext($item, 'author');
  241. return $author;
  242. }
  243. } else {
  244. // This case is only hit when the author property is an mf2 object that is not an h-card
  245. $author['name'] = self::getPlaintext($item, 'author');
  246. return $author;
  247. }
  248. }
  249. }
  250. // 6. "if no author page was found" ... check for rel-author link
  251. if(!$authorPage) {
  252. if(isset($mf2['rels']) && isset($mf2['rels']['author']))
  253. $authorPage = $mf2['rels']['author'][0];
  254. }
  255. // 7. "if there is an author-page URL" ...
  256. if($authorPage) {
  257. // 7.1 "get the author-page from that URL and parse it for microformats2"
  258. $authorPageContents = self::getURL($authorPage, $http);
  259. if($authorPageContents) {
  260. foreach($authorPageContents['items'] as $i) {
  261. if(self::isHCard($i)) {
  262. // 7.2 "if author-page has 1+ h-card with url == uid == author-page's URL, then use first such h-card, exit."
  263. if(array_key_exists('url', $i['properties'])
  264. and in_array($authorPage, $i['properties']['url'])
  265. and array_key_exists('uid', $i['properties'])
  266. and in_array($authorPage, $i['properties']['uid'])
  267. ) {
  268. return self::parseAsHCard($i, $http, $authorPage)['data'];
  269. }
  270. // 7.3 "else if author-page has 1+ h-card with url property which matches the href of a rel-me link on the author-page"
  271. $relMeLinks = (isset($authorPageContents['rels']) && isset($authorPageContents['rels']['me'])) ? $authorPageContents['rels']['me'] : [];
  272. if(count($relMeLinks) > 0
  273. and array_key_exists('url', $i['properties'])
  274. and count(array_intersect($i['properties']['url'], $relMeLinks)) > 0
  275. ) {
  276. return self::parseAsHCard($i, $http, $authorPage)['data'];
  277. }
  278. }
  279. }
  280. }
  281. // 7.4 "if the h-entry's page has 1+ h-card with url == author-page URL, use first such h-card, exit."
  282. foreach($mf2['items'] as $i) {
  283. if(self::isHCard($i)) {
  284. if(array_key_exists('url', $i['properties'])
  285. and in_array($authorPage, $i['properties']['url'])
  286. ) {
  287. return self::parseAsHCard($i, $http)['data'];
  288. }
  289. }
  290. }
  291. }
  292. if(!$author['name'] && !$author['photo'] && !$author['url'])
  293. return null;
  294. return $author;
  295. }
  296. private static function sanitizeHTML($html) {
  297. $config = HTMLPurifier_Config::createDefault();
  298. $config->set('Cache.DefinitionImpl', null);
  299. $config->set('HTML.AllowedElements', [
  300. 'a',
  301. 'abbr',
  302. 'b',
  303. 'code',
  304. 'del',
  305. 'em',
  306. 'i',
  307. 'img',
  308. 'q',
  309. 'strike',
  310. 'strong',
  311. 'time',
  312. 'blockquote',
  313. 'pre',
  314. 'p',
  315. 'h1',
  316. 'h2',
  317. 'h3',
  318. 'h4',
  319. 'h5',
  320. 'h6',
  321. 'ul',
  322. 'li',
  323. 'ol'
  324. ]);
  325. $def = $config->getHTMLDefinition(true);
  326. $def->addElement(
  327. 'time',
  328. 'Inline',
  329. 'Inline',
  330. 'Common',
  331. [
  332. 'datetime' => 'Text'
  333. ]
  334. );
  335. // Override the allowed classes to only support Microformats2 classes
  336. $def->manager->attrTypes->set('Class', new \HTMLPurifier_AttrDef_HTML_Microformats2());
  337. $purifier = new HTMLPurifier($config);
  338. return $purifier->purify($html);
  339. }
  340. private static function responseDisplayText($name, $summary, $content) {
  341. // Build a fake h-entry to pass to the comments parser
  342. $input = [
  343. 'type' => ['h-entry'],
  344. 'properties' => [
  345. 'name' => [trim($name)],
  346. 'summary' => [trim($summary)],
  347. 'content' => [trim($content)]
  348. ]
  349. ];
  350. if(!trim($name))
  351. unset($input['properties']['name']);
  352. if(!trim($summary))
  353. unset($input['properties']['summary']);
  354. $result = \IndieWeb\comments\parse($input, false, 1024, 4);
  355. return [
  356. 'name' => trim($result['name']),
  357. 'content' => $result['text']
  358. ];
  359. }
  360. private static function hasNumericKeys(array $arr) {
  361. foreach($arr as $key=>$val)
  362. if (is_numeric($key))
  363. return true;
  364. return false;
  365. }
  366. private static function isMicroformat($mf) {
  367. return is_array($mf)
  368. and !self::hasNumericKeys($mf)
  369. and !empty($mf['type'])
  370. and isset($mf['properties']);
  371. }
  372. private static function isHCard($mf) {
  373. return is_array($mf)
  374. and !empty($mf['type'])
  375. and is_array($mf['type'])
  376. and in_array('h-card', $mf['type']);
  377. }
  378. private static function isURL($string) {
  379. return preg_match('/^https?:\/\/.+\..+$/', $string);
  380. }
  381. // Given an array of microformats properties and a key name, return the plaintext value
  382. // at that property
  383. // e.g.
  384. // {"properties":{"published":["foo"]}} results in "foo"
  385. private static function getPlaintext($mf2, $k, $fallback=null) {
  386. if(!empty($mf2['properties'][$k]) and is_array($mf2['properties'][$k])) {
  387. // $mf2['properties'][$v] will always be an array since the input was from the mf2 parser
  388. $value = $mf2['properties'][$k][0];
  389. if(is_string($value)) {
  390. return $value;
  391. } elseif(self::isMicroformat($value) && array_key_exists('value', $value)) {
  392. return $value['value'];
  393. }
  394. }
  395. return $fallback;
  396. }
  397. private static function getURL($url, $http) {
  398. if(!$url) return null;
  399. // TODO: consider adding caching here
  400. $result = $http->get($url);
  401. if($result['error'] || !$result['body']) {
  402. return null;
  403. }
  404. return \mf2\Parse($result['body'], $url);
  405. }
  406. }