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.

1008 lines
36 KiB

6 years ago
6 years ago
8 years ago
  1. <?php
  2. namespace p3k\XRay\Formats;
  3. class Mf2 extends Format {
  4. use Mf2Feed;
  5. public static function matches_host($url) {
  6. return true;
  7. }
  8. public static function matches($url) {
  9. return true;
  10. }
  11. public static function parse($http_response, $http, $opts=[]) {
  12. $mf2 = $http_response['body'];
  13. $url = $http_response['url'];
  14. if(!isset($mf2['items']) || count($mf2['items']) == 0)
  15. return false;
  16. // If they are expecting a feed, always return a feed or an error
  17. if(isset($opts['expect']) && $opts['expect'] == 'feed') {
  18. return self::parseAsHFeed($mf2, $http, $url);
  19. }
  20. // Remove h-breadcrumb since we never use it and it causes problems determining
  21. // whether a page is a feed or permalink
  22. $mf2['items'] = array_values(array_filter($mf2['items'], function($item){
  23. return !in_array('h-breadcrumb', $item['type']);
  24. }));
  25. $items = $mf2['items'];
  26. // If there is more than one item on the page, it may be a feed.
  27. // Remove an h-card if there is one that doesn't match the page URL, then try again.
  28. // (Don't modify the actual tree, but compare on the modified tree)
  29. if(count($items) > 1) {
  30. $tmpmf2 = array_filter($items, function($item) use($url){
  31. return !(in_array('h-card', $item['type']) && isset($item['properties']['url'][0]) && $item['properties']['url'][0] != $url);
  32. });
  33. $items = array_values($tmpmf2);
  34. }
  35. // If there is only one item left on the page, it's a permalink, and just use that
  36. if(count($items) == 1) {
  37. $item = $items[0];
  38. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  39. #Parse::debug("mf2:0: Recognized $url as an h-entry it is the only item on the page");
  40. return self::parseAsHEntry($mf2, $item, $http, $url);
  41. }
  42. if(in_array('h-event', $item['type'])) {
  43. #Parse::debug("mf2:0: Recognized $url as an h-event it is the only item on the page");
  44. return self::parseAsHEvent($mf2, $item, $http, $url);
  45. }
  46. if(in_array('h-review', $item['type'])) {
  47. #Parse::debug("mf2:0: Recognized $url as an h-review it is the only item on the page");
  48. return self::parseAsHReview($mf2, $item, $http, $url);
  49. }
  50. if(in_array('h-recipe', $item['type'])) {
  51. #Parse::debug("mf2:0: Recognized $url as an h-recipe it is the only item on the page");
  52. return self::parseAsHRecipe($mf2, $item, $http, $url);
  53. }
  54. if(in_array('h-product', $item['type'])) {
  55. #Parse::debug("mf2:0: Recognized $url as an h-product it is the only item on the page");
  56. return self::parseAsHProduct($mf2, $item, $http, $url);
  57. }
  58. if(in_array('h-item', $item['type'])) {
  59. #Parse::debug("mf2:0: Recognized $url as an h-product it is the only item on the page");
  60. return self::parseAsHItem($mf2, $item, $http, $url);
  61. }
  62. if(in_array('h-card', $item['type'])) {
  63. #Parse::debug("mf2:0: Recognized $url as an h-card it is the only item on the page");
  64. return self::parseAsHCard($item, $http, $url, $url);
  65. }
  66. if(in_array('h-app', $item['type']) || in_array('h-x-app', $item['type'])) {
  67. #Parse::debug("mf2:0: Recognized $url as an h-feed because it is the only item on the page");
  68. return self::parseAsHApp($mf2, $item, $http, $url);
  69. }
  70. if(in_array('h-feed', $item['type'])) {
  71. #Parse::debug("mf2:0: Recognized $url as an h-feed because it is the only item on the page");
  72. return self::parseAsHFeed($mf2, $http, $url);
  73. }
  74. }
  75. // Check the list of items on the page to see if one matches the URL of the page,
  76. // and treat as a permalink for that object if so.
  77. foreach($mf2['items'] as $item) {
  78. if(array_key_exists('url', $item['properties'])) {
  79. $urls = $item['properties']['url'];
  80. $urls = array_map('\p3k\XRay\normalize_url', $urls);
  81. if(in_array($url, $urls)) {
  82. #Parse::debug("mf2:1: Recognized $url as a permalink because an object on the page matched the URL of the request");
  83. if(in_array('h-card', $item['type'])) {
  84. return self::parseAsHCard($item, $http, $url, $url);
  85. } elseif(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  86. return self::parseAsHEntry($mf2, $item, $http, $url);
  87. } elseif(in_array('h-event', $item['type'])) {
  88. return self::parseAsHEvent($mf2, $item, $http, $url);
  89. } elseif(in_array('h-review', $item['type'])) {
  90. return self::parseAsHReview($mf2, $item, $http, $url);
  91. } elseif(in_array('h-recipe', $item['type'])) {
  92. return self::parseAsHRecipe($mf2, $item, $http, $url);
  93. } elseif(in_array('h-product', $item['type'])) {
  94. return self::parseAsHProduct($mf2, $item, $http, $url);
  95. } elseif(in_array('h-item', $item['type'])) {
  96. return self::parseAsHItem($mf2, $item, $http, $url);
  97. } elseif(in_array('h-app', $item['type']) || in_array('h-x-app', $item['type'])) {
  98. return self::parseAsHApp($mf2, $item, $http, $url);
  99. } elseif(in_array('h-feed', $item['type'])) {
  100. return self::parseAsHFeed($mf2, $http, $url);
  101. } else {
  102. #Parse::debug('This object was not a recognized type.');
  103. return false;
  104. }
  105. }
  106. }
  107. }
  108. // Check for an h-card matching rel=author or the author URL of any h-* on the page,
  109. // and return the h-* object if so
  110. if(isset($mf2['rels']['author'])) {
  111. foreach($mf2['items'] as $card) {
  112. if(in_array('h-card', $card['type']) && array_key_exists('url', $card['properties'])) {
  113. $urls = \p3k\XRay\normalize_urls($card['properties']['url']);
  114. if(count(array_intersect($urls, \p3k\XRay\normalize_urls($mf2['rels']['author']))) > 0) {
  115. // There is an author h-card on this page
  116. // Now look for the first h-* object other than an h-card and use that as the object
  117. foreach($mf2['items'] as $item) {
  118. if(!in_array('h-card', $item['type'])) {
  119. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  120. return self::parseAsHEntry($mf2, $item, $http, $url);
  121. } elseif(in_array('h-event', $item['type'])) {
  122. return self::parseAsHEvent($mf2, $item, $http, $url);
  123. } elseif(in_array('h-review', $item['type'])) {
  124. return self::parseAsHReview($mf2, $item, $http, $url);
  125. } elseif(in_array('h-recipe', $item['type'])) {
  126. return self::parseAsHRecipe($mf2, $item, $http, $url);
  127. } elseif(in_array('h-product', $item['type'])) {
  128. return self::parseAsHProduct($mf2, $item, $http, $url);
  129. } elseif(in_array('h-item', $item['type'])) {
  130. return self::parseAsHItem($mf2, $item, $http, $url);
  131. } elseif(in_array('h-app', $item['type']) || in_array('h-x-app', $item['type'])) {
  132. return self::parseAsHApp($mf2, $item, $http, $url);
  133. }
  134. }
  135. }
  136. }
  137. }
  138. }
  139. }
  140. // At this point, if there are any h-entrys left on the page, it's probably a feed.
  141. if(count($items) > 0) {
  142. if(count(array_filter($items, function($item){
  143. return in_array('h-entry', $item['type']);
  144. })) > 0) {
  145. #Parse::debug("mf2:2: Recognized $url as an h-feed because there are more than one object on the page");
  146. return self::parseAsHFeed($mf2, $http, $url);
  147. }
  148. }
  149. // If the first item is an h-feed, parse as a feed
  150. $first = $items[0];
  151. if(in_array('h-feed', $first['type'])) {
  152. #Parse::debug("mf2:3: Recognized $url as an h-feed because the first item is an h-feed");
  153. return self::parseAsHFeed($mf2, $http, $url);
  154. }
  155. // Fallback case, but hopefully we have found something before this point
  156. foreach($mf2['items'] as $item) {
  157. // Otherwise check for a recognized h-* object
  158. if(in_array('h-entry', $item['type']) || in_array('h-cite', $item['type'])) {
  159. #Parse::debug("mf2:6: $url is falling back to the first h-entry on the page");
  160. return self::parseAsHEntry($mf2, $item, $http, $url);
  161. } elseif(in_array('h-event', $item['type'])) {
  162. #Parse::debug("mf2:6: $url is falling back to the first h-event on the page");
  163. return self::parseAsHEvent($mf2, $item, $http, $url);
  164. } elseif(in_array('h-review', $item['type'])) {
  165. #Parse::debug("mf2:6: $url is falling back to the first h-review on the page");
  166. return self::parseAsHReview($mf2, $item, $http, $url);
  167. } elseif(in_array('h-recipe', $item['type'])) {
  168. #Parse::debug("mf2:6: $url is falling back to the first h-recipe on the page");
  169. return self::parseAsHRecipe($mf2, $item, $http, $url);
  170. } elseif(in_array('h-product', $item['type'])) {
  171. #Parse::debug("mf2:6: $url is falling back to the first h-product on the page");
  172. return self::parseAsHProduct($mf2, $item, $http, $url);
  173. } elseif(in_array('h-item', $item['type'])) {
  174. #Parse::debug("mf2:6: $url is falling back to the first h-item on the page");
  175. return self::parseAsHItem($mf2, $item, $http, $url);
  176. } elseif(in_array('h-app', $item['type']) || in_array('h-x-app', $item['type'])) {
  177. #Parse::debug("mf2:6: $url is falling back to the first h-item on the page");
  178. return self::parseAsHApp($mf2, $item, $http, $url);
  179. }
  180. }
  181. #Parse::debug("mf2:E: No object at $url was recognized");
  182. return false;
  183. }
  184. private static function collectSingleValues($properties, $urlProperties, $item, $url, &$data) {
  185. foreach($properties as $p) {
  186. if(($v = self::getPlaintext($item, $p)) !== null) {
  187. $data[$p] = $v;
  188. }
  189. }
  190. foreach($urlProperties as $p) {
  191. if($p == 'url') {
  192. // Special handling for the 'url' property to prioritize finding the URL on the same domain
  193. if($values = self::getPlaintextValues($item, 'url')) {
  194. if(count($values) == 1) {
  195. if(self::isURL($values[0]))
  196. $data['url'] = $values[0];
  197. }
  198. else {
  199. $set = false;
  200. foreach($values as $v) {
  201. if(self::isURL($v) && parse_url($v, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) {
  202. $set = true;
  203. $data['url'] = $v;
  204. }
  205. }
  206. if(!$set) {
  207. // Fall back to the first URL if there isn't one on the domain
  208. if(self::isURL($values[0]))
  209. $data['url'] = $values[0];
  210. }
  211. }
  212. }
  213. } else {
  214. if(($v = self::getPlaintext($item, $p)) !== null) {
  215. if(self::isURL($v))
  216. $data[$p] = $v;
  217. }
  218. }
  219. }
  220. }
  221. private static function parseHTMLValue($property, $item) {
  222. if(!array_key_exists($property, $item['properties']))
  223. return null;
  224. $textContent = false;
  225. $htmlContent = false;
  226. $content = $item['properties'][$property][0];
  227. if(is_string($content)) {
  228. $textContent = $content;
  229. } elseif(!is_string($content) && is_array($content) && array_key_exists('html', $content)) {
  230. if(array_key_exists('html', $content)) {
  231. // Only allow images in the content if there is no photo property set
  232. if(isset($item['properties']['photo']))
  233. $allowImg = false;
  234. else
  235. $allowImg = true;
  236. $htmlContent = trim(self::sanitizeHTML($content['html'], $allowImg));
  237. #$textContent = trim(str_replace("&#xD;","\r",$content['value']));
  238. $textContent = trim(self::stripHTML($htmlContent));
  239. } else {
  240. if(isset($content['value']))
  241. $textContent = trim($content['value']);
  242. }
  243. }
  244. if($textContent || $htmlContent) {
  245. $data = [
  246. 'text' => $textContent
  247. ];
  248. // Only add HTML content if there is actual content.
  249. // If the text content ends up empty, then the HTML should be too
  250. // e.g. <div class="e-content"><a href=""><img src="" class="u-photo"></a></div>
  251. // should not return content of <a href=""></a>
  252. // TODO: still need to remove empty <a> tags when there is other text in the content
  253. if($htmlContent && $textContent && $textContent != $htmlContent) {
  254. $data['html'] = $htmlContent;
  255. }
  256. // Also add HTML content if it contains images, video or audio
  257. // TODO: allow video and audio tags in content, then uncomment this
  258. if(strpos($htmlContent, '<img') !== false
  259. /* || strpos($htmlContent, '<video') !== false */
  260. /* || strpos($htmlContent, '<audio') !== false */) {
  261. $data['html'] = $htmlContent;
  262. }
  263. if(!$data['text'] && !isset($data['html']))
  264. return null;
  265. return $data;
  266. } else {
  267. return null;
  268. }
  269. }
  270. // Always return arrays, and may contain plaintext content
  271. // Nested objects are added to refs and the URL is used as the value if present
  272. private static function collectArrayValues($properties, $item, &$data, &$refs, &$http) {
  273. foreach($properties as $p) {
  274. if(array_key_exists($p, $item['properties'])) {
  275. foreach($item['properties'][$p] as $v) {
  276. if(is_string($v)) {
  277. if(!array_key_exists($p, $data)) $data[$p] = [];
  278. if(!in_array($v, $data[$p]))
  279. $data[$p][] = $v;
  280. } elseif(self::isMicroformat($v)) {
  281. if(($u=self::getPlaintext($v, 'url')) && self::isURL($u)) {
  282. if(!array_key_exists($p, $data)) $data[$p] = [];
  283. if(!in_array($u, $data[$p]))
  284. $data[$p][] = $u;
  285. $ref = self::parse([
  286. 'body' => ['items'=>[$v]],
  287. 'url' => $u,
  288. 'code' => null,
  289. ], $http);
  290. if($ref) {
  291. $refs[$u] = $ref['data'];
  292. }
  293. } else {
  294. if(!array_key_exists($p, $data)) $data[$p] = [];
  295. if(!in_array($v['value'], $data[$p]))
  296. $data[$p][] = $v['value'];
  297. }
  298. }
  299. }
  300. }
  301. }
  302. }
  303. private static function parseEmbeddedHCard($property, $item, &$http) {
  304. if(array_key_exists($property, $item['properties'])) {
  305. $mf2 = $item['properties'][$property][0];
  306. if(is_string($mf2) && self::isURL($mf2)) {
  307. $hcard = [
  308. 'type' => 'card',
  309. 'url' => $mf2
  310. ];
  311. return $hcard;
  312. } if(self::isMicroformat($mf2) && in_array('h-card', $mf2['type'])) {
  313. $hcard = [
  314. 'type' => 'card',
  315. ];
  316. $properties = ['name','latitude','longitude','street-address','locality','region','country-name','url'];
  317. foreach($properties as $p) {
  318. if($v=self::getPlaintext($mf2, $p)) {
  319. $hcard[$p] = $v;
  320. }
  321. }
  322. return $hcard;
  323. }
  324. }
  325. return false;
  326. }
  327. private static function collectArrayURLValues($properties, $item, &$data, &$refs, &$http) {
  328. $keys = [];
  329. foreach($properties as $p) {
  330. if(array_key_exists($p, $item['properties'])) {
  331. foreach($item['properties'][$p] as $v) {
  332. if(is_string($v) && self::isURL($v)) {
  333. if(!array_key_exists($p, $data)) $data[$p] = [];
  334. $data[$p][] = $v;
  335. $keys[] = $p;
  336. }
  337. elseif(self::isImgAlt($v)) {
  338. // For the moment, disregard the alt value and output a string for compatibility with current consuming code.
  339. $imgURL = $v['value'];
  340. if (is_string($imgURL) and self::isURL($imgURL)) {
  341. if(!array_key_exists($p, $data)) $data[$p] = [];
  342. $data[$p][] = $imgURL;
  343. $keys[] = $p;
  344. }
  345. }
  346. elseif(self::isMicroformat($v) && ($u=self::getPlaintext($v, 'url')) && self::isURL($u)) {
  347. if(!array_key_exists($p, $data)) $data[$p] = [];
  348. $data[$p][] = $u;
  349. $keys[] = $p;
  350. // parse the object and put the result in the "refs" object
  351. $ref = self::parse([
  352. 'body' => ['items'=>[$v]],
  353. 'url' => $u,
  354. 'code' => null,
  355. ], $http);
  356. if($ref) {
  357. $refs[$u] = $ref['data'];
  358. }
  359. }
  360. }
  361. }
  362. }
  363. // Remove duplicate values
  364. foreach(array_unique($keys) as $key) {
  365. $data[$key] = array_unique($data[$key]);
  366. }
  367. }
  368. private static function determineNameAndContent($item, &$data) {
  369. // Determine if the name is distinct from the content
  370. $name = self::getPlaintext($item, 'name');
  371. $textContent = null;
  372. $htmlContent = null;
  373. $content = self::getHTMLValue($item, 'content');
  374. if(is_string($content)) {
  375. $textContent = $content;
  376. } elseif($content) {
  377. $htmlContent = array_key_exists('html', $content) ? $content['html'] : null;
  378. $textContent = array_key_exists('value', $content) ? $content['value'] : null;
  379. }
  380. $checkedname = $name;
  381. if($content) {
  382. // Trim ellipses from the name
  383. $name = preg_replace('/ ?(\.\.\.|…)$/', '', $name ?: '');
  384. // Remove all whitespace when checking equality
  385. $nameCompare = preg_replace('/\s/','',trim($name) ?: '');
  386. $contentCompare = preg_replace('/\s/','',trim($textContent) ?: '');
  387. // Check if the name is a prefix of the content
  388. if($contentCompare && $nameCompare && strpos($contentCompare, $nameCompare) === 0) {
  389. $checkedname = null;
  390. }
  391. }
  392. if($checkedname) {
  393. $data['name'] = $checkedname;
  394. }
  395. // If there is content, always return the plaintext content, and return HTML content if it's different
  396. if($content) {
  397. $content = self::parseHTMLValue('content', $item);
  398. if($content && ($content['text'] || $content['html'])) {
  399. $data['content']['text'] = $content['text'];
  400. if(isset($content['html']))
  401. $data['content']['html'] = $content['html'];
  402. } else {
  403. // If the content text was blank because the img was removed and that was the only content,
  404. // then put the name back as the name if it was previously set.
  405. // See https://github.com/aaronpk/XRay/issues/57
  406. if($name) {
  407. $data['name'] = $name;
  408. }
  409. }
  410. }
  411. }
  412. private static function parseAsHEntry($mf2, $item, $http, $url) {
  413. $data = [
  414. 'type' => 'entry'
  415. ];
  416. $refs = [];
  417. // Single plaintext and URL values
  418. self::collectSingleValues(['published','summary','rsvp','swarm-coins'], ['url','featured','follow-of'], $item, $url, $data);
  419. if(isset($data['rsvp']))
  420. $data['rsvp'] = strtolower($data['rsvp']);
  421. // These properties are always returned as arrays and may contain plaintext content
  422. // First strip leading hashtags from category values if present
  423. if(array_key_exists('category', $item['properties'])) {
  424. foreach($item['properties']['category'] as $i=>$c) {
  425. if(is_string($c))
  426. $item['properties']['category'][$i] = ltrim($c, '#');
  427. }
  428. }
  429. self::collectArrayValues(['category','invitee'], $item, $data, $refs, $http);
  430. // These properties are always returned as arrays and always URLs
  431. // If the value is an h-* object with a URL, the URL is used and a "ref" is added as well
  432. self::collectArrayURLValues(['photo','video','audio','syndication','in-reply-to','like-of','repost-of','bookmark-of','quotation-of'], $item, $data, $refs, $http);
  433. // Hack to make quotation-of a single value
  434. if(isset($data['quotation-of']))
  435. $data['quotation-of'] = $data['quotation-of'][0];
  436. self::determineNameAndContent($item, $data);
  437. if($author = self::findAuthor($mf2, $item, $http, $url))
  438. $data['author'] = $author;
  439. if($checkin = self::parseEmbeddedHCard('checkin', $item, $http))
  440. $data['checkin'] = $checkin;
  441. $data['post-type'] = \p3k\XRay\PostType::discover($data);
  442. $response = [
  443. 'data' => $data,
  444. ];
  445. if(count($refs)) {
  446. $response['data']['refs'] = $refs;
  447. }
  448. return $response;
  449. }
  450. private static function parseAsHReview($mf2, $item, $http, $url) {
  451. $data = [
  452. 'type' => 'review'
  453. ];
  454. $refs = [];
  455. self::collectSingleValues(['summary','published','rating','best','worst'], ['url'], $item, $url, $data);
  456. // Fallback for Mf1 "description" as content. The PHP parser does not properly map this to "content"
  457. $description = self::parseHTMLValue('description', $item);
  458. if($description) {
  459. $data['content'] = $description;
  460. }
  461. self::collectArrayValues(['category'], $item, $data, $refs, $http);
  462. self::collectArrayURLValues(['item'], $item, $data, $refs, $http);
  463. self::determineNameAndContent($item, $data);
  464. if($author = self::findAuthor($mf2, $item, $http, $url))
  465. $data['author'] = $author;
  466. $data['post-type'] = \p3k\XRay\PostType::discover($data);
  467. $response = [
  468. 'data' => $data
  469. ];
  470. if(count($refs)) {
  471. $response['data']['refs'] = $refs;
  472. }
  473. return $response;
  474. }
  475. private static function parseAsHRecipe($mf2, $item, $http, $url) {
  476. $data = [
  477. 'type' => 'recipe',
  478. ];
  479. $refs = [];
  480. self::collectSingleValues(['name','summary','published','duration','yield','nutrition'], ['url'], $item, $url, $data);
  481. $instructions = self::parseHTMLValue('instructions', $item);
  482. if($instructions) {
  483. $data['instructions'] = $instructions;
  484. }
  485. self::collectArrayValues(['category','ingredient'], $item, $data, $refs, $http);
  486. self::collectArrayURLValues(['photo'], $item, $data, $refs, $http);
  487. if($author = self::findAuthor($mf2, $item, $http, $url))
  488. $data['author'] = $author;
  489. $data['post-type'] = \p3k\XRay\PostType::discover($data);
  490. $response = [
  491. 'data' => $data
  492. ];
  493. if(count($refs)) {
  494. $response['data']['refs'] = $refs;
  495. }
  496. return $response;
  497. }
  498. private static function parseAsHProduct($mf2, $item, $http, $url) {
  499. $data = [
  500. 'type' => 'product'
  501. ];
  502. $refs = [];
  503. self::collectSingleValues(['name','identifier','price'], ['url'], $item, $url, $data);
  504. $description = self::parseHTMLValue('description', $item);
  505. if($description) {
  506. $data['description'] = $description;
  507. }
  508. self::collectArrayValues(['category','brand'], $item, $data, $refs, $http);
  509. self::collectArrayURLValues(['photo','video','audio'], $item, $data, $refs, $http);
  510. $response = [
  511. 'data' => $data
  512. ];
  513. if(count($refs)) {
  514. $response['data']['refs'] = $refs;
  515. }
  516. return $response;
  517. }
  518. private static function parseAsHItem($mf2, $item, $http, $url) {
  519. $data = [
  520. 'type' => 'item'
  521. ];
  522. $refs = [];
  523. self::collectSingleValues(['name'], ['url'], $item, $url, $data);
  524. self::collectArrayURLValues(['photo','video','audio'], $item, $data, $refs, $http);
  525. $response = [
  526. 'data' => $data
  527. ];
  528. if(count($refs)) {
  529. $response['data']['refs'] = $refs;
  530. }
  531. return $response;
  532. }
  533. private static function parseAsHApp($mf2, $item, $http, $url) {
  534. $data = [
  535. 'type' => 'app'
  536. ];
  537. self::collectSingleValues(['name'], ['url','logo'], $item, $url, $data);
  538. self::collectArrayURLValues(['redirect-uri'], $item, $data, $refs, $http);
  539. if(!isset($data['url']))
  540. $data['url'] = $url;
  541. if(isset($mf2['rels']['redirect_uri'])) {
  542. if(!isset($data['redirect-uri'])) $data['redirect-uri'] = [];
  543. $data['redirect-uri'] = array_merge($data['redirect-uri'], $mf2['rels']['redirect_uri']);
  544. }
  545. if(isset($data['redirect-uri'])) {
  546. $data['redirect-uri'] = array_values(array_unique($data['redirect-uri']));
  547. }
  548. $response = [
  549. 'data' => $data
  550. ];
  551. return $response;
  552. }
  553. private static function parseAsHEvent($mf2, $item, $http, $url) {
  554. $data = [
  555. 'type' => 'event'
  556. ];
  557. $refs = [];
  558. // Single plaintext and URL values
  559. self::collectSingleValues(['name','summary','published','start','end','duration'], ['url','featured'], $item, $url, $data);
  560. // These properties are always returned as arrays and may contain plaintext content
  561. self::collectArrayValues(['category','attendee'], $item, $data, $refs, $http);
  562. if($location = self::parseEmbeddedHCard('location', $item, $http))
  563. $data['location'] = $location;
  564. // These properties are always returned as arrays and always URLs
  565. // If the value is an h-* object with a URL, the URL is used and a "ref" is added as well
  566. self::collectArrayURLValues(['photo','video','audio','syndication'], $item, $data, $refs, $http);
  567. // If there is a description, always return the plaintext content, and return HTML content if it's different
  568. $content = self::parseHTMLValue('content', $item);
  569. if($content) {
  570. $data['content'] = $content;
  571. } else {
  572. // Fall back to looking for "description"
  573. $content = self::parseHTMLValue('description', $item);
  574. if($content)
  575. $data['content'] = $content;
  576. }
  577. if($author = self::findAuthor($mf2, $item, $http, $url))
  578. $data['author'] = $author;
  579. $data['post-type'] = \p3k\XRay\PostType::discover($data);
  580. $response = [
  581. 'data' => $data
  582. ];
  583. if(count($refs)) {
  584. $response['data']['refs'] = $refs;
  585. }
  586. return $response;
  587. }
  588. private static function parseAsHCard($item, $http, $url, $authorURL=false) {
  589. $data = [
  590. 'type' => 'card',
  591. 'name' => null,
  592. 'url' => null,
  593. 'photo' => null
  594. ];
  595. $properties = ['url','name','photo'];
  596. foreach($properties as $p) {
  597. if($p == 'url' && $authorURL) {
  598. // If there is a matching author URL, use that one
  599. $found = false;
  600. if (array_key_exists('url', $item['properties']) and is_array($item['properties']['url'])) {
  601. foreach($item['properties']['url'] as $url) {
  602. if(self::isURL($url)) {
  603. $url = \p3k\XRay\normalize_url($url);
  604. if($url == \p3k\XRay\normalize_url($authorURL)) {
  605. $data['url'] = $url;
  606. $found = true;
  607. }
  608. }
  609. }
  610. if(!$found && self::isURL($item['properties']['url'][0])) {
  611. $data['url'] = $item['properties']['url'][0];
  612. }
  613. }
  614. } else if(($v = self::getPlaintext($item, $p)) !== null) {
  615. // Make sure the URL property is actually a URL
  616. if($p == 'url' || $p == 'photo') {
  617. if(self::isURL($v))
  618. $data[$p] = $v;
  619. } else {
  620. $data[$p] = $v;
  621. }
  622. }
  623. }
  624. // If no URL property was found, use the $authorURL provided
  625. if(!$data['url'])
  626. $data['url'] = $authorURL;
  627. $response = [
  628. 'data' => $data
  629. ];
  630. return $response;
  631. }
  632. private static function findAuthor($mf2, $item, $http, $url) {
  633. $author = [
  634. 'type' => 'card',
  635. 'name' => null,
  636. 'url' => null,
  637. 'photo' => null
  638. ];
  639. // Start by setting the URL of the author to the author URL if one is present in the item.
  640. // It will be upgraded to a full h-card if additional data can be found.
  641. if(isset($item['properties']['author'][0]) && self::isURL($item['properties']['author'][0])) {
  642. $author['url'] = $item['properties']['author'][0];
  643. }
  644. // Author Discovery
  645. // http://indiewebcamp.com/authorship
  646. $authorPage = false;
  647. if(array_key_exists('author', $item['properties'])) {
  648. // Check if any of the values of the author property are an h-card
  649. foreach($item['properties']['author'] as $a) {
  650. if(self::isHCard($a)) {
  651. // 5.1 "if it has an h-card, use it, exit."
  652. return self::parseAsHCard($a, $http, $url)['data'];
  653. } elseif(is_string($a)) {
  654. if(self::isURL($a)) {
  655. // 5.2 "otherwise if author property is an http(s) URL, let the author-page have that URL"
  656. $authorPage = $a;
  657. } else {
  658. // 5.3 "otherwise use the author property as the author name, exit"
  659. // We can only set the name, no h-card or URL was found
  660. $author['name'] = self::getPlaintext($item, 'author');
  661. return $author;
  662. }
  663. } else {
  664. // This case is only hit when the author property is an mf2 object that is not an h-card
  665. $author['name'] = self::getPlaintext($item, 'author');
  666. return $author;
  667. }
  668. }
  669. }
  670. // 6. "if no author page was found" ... check for rel-author link
  671. if(!$authorPage) {
  672. if(isset($mf2['rels']) && isset($mf2['rels']['author']))
  673. $authorPage = $mf2['rels']['author'][0];
  674. }
  675. // 7. "if there is an author-page URL" ...
  676. if($authorPage) {
  677. // 7.1 "get the author-page from that URL and parse it for microformats2"
  678. $authorPageContents = self::getURL($authorPage, $http);
  679. if($authorPageContents) {
  680. $allHCards = self::findAllMicroformatsByType($authorPageContents, 'h-card');
  681. $numHCards = count($allHCards);
  682. foreach($allHCards as $i) {
  683. if(self::isHCard($i)) {
  684. // 7.2 "if author-page has 1+ h-card with url == uid == author-page's URL, then use first such h-card, exit."
  685. if(array_key_exists('url', $i['properties'])
  686. and in_array(\p3k\XRay\normalize_url($authorPage), \p3k\XRay\normalize_urls($i['properties']['url']))
  687. and array_key_exists('uid', $i['properties'])
  688. and in_array(\p3k\XRay\normalize_url($authorPage), \p3k\XRay\normalize_urls($i['properties']['uid']))
  689. ) {
  690. return self::parseAsHCard($i, $http, $url, $authorPage)['data'];
  691. }
  692. // 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"
  693. $relMeLinks = (isset($authorPageContents['rels']) && isset($authorPageContents['rels']['me'])) ? $authorPageContents['rels']['me'] : [];
  694. if(count($relMeLinks) > 0
  695. and array_key_exists('url', $i['properties'])
  696. and count(array_intersect(\p3k\XRay\normalize_urls($i['properties']['url']), \p3k\XRay\normalize_urls($relMeLinks))) > 0
  697. ) {
  698. return self::parseAsHCard($i, $http, $url, $authorPage)['data'];
  699. }
  700. }
  701. }
  702. }
  703. // 7.4 "if the h-entry's page has 1+ h-card with url == author-page URL, use first such h-card, exit."
  704. foreach($mf2['items'] as $i) {
  705. if(self::isHCard($i)) {
  706. if(array_key_exists('url', $i['properties'])
  707. and in_array(\p3k\XRay\normalize_url($authorPage), \p3k\XRay\normalize_urls($i['properties']['url']))
  708. ) {
  709. return self::parseAsHCard($i, $http, $url)['data'];
  710. }
  711. }
  712. // Also check the "author" property
  713. // (for finding the author of an h-feed's children when the author is the p-author property of the h-feed)
  714. if(isset($i['properties']['author'])) {
  715. foreach($i['properties']['author'] as $ic) {
  716. if(self::isHCard($ic)) {
  717. if(array_key_exists('url', $ic['properties'])
  718. and in_array(\p3k\XRay\normalize_url($authorPage), \p3k\XRay\normalize_urls($ic['properties']['url']))
  719. ) {
  720. return self::parseAsHCard($ic, $http, $url)['data'];
  721. }
  722. }
  723. }
  724. }
  725. }
  726. }
  727. // The below is not yet in the authorship algorithm.
  728. // If the top object is an h-feed, check for an author property there
  729. if(isset($mf2['items'][0]['type'][0]) && in_array('h-feed', $mf2['items'][0]['type'])) {
  730. if(isset($mf2['items'][0]['properties']['author'][0])) {
  731. $potentialAuthor = $mf2['items'][0]['properties']['author'][0];
  732. if(self::isHCard($potentialAuthor)) {
  733. return self::parseAsHCard($potentialAuthor, $http, $url)['data'];
  734. }
  735. }
  736. }
  737. // If still no author is found, and this page is a feed (list of h-*),
  738. // then use the first h-card in the list of items.
  739. $items = array_filter($mf2['items'], function($item){
  740. return !in_array('h-card', $item['type']);
  741. });
  742. if(count($items) > 1) {
  743. $card = self::_findFirstOfType($mf2, 'h-card');
  744. if($card) {
  745. return self::parseAsHCard($card, $http, $url)['data'];
  746. }
  747. }
  748. if(!$author['name'] && !$author['photo'] && !$author['url'])
  749. return null;
  750. return $author;
  751. }
  752. private static function hasNumericKeys(array $arr) {
  753. foreach($arr as $key=>$val)
  754. if (is_numeric($key))
  755. return true;
  756. return false;
  757. }
  758. private static function isImgAlt($mf) {
  759. return is_array($mf)
  760. and !self::hasNumericKeys($mf)
  761. and array_key_exists('value', $mf)
  762. and array_key_exists('alt', $mf);
  763. }
  764. private static function isMicroformat($mf) {
  765. return is_array($mf)
  766. and !self::hasNumericKeys($mf)
  767. and !empty($mf['type'])
  768. and isset($mf['properties']);
  769. }
  770. private static function isHCard($mf) {
  771. return is_array($mf)
  772. and !empty($mf['type'])
  773. and is_array($mf['type'])
  774. and in_array('h-card', $mf['type']);
  775. }
  776. private static function isURL($string) {
  777. return is_string($string) && preg_match('/^https?:\/\/.+\..+$/', $string);
  778. }
  779. // Given an array of microformats properties and a key name, return the plaintext value
  780. // at that property
  781. // e.g.
  782. // {"properties":{"published":["foo"]}} results in "foo"
  783. private static function getPlaintext($mf2, $k, $fallback=null) {
  784. if(!empty($mf2['properties'][$k]) and is_array($mf2['properties'][$k])) {
  785. // $mf2['properties'][$v] will always be an array since the input was from the mf2 parser
  786. $value = $mf2['properties'][$k][0];
  787. if(is_string($value)) {
  788. return $value;
  789. }
  790. elseif(self::isImgAlt($value)) {
  791. // For back-compatibility, assume that the consuming code wants the URL value.
  792. if (is_string($value['value'])) {
  793. return $value['value'];
  794. }
  795. } elseif(self::isMicroformat($value) && array_key_exists('value', $value)) {
  796. return $value['value'];
  797. }
  798. }
  799. return $fallback;
  800. }
  801. private static function getHTMLValue($mf2, $k, $fallback=null) {
  802. // Return an array with html and value if the value is html, otherwise return a string
  803. if(!empty($mf2['properties'][$k]) and is_array($mf2['properties'][$k])) {
  804. // $mf2['properties'][$v] will always be an array since the input was from the mf2 parser
  805. $value = $mf2['properties'][$k][0];
  806. if(is_string($value)) {
  807. return $value;
  808. } elseif(isset($value['html'])) {
  809. return $value;
  810. }
  811. }
  812. return $fallback;
  813. }
  814. private static function getPlaintextValues($mf2, $k, $values=[]) {
  815. if(!empty($mf2['properties'][$k]) and is_array($mf2['properties'][$k])) {
  816. foreach($mf2['properties'][$k] as $value) {
  817. if(is_string($value)) {
  818. $values[] = $value;
  819. } elseif(self::isMicroformat($value) && array_key_exists('value', $value)) {
  820. $values[] = $value['value'];
  821. }
  822. }
  823. }
  824. return $values;
  825. }
  826. private static function getURL($url, $http) {
  827. if(!$url || !$http) return null;
  828. // TODO: consider adding caching here
  829. $result = $http->get($url);
  830. if($result['error'] || !$result['body']) {
  831. return null;
  832. }
  833. return \mf2\Parse($result['body'], $url);
  834. }
  835. public static function findAllMicroformatsByType($mf2, $type='h-card') {
  836. $objects = [];
  837. foreach($mf2['items'] as $item) {
  838. if(in_array($type, $item['type'])) {
  839. $objects[] = $item;
  840. } else {
  841. if(isset($item['properties']) && is_array($item['properties'])) {
  842. foreach($item['properties'] as $property=>$values) {
  843. foreach($values as $value) {
  844. if(is_array($value) && isset($value['type']) && is_array($value['type'])) {
  845. if(in_array($type, $value['type'])) {
  846. $objects[] = $value;
  847. }
  848. }
  849. }
  850. }
  851. }
  852. if(isset($item['children']) && is_array($item['children'])) {
  853. $items = $item['children'];
  854. $objects = array_merge($objects, self::findAllMicroformatsByType(['items'=>$items], $type));
  855. }
  856. }
  857. }
  858. return $objects;
  859. }
  860. }