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.

654 lines
22 KiB

8 years ago
8 years ago
8 years ago
  1. <?php
  2. namespace XRay\Formats;
  3. use HTMLPurifier, HTMLPurifier_Config;
  4. use Parse;
  5. class Mf2 {
  6. public static function parse($mf2, $url, $http) {
  7. if(count($mf2['items']) == 0)
  8. return false;
  9. // If there is only one item on the page, just use that
  10. if(count($mf2['items']) == 1) {
  11. $item = $mf2['items'][0];
  12. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  13. Parse::debug("mf2:0: Recognized $url as an h-entry it is the only item on the page");
  14. return self::parseAsHEntry($mf2, $item, $http);
  15. }
  16. if(in_array('h-event', $item['type'])) {
  17. Parse::debug("mf2:0: Recognized $url as an h-event it is the only item on the page");
  18. return self::parseAsHEvent($mf2, $item, $http);
  19. }
  20. if(in_array('h-review', $item['type'])) {
  21. Parse::debug("mf2:0: Recognized $url as an h-review it is the only item on the page");
  22. return self::parseAsHReview($mf2, $item, $http);
  23. }
  24. if(in_array('h-product', $item['type'])) {
  25. Parse::debug("mf2:0: Recognized $url as an h-product it is the only item on the page");
  26. return self::parseAsHProduct($mf2, $item, $http);
  27. }
  28. if(in_array('h-feed', $item['type'])) {
  29. Parse::debug("mf2:0: Recognized $url as an h-feed because it is the only item on the page");
  30. return self::parseAsHFeed($mf2, $http);
  31. }
  32. }
  33. // Check the list of items on the page to see if one matches the URL of the page,
  34. // and treat as a permalink for that object if so. Otherwise, parse as a feed.
  35. foreach($mf2['items'] as $item) {
  36. if(array_key_exists('url', $item['properties'])) {
  37. $urls = $item['properties']['url'];
  38. $urls = array_map('self::normalize_url', $urls);
  39. if(in_array($url, $urls)) {
  40. Parse::debug("mf2:1: Recognized $url as a permalink because an object on the page matched the URL of the request");
  41. if(in_array('h-card', $item['type'])) {
  42. return self::parseAsHCard($item, $http, $url);
  43. } elseif(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  44. return self::parseAsHEntry($mf2, $item, $http);
  45. } elseif(in_array('h-event', $item['type'])) {
  46. return self::parseAsHEvent($mf2, $item, $http);
  47. } elseif(in_array('h-review', $item['type'])) {
  48. return self::parseAsHReview($mf2, $item, $http);
  49. } elseif(in_array('h-product', $item['type'])) {
  50. return self::parseAsHProduct($mf2, $item, $http);
  51. } else {
  52. Parse::debug('This object was not a recognized type.');
  53. return false;
  54. }
  55. }
  56. }
  57. }
  58. // Check for an h-card matching rel=author or the author URL of any h-* on the page,
  59. // and return the h-* object if so
  60. if(isset($mf2['rels']['author'])) {
  61. foreach($mf2['items'] as $card) {
  62. if(in_array('h-card', $card['type']) && array_key_exists('url', $card['properties'])) {
  63. $urls = $card['properties']['url'];
  64. $urls = array_map('self::normalize_url', $urls);
  65. if(count(array_intersect($urls, $mf2['rels']['author'])) > 0) {
  66. // There is an author h-card on this page
  67. // Now look for the first h-* object other than an h-card and use that as the object
  68. foreach($mf2['items'] as $item) {
  69. if(!in_array('h-card', $item['type'])) {
  70. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  71. return self::parseAsHEntry($mf2, $item, $http);
  72. } elseif(in_array('h-event', $item['type'])) {
  73. return self::parseAsHEvent($mf2, $item, $http);
  74. } elseif(in_array('h-review', $item['type'])) {
  75. return self::parseAsHReview($mf2, $item, $http);
  76. } elseif(in_array('h-product', $item['type'])) {
  77. return self::parseAsHProduct($mf2, $item, $http);
  78. }
  79. }
  80. }
  81. }
  82. }
  83. }
  84. }
  85. // If there was more than one h-entry on the page, treat the whole page as a feed
  86. if(count($mf2['items']) > 1) {
  87. if(count(array_filter($mf2['items'], function($item){
  88. return in_array('h-entry', $item['type']);
  89. })) > 1) {
  90. Parse::debug("mf2:2: Recognized $url as an h-feed because there are more than one object on the page");
  91. return self::parseAsHFeed($mf2, $http);
  92. }
  93. }
  94. // If the first item is an h-feed, parse as a feed
  95. $first = $mf2['items'][0];
  96. if(in_array('h-feed', $first['type'])) {
  97. Parse::debug("mf2:3: Recognized $url as an h-feed because the first item is an h-feed");
  98. return self::parseAsHFeed($mf2, $http);
  99. }
  100. // Fallback case, but hopefully we have found something before this point
  101. foreach($mf2['items'] as $item) {
  102. // Otherwise check for a recognized h-entr* object
  103. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  104. Parse::debug("mf2:6: $url is falling back to the first h-entry on the page");
  105. return self::parseAsHEntry($mf2, $item, $http);
  106. } elseif(in_array('h-event', $item['type'])) {
  107. Parse::debug("mf2:6: $url is falling back to the first h-event on the page");
  108. return self::parseAsHEvent($mf2, $item, $http);
  109. } elseif(in_array('h-review', $item['type'])) {
  110. Parse::debug("mf2:6: $url is falling back to the first h-review on the page");
  111. return self::parseAsHReview($mf2, $item, $http);
  112. } elseif(in_array('h-product', $item['type'])) {
  113. Parse::debug("mf2:6: $url is falling back to the first h-product on the page");
  114. return self::parseAsHProduct($mf2, $item, $http);
  115. }
  116. }
  117. Parse::debug("mf2:E: No object at $url was recognized");
  118. return false;
  119. }
  120. private static function collectSingleValues($properties, $urlProperties, $item, &$data) {
  121. foreach($properties as $p) {
  122. if(($v = self::getPlaintext($item, $p)) !== null) {
  123. $data[$p] = $v;
  124. }
  125. }
  126. foreach($urlProperties as $p) {
  127. if(($v = self::getPlaintext($item, $p)) !== null) {
  128. if(self::isURL($v))
  129. $data[$p] = $v;
  130. }
  131. }
  132. }
  133. // Always return arrays, and may contain plaintext content
  134. // Nested objects are added to refs and the URL is used as the value if present
  135. private static function collectArrayValues($properties, $item, &$data, &$refs, &$http) {
  136. foreach($properties as $p) {
  137. if(array_key_exists($p, $item['properties'])) {
  138. foreach($item['properties'][$p] as $v) {
  139. if(is_string($v)) {
  140. if(!array_key_exists($p, $data)) $data[$p] = [];
  141. $data[$p][] = $v;
  142. } elseif(self::isMicroformat($v)) {
  143. if(($u=self::getPlaintext($v, 'url')) && self::isURL($u)) {
  144. if(!array_key_exists($p, $data)) $data[$p] = [];
  145. $data[$p][] = $u;
  146. $ref = self::parse(['items'=>[$v]], $u, $http);
  147. if($ref) {
  148. $refs[$u] = $ref['data'];
  149. }
  150. } else {
  151. if(!array_key_exists($p, $data)) $data[$p] = [];
  152. $data[$p][] = $v['value'];
  153. }
  154. }
  155. }
  156. }
  157. }
  158. }
  159. private static function collectArrayURLValues($properties, $item, &$data, &$refs, &$http) {
  160. foreach($properties as $p) {
  161. if(array_key_exists($p, $item['properties'])) {
  162. foreach($item['properties'][$p] as $v) {
  163. if(is_string($v) && self::isURL($v)) {
  164. if(!array_key_exists($p, $data)) $data[$p] = [];
  165. $data[$p][] = $v;
  166. }
  167. elseif(self::isMicroformat($v) && ($u=self::getPlaintext($v, 'url')) && self::isURL($u)) {
  168. if(!array_key_exists($p, $data)) $data[$p] = [];
  169. $data[$p][] = $u;
  170. // parse the object and put the result in the "refs" object
  171. $ref = self::parse(['items'=>[$v]], $u, $http);
  172. if($ref) {
  173. $refs[$u] = $ref['data'];
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. private static function determineNameAndContent($item, &$data) {
  181. // Determine if the name is distinct from the content
  182. $name = self::getPlaintext($item, 'name');
  183. $content = null;
  184. $textContent = null;
  185. $htmlContent = null;
  186. if(array_key_exists('content', $item['properties'])) {
  187. $content = $item['properties']['content'][0];
  188. if(is_string($content)) {
  189. $textContent = $content;
  190. } elseif(!is_string($content) && is_array($content) && array_key_exists('value', $content)) {
  191. if(array_key_exists('html', $content)) {
  192. $htmlContent = trim(self::sanitizeHTML($content['html']));
  193. $textContent = trim(str_replace("&#xD;","\r",strip_tags($htmlContent)));
  194. $textContent = trim(str_replace("&#xD;","\r",$content['value']));
  195. } else {
  196. $textContent = trim($content['value']);
  197. }
  198. }
  199. // Trim ellipses from the name
  200. $name = preg_replace('/ ?(\.\.\.|…)$/', '', $name);
  201. // Remove all whitespace when checking equality
  202. $nameCompare = preg_replace('/\s/','',trim($name));
  203. $contentCompare = preg_replace('/\s/','',trim($textContent));
  204. // Check if the name is a prefix of the content
  205. if($contentCompare && $nameCompare && strpos($contentCompare, $nameCompare) === 0) {
  206. $name = null;
  207. }
  208. }
  209. if($name) {
  210. $data['name'] = $name;
  211. }
  212. // If there is content, always return the plaintext content, and return HTML content if it's different
  213. if($content) {
  214. $data['content'] = [
  215. 'text' => $textContent
  216. ];
  217. if($htmlContent && $textContent != $htmlContent) {
  218. $data['content']['html'] = $htmlContent;
  219. }
  220. // TODO: If no HTML content was included in the post, create HTML by autolinking?
  221. }
  222. }
  223. private static function parseAsHEntry($mf2, $item, $http) {
  224. $data = [
  225. 'type' => 'entry'
  226. ];
  227. $refs = [];
  228. // Single plaintext and URL values
  229. self::collectSingleValues(['published','summary','rsvp'], ['url'], $item, $data);
  230. // These properties are always returned as arrays and may contain plaintext content
  231. self::collectArrayValues(['category','invitee'], $item, $data, $refs, $http);
  232. // These properties are always returned as arrays and always URLs
  233. // If the value is an h-* object with a URL, the URL is used and a "ref" is added as well
  234. self::collectArrayURLValues(['photo','video','audio','syndication','in-reply-to','like-of','repost-of','bookmark-of'], $item, $data, $refs, $http);
  235. self::determineNameAndContent($item, $data);
  236. if($author = self::findAuthor($mf2, $item, $http))
  237. $data['author'] = $author;
  238. $response = [
  239. 'data' => $data
  240. ];
  241. if(count($refs)) {
  242. $response['refs'] = $refs;
  243. }
  244. return $response;
  245. }
  246. private static function parseAsHReview($mf2, $item, $http) {
  247. $data = [
  248. 'type' => 'review'
  249. ];
  250. $refs = [];
  251. // TODO: add description as an HTML value
  252. self::collectSingleValues(['summary','published','rating','best','worst'], ['url'], $item, $data);
  253. self::collectArrayValues(['category'], $item, $data, $refs, $http);
  254. self::collectArrayURLValues(['item'], $item, $data, $refs, $http);
  255. self::determineNameAndContent($item, $data);
  256. if($author = self::findAuthor($mf2, $item, $http))
  257. $data['author'] = $author;
  258. $response = [
  259. 'data' => $data
  260. ];
  261. if(count($refs)) {
  262. $response['refs'] = $refs;
  263. }
  264. return $response;
  265. }
  266. private static function parseAsHProduct($mf2, $item, $http) {
  267. $data = [
  268. 'type' => 'product'
  269. ];
  270. self::collectSingleValues(['name','identifier','price'], ['url'], $item, $data);
  271. self::collectArrayValues(['category','brand'], $item, $data, $refs, $http);
  272. self::collectArrayURLValues(['photo','video','audio'], $item, $data, $refs, $http);
  273. $response = [
  274. 'data' => $data
  275. ];
  276. return $response;
  277. }
  278. private static function parseAsHEvent($mf2, $item, $http) {
  279. $data = [
  280. 'type' => 'event'
  281. ];
  282. $refs = [];
  283. // Single plaintext and URL values
  284. self::collectSingleValues(['name','summary','published','start','end','duration'], ['url'], $item, $data);
  285. // These properties are always returned as arrays and may contain plaintext content
  286. self::collectArrayValues(['category','location','attendee'], $item, $data, $refs, $http);
  287. // These properties are always returned as arrays and always URLs
  288. // If the value is an h-* object with a URL, the URL is used and a "ref" is added as well
  289. self::collectArrayURLValues(['photo','video','audio','syndication'], $item, $data, $refs, $http);
  290. // If there is a description, always return the plaintext description, and return HTML description if it's different
  291. $textDescription = null;
  292. $htmlDescription = null;
  293. if(array_key_exists('description', $item['properties'])) {
  294. $description = $item['properties']['description'][0];
  295. if(is_string($description)) {
  296. $textDescription = $description;
  297. } elseif(!is_string($description) && is_array($description) && array_key_exists('value', $description)) {
  298. if(array_key_exists('html', $description)) {
  299. $htmlDescription = trim(self::sanitizeHTML($description['html']));
  300. $textDescription = trim(str_replace("&#xD;","\r",strip_tags($htmlDescription)));
  301. $textDescription = trim(str_replace("&#xD;","\r",$description['value']));
  302. } else {
  303. $textDescription = trim($description['value']);
  304. }
  305. }
  306. }
  307. if($textDescription) {
  308. $data['description'] = [
  309. 'text' => $textDescription
  310. ];
  311. if($htmlDescription && $textDescription != $htmlDescription) {
  312. $data['description']['html'] = $htmlDescription;
  313. }
  314. }
  315. $response = [
  316. 'data' => $data
  317. ];
  318. if(count($refs)) {
  319. $response['refs'] = $refs;
  320. }
  321. return $response;
  322. }
  323. private static function parseAsHFeed($mf2, $http) {
  324. $data = [
  325. 'type' => 'feed',
  326. 'author' => [
  327. 'type' => 'card',
  328. 'name' => null,
  329. 'url' => null,
  330. 'photo' => null
  331. ],
  332. 'todo' => 'Not yet implemented. Please see https://github.com/aaronpk/XRay/issues/1'
  333. ];
  334. return [
  335. 'data' => $data,
  336. 'entries' => []
  337. ];
  338. }
  339. private static function parseAsHCard($item, $http, $authorURL=false) {
  340. $data = [
  341. 'type' => 'card',
  342. 'name' => null,
  343. 'url' => null,
  344. 'photo' => null
  345. ];
  346. $properties = ['url','name','photo'];
  347. foreach($properties as $p) {
  348. if($p == 'url' && $authorURL) {
  349. // If there is a matching author URL, use that one
  350. $found = false;
  351. foreach($item['properties']['url'] as $url) {
  352. if(self::isURL($url)) {
  353. $url = self::normalize_url($url);
  354. if($url == $authorURL) {
  355. $data['url'] = $url;
  356. $found = true;
  357. }
  358. }
  359. }
  360. if(!$found && self::isURL($item['properties']['url'][0])) {
  361. $data['url'] = $item['properties']['url'][0];
  362. }
  363. } else if(($v = self::getPlaintext($item, $p)) !== null) {
  364. // Make sure the URL property is actually a URL
  365. if($p == 'url' || $p == 'photo') {
  366. if(self::isURL($v))
  367. $data[$p] = $v;
  368. } else {
  369. $data[$p] = $v;
  370. }
  371. }
  372. }
  373. $response = [
  374. 'data' => $data
  375. ];
  376. return $response;
  377. }
  378. private static function findAuthor($mf2, $item, $http) {
  379. $author = [
  380. 'type' => 'card',
  381. 'name' => null,
  382. 'url' => null,
  383. 'photo' => null
  384. ];
  385. // Author Discovery
  386. // http://indiewebcamp.com/authorship
  387. $authorPage = false;
  388. if(array_key_exists('author', $item['properties'])) {
  389. // Check if any of the values of the author property are an h-card
  390. foreach($item['properties']['author'] as $a) {
  391. if(self::isHCard($a)) {
  392. // 5.1 "if it has an h-card, use it, exit."
  393. return self::parseAsHCard($a, $http)['data'];
  394. } elseif(is_string($a)) {
  395. if(self::isURL($a)) {
  396. // 5.2 "otherwise if author property is an http(s) URL, let the author-page have that URL"
  397. $authorPage = $a;
  398. } else {
  399. // 5.3 "otherwise use the author property as the author name, exit"
  400. // We can only set the name, no h-card or URL was found
  401. $author['name'] = self::getPlaintext($item, 'author');
  402. return $author;
  403. }
  404. } else {
  405. // This case is only hit when the author property is an mf2 object that is not an h-card
  406. $author['name'] = self::getPlaintext($item, 'author');
  407. return $author;
  408. }
  409. }
  410. }
  411. // 6. "if no author page was found" ... check for rel-author link
  412. if(!$authorPage) {
  413. if(isset($mf2['rels']) && isset($mf2['rels']['author']))
  414. $authorPage = $mf2['rels']['author'][0];
  415. }
  416. // 7. "if there is an author-page URL" ...
  417. if($authorPage) {
  418. // 7.1 "get the author-page from that URL and parse it for microformats2"
  419. $authorPageContents = self::getURL($authorPage, $http);
  420. if($authorPageContents) {
  421. foreach($authorPageContents['items'] as $i) {
  422. if(self::isHCard($i)) {
  423. // 7.2 "if author-page has 1+ h-card with url == uid == author-page's URL, then use first such h-card, exit."
  424. if(array_key_exists('url', $i['properties'])
  425. and in_array($authorPage, $i['properties']['url'])
  426. and array_key_exists('uid', $i['properties'])
  427. and in_array($authorPage, $i['properties']['uid'])
  428. ) {
  429. return self::parseAsHCard($i, $http, $authorPage)['data'];
  430. }
  431. // 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"
  432. $relMeLinks = (isset($authorPageContents['rels']) && isset($authorPageContents['rels']['me'])) ? $authorPageContents['rels']['me'] : [];
  433. if(count($relMeLinks) > 0
  434. and array_key_exists('url', $i['properties'])
  435. and count(array_intersect($i['properties']['url'], $relMeLinks)) > 0
  436. ) {
  437. return self::parseAsHCard($i, $http, $authorPage)['data'];
  438. }
  439. }
  440. }
  441. }
  442. // 7.4 "if the h-entry's page has 1+ h-card with url == author-page URL, use first such h-card, exit."
  443. foreach($mf2['items'] as $i) {
  444. if(self::isHCard($i)) {
  445. if(array_key_exists('url', $i['properties'])
  446. and in_array($authorPage, $i['properties']['url'])
  447. ) {
  448. return self::parseAsHCard($i, $http)['data'];
  449. }
  450. }
  451. }
  452. }
  453. if(!$author['name'] && !$author['photo'] && !$author['url'])
  454. return null;
  455. return $author;
  456. }
  457. private static function sanitizeHTML($html) {
  458. $config = HTMLPurifier_Config::createDefault();
  459. $config->set('Cache.DefinitionImpl', null);
  460. $config->set('HTML.AllowedElements', [
  461. 'a',
  462. 'abbr',
  463. 'b',
  464. 'code',
  465. 'del',
  466. 'em',
  467. 'i',
  468. 'img',
  469. 'q',
  470. 'strike',
  471. 'strong',
  472. 'time',
  473. 'blockquote',
  474. 'pre',
  475. 'p',
  476. 'h1',
  477. 'h2',
  478. 'h3',
  479. 'h4',
  480. 'h5',
  481. 'h6',
  482. 'ul',
  483. 'li',
  484. 'ol'
  485. ]);
  486. $def = $config->getHTMLDefinition(true);
  487. $def->addElement(
  488. 'time',
  489. 'Inline',
  490. 'Inline',
  491. 'Common',
  492. [
  493. 'datetime' => 'Text'
  494. ]
  495. );
  496. // Override the allowed classes to only support Microformats2 classes
  497. $def->manager->attrTypes->set('Class', new HTMLPurifier_AttrDef_HTML_Microformats2());
  498. $purifier = new HTMLPurifier($config);
  499. $sanitized = $purifier->purify($html);
  500. $sanitized = str_replace("&#xD;","\r",$sanitized);
  501. return $sanitized;
  502. }
  503. private static function hasNumericKeys(array $arr) {
  504. foreach($arr as $key=>$val)
  505. if (is_numeric($key))
  506. return true;
  507. return false;
  508. }
  509. private static function isMicroformat($mf) {
  510. return is_array($mf)
  511. and !self::hasNumericKeys($mf)
  512. and !empty($mf['type'])
  513. and isset($mf['properties']);
  514. }
  515. private static function isHCard($mf) {
  516. return is_array($mf)
  517. and !empty($mf['type'])
  518. and is_array($mf['type'])
  519. and in_array('h-card', $mf['type']);
  520. }
  521. private static function isURL($string) {
  522. return preg_match('/^https?:\/\/.+\..+$/', $string);
  523. }
  524. // Given an array of microformats properties and a key name, return the plaintext value
  525. // at that property
  526. // e.g.
  527. // {"properties":{"published":["foo"]}} results in "foo"
  528. private static function getPlaintext($mf2, $k, $fallback=null) {
  529. if(!empty($mf2['properties'][$k]) and is_array($mf2['properties'][$k])) {
  530. // $mf2['properties'][$v] will always be an array since the input was from the mf2 parser
  531. $value = $mf2['properties'][$k][0];
  532. if(is_string($value)) {
  533. return $value;
  534. } elseif(self::isMicroformat($value) && array_key_exists('value', $value)) {
  535. return $value['value'];
  536. }
  537. }
  538. return $fallback;
  539. }
  540. private static function getURL($url, $http) {
  541. if(!$url) return null;
  542. // TODO: consider adding caching here
  543. $result = $http->get($url);
  544. if($result['error'] || !$result['body']) {
  545. return null;
  546. }
  547. return \mf2\Parse($result['body'], $url);
  548. }
  549. private static function normalize_url($url) {
  550. $parts = parse_url($url);
  551. if(empty($parts['path']))
  552. $parts['path'] = '/';
  553. $parts['host'] = strtolower($parts['host']);
  554. return self::build_url($parts);
  555. }
  556. private static function build_url($parsed_url) {
  557. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  558. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  559. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  560. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  561. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  562. $pass = ($user || $pass) ? "$pass@" : '';
  563. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  564. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  565. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  566. return "$scheme$user$pass$host$port$path$query$fragment";
  567. }
  568. }