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.

881 lines
31 KiB

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