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.

456 lines
13 KiB

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