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.

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