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.

373 lines
11 KiB

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