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.

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