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.

429 lines
12 KiB

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