util.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. function linkback_lenient_target_match($body, $target) {
  3. return strpos(''.$body, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', preg_replace('/\/+$/', '', preg_replace( '/#.*/', '', $target))));
  4. }
  5. function linkback_get_source($source, $target) {
  6. // Check if we are pinging ourselves and ignore
  7. $localprefix = common_config('site', 'server') . '/' . common_config('site', 'path');
  8. if(linkback_lenient_target_match($source, $localprefix) === 0) {
  9. common_debug('Ignoring self ping from ' . $source . ' to ' . $target);
  10. return NULL;
  11. }
  12. $request = HTTPClient::start();
  13. try {
  14. $response = $request->get($source);
  15. } catch(Exception $ex) {
  16. return NULL;
  17. }
  18. $body = htmlspecialchars_decode($response->getBody());
  19. // We're slightly more lenient in our link detection than the spec requires
  20. if(linkback_lenient_target_match($body, $target) === FALSE) {
  21. return NULL;
  22. }
  23. return $response;
  24. }
  25. function linkback_get_target($target) {
  26. // Resolve target (https://github.com/converspace/webmention/issues/43)
  27. $request = HTTPClient::start();
  28. try {
  29. $response = $request->head($target);
  30. } catch(Exception $ex) {
  31. return NULL;
  32. }
  33. try {
  34. $notice = Notice::fromUri($response->getEffectiveUrl());
  35. } catch(UnknownUriException $ex) {
  36. preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
  37. $notice = Notice::getKV('id', $match[1]);
  38. }
  39. if($notice instanceof Notice && $notice->isLocal()) {
  40. return $notice;
  41. } else {
  42. $user = User::getKV('uri', $response->getEffectiveUrl());
  43. if(!$user) {
  44. preg_match('/\/user\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
  45. $user = User::getKV('id', $match[1]);
  46. }
  47. if(!$user) {
  48. preg_match('/\/([^\/\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
  49. if(linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl()) !== FALSE) {
  50. $user = User::getKV('nickname', $match[1]);
  51. }
  52. }
  53. if($user instanceof User) {
  54. return $user;
  55. }
  56. }
  57. return NULL;
  58. }
  59. function linkback_is_contained_in($entry, $target) {
  60. foreach ((array)$entry['properties'] as $key => $values) {
  61. if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target) !== FALSE; })) > 0) {
  62. return $entry['properties'];
  63. }
  64. // check included h-* formats and their links
  65. foreach ($values as $obj) {
  66. if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
  67. isset($obj['properties']) && isset($obj['properties']['url']) &&
  68. count(array_filter($obj['properties']['url'],
  69. function($x) use ($target) { return linkback_lenient_target_match($x, $target) !== FALSE; })) > 0
  70. ) {
  71. return $entry['properties'];
  72. }
  73. }
  74. // check content for the link
  75. if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
  76. return $entry['properties'];
  77. // check summary for the link
  78. } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
  79. return $entry['properties'];
  80. }
  81. }
  82. foreach((array)$entry['children'] as $mf2) {
  83. if(linkback_is_contained_in($mf2, $target)) {
  84. return $entry['properties'];
  85. }
  86. }
  87. return null;
  88. }
  89. // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
  90. function linkback_find_entry($mf2, $target) {
  91. if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
  92. $mf2['items'] = $mf2['items'][0]['children'];
  93. }
  94. $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
  95. foreach ($entries as $entry) {
  96. if($prop = linkback_is_contained_in($entry, $target)) {
  97. return $prop;
  98. }
  99. }
  100. // Default to first one
  101. if(count($entries) > 0) {
  102. return $entries[0]['properties'];
  103. }
  104. return NULL;
  105. }
  106. function linkback_entry_type($entry, $mf2, $target) {
  107. if(!$entry) { return 'mention'; }
  108. if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
  109. foreach($mf2['rels']['in-reply-to'] as $url) {
  110. if(linkback_lenient_target_match($url, $target) !== FALSE) {
  111. return 'reply';
  112. }
  113. }
  114. }
  115. $classes = array(
  116. 'in-reply-to' => 'reply',
  117. 'repost-of' => 'repost',
  118. 'like-of' => 'like',
  119. 'tag-of' => 'tag'
  120. );
  121. foreach((array)$entry as $key => $values) {
  122. if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target) != FALSE; })) > 0) {
  123. if($classes[$key]) { return $classes[$key]; }
  124. }
  125. foreach ($values as $obj) {
  126. if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
  127. isset($obj['properties']) && isset($obj['properties']['url']) &&
  128. count(array_filter($obj['properties']['url'],
  129. function($x) use ($target) { return linkback_lenient_target_match($x, $target) != FALSE; })) > 0
  130. ) {
  131. if($classes[$key]) { return $classes[$key]; }
  132. }
  133. }
  134. }
  135. return 'mention';
  136. }
  137. function linkback_is_dupe($key, $url) {
  138. $dupe = Notice::getKV($key, $url);
  139. if ($dupe instanceof Notice) {
  140. return $dupe;
  141. }
  142. return false;
  143. }
  144. function linkback_hcard($mf2, $url) {
  145. if(empty($mf2['items'])) {
  146. return null;
  147. }
  148. $hcards = array();
  149. foreach($mf2['items'] as $item) {
  150. if(!in_array('h-card', $item['type'])) {
  151. continue;
  152. }
  153. // We found a match, return it immediately
  154. if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
  155. return $item['properties'];
  156. }
  157. // Let's keep all the hcards for later, to return one of them at least
  158. $hcards[] = $item['properties'];
  159. }
  160. // No match immediately for the url we expected, but there were h-cards found
  161. if (count($hcards) > 0) {
  162. return $hcards[0];
  163. }
  164. return null;
  165. }
  166. function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
  167. $content = isset($entry['content']) ? $entry['content'][0]['html'] :
  168. (isset($entry['summary']) ? $entry['summary'][0] : $entry['name'][0]);
  169. $rendered = common_purify($content);
  170. if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
  171. $name = isset($entry['name']) ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
  172. $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
  173. }
  174. $content = common_strip_html($rendered);
  175. $shortened = common_shorten_links($content);
  176. if(Notice::contentTooLong($shortened)) {
  177. $content = substr($content,
  178. 0,
  179. Notice::maxContent() - (mb_strlen($source) + 2));
  180. $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
  181. $content .= ' ' . $source;
  182. }
  183. $options = array('is_local' => Notice::REMOTE,
  184. 'url' => $entry['url'][0],
  185. 'uri' => $entry['url'][0],
  186. 'rendered' => $rendered,
  187. 'replies' => array(),
  188. 'groups' => array(),
  189. 'peopletags' => array(),
  190. 'tags' => array(),
  191. 'urls' => array());
  192. if($notice_or_user instanceof User) {
  193. $options['replies'][] = $notice_or_user->getUri();
  194. } else {
  195. if($entry['type'] == 'repost') {
  196. $options['repeat_of'] = $notice_or_user->id;
  197. } else {
  198. $options['reply_to'] = $notice_or_user->id;
  199. }
  200. }
  201. if (isset($entry['published']) || isset($entry['updated'])) {
  202. $options['created'] = isset($entry['published'])
  203. ? common_sql_date(strtotime($entry['published'][0]))
  204. : common_sql_date(strtotime($entry['updated'][0]));
  205. }
  206. if (isset($entry['photo']) && common_valid_http_url($entry['photo'])) {
  207. $options['urls'][] = $entry['photo'][0];
  208. } elseif (isset($entry['photo'])) {
  209. common_debug('Linkback got invalid HTTP URL for photo: '._ve($entry['photo']));
  210. }
  211. foreach((array)$entry['category'] as $tag) {
  212. $tag = common_canonical_tag($tag);
  213. if($tag) { $options['tags'][] = $tag; }
  214. }
  215. if($mf2['rels'] && $mf2['rels']['enclosure']) {
  216. foreach($mf2['rels']['enclosure'] as $url) {
  217. $options['urls'][] = $url;
  218. }
  219. }
  220. if($mf2['rels'] && $mf2['rels']['tag']) {
  221. foreach($mf2['rels']['tag'] as $url) {
  222. preg_match('/\/([^\/]+)\/*$/', $url, $match);
  223. $tag = common_canonical_tag($match[1]);
  224. if($tag) { $options['tags'][] = $tag; }
  225. }
  226. }
  227. if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
  228. $options['urls'] = array();
  229. }
  230. return array($content, $options);
  231. }
  232. function linkback_avatar($profile, $url) {
  233. // Ripped from OStatus plugin for now
  234. $temp_filename = tempnam(sys_get_temp_dir(), 'linback_avatar');
  235. try {
  236. $imgData = HTTPClient::quickGet($url);
  237. // Make sure it's at least an image file. ImageFile can do the rest.
  238. if (false === getimagesizefromstring($imgData)) {
  239. return false;
  240. }
  241. file_put_contents($temp_filename, $imgData);
  242. unset($imgData); // No need to carry this in memory.
  243. $imagefile = new ImageFile(null, $temp_filename);
  244. $filename = Avatar::filename($profile->id,
  245. image_type_to_extension($imagefile->type),
  246. null,
  247. common_timestamp());
  248. rename($temp_filename, Avatar::path($filename));
  249. } catch (Exception $e) {
  250. unlink($temp_filename);
  251. throw $e;
  252. }
  253. // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
  254. // keep from accidentally saving images from command-line (queues)
  255. // that can't be read from web server, which causes hard-to-notice
  256. // problems later on:
  257. //
  258. // http://status.net/open-source/issues/2663
  259. chmod(Avatar::path($filename), 0644);
  260. $profile->setOriginal($filename);
  261. }
  262. function linkback_profile($entry, $mf2, $response, $target) {
  263. if(isset($entry['author']) && isset($entry['author'][0]['properties'])) {
  264. $author = $entry['author'][0]['properties'];
  265. } else {
  266. $author = linkback_hcard($mf2, $response->getEffectiveUrl());
  267. }
  268. if(!$author) {
  269. $author = array('name' => $entry['name']);
  270. }
  271. if (!isset($author['url']) || empty($author['url'])) {
  272. $author['url'] = array($response->getEffectiveUrl());
  273. }
  274. $user = User::getKV('uri', $author['url'][0]);
  275. if ($user instanceof User) {
  276. common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
  277. return true;
  278. }
  279. try {
  280. $profile = Profile::fromUri($author['url'][0]);
  281. } catch(UnknownUriException $ex) {
  282. $profile = Profile::getKV('profileurl', $author['url'][0]);
  283. }
  284. // XXX: Is this a good way to create the profile?
  285. if (!$profile instanceof Profile) {
  286. $profile = new Profile();
  287. $profile->profileurl = $author['url'][0];
  288. $profile->fullname = $author['name'][0];
  289. $profile->nickname = isset($author['nickname']) ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
  290. $profile->created = common_sql_now();
  291. $profile->insert();
  292. if($author['photo'] && $author['photo'][0]) {
  293. linkback_avatar($profile, $author['photo'][0]);
  294. }
  295. }
  296. return array($profile, $author);
  297. }
  298. function linkback_save($source, $target, $response, $notice_or_user) {
  299. $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
  300. if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
  301. if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
  302. if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
  303. $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
  304. $mf2 = $mf2->parse();
  305. $entry = linkback_find_entry($mf2, $target);
  306. if(!$entry) {
  307. preg_match('/<title>([^<]+)', $response->getBody(), $match);
  308. $entry = array(
  309. 'content' => array('html' => $response->getBody()),
  310. 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
  311. );
  312. }
  313. if(!$entry['url']) {
  314. $entry['url'] = array($response->getEffectiveUrl());
  315. }
  316. if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
  317. if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
  318. $entry['type'] = linkback_entry_type($entry, $mf2, $target);
  319. list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
  320. list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
  321. if($dupe) {
  322. $orig = clone($dupe);
  323. try {
  324. // Ignore duplicate save error
  325. try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
  326. try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
  327. try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
  328. if (isset($options['reply_to'])) {
  329. $dupe->reply_to = $options['reply_to'];
  330. }
  331. if (isset($options['repeat_of'])) {
  332. $dupe->repeat_of = $options['repeat_of'];
  333. }
  334. if ($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
  335. $parent = Notice::getKV('id', $dupe->repeat_of ?: $dupe->reply_to);
  336. if($parent instanceof Notice) {
  337. // If we changed the reply_to or repeat_of we might live in a new conversation now
  338. $dupe->conversation = $parent->conversation;
  339. }
  340. }
  341. if($dupe->update($orig)) { $saved = $dupe; }
  342. if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
  343. // Delete empty conversation
  344. $emptyConversation = Conversation::getKV('id', $orig->conversation);
  345. $emptyConversation->delete();
  346. }
  347. } catch (Exception $e) {
  348. common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
  349. return false;
  350. }
  351. common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
  352. } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
  353. $act = new Activity();
  354. $act->type = ActivityObject::ACTIVITY;
  355. $act->time = $options['created'] ? strtotime($options['created']) : time();
  356. $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
  357. $act->actor = $profile->asActivityObject();
  358. $act->target = $notice_or_user->asActivityObject();
  359. $act->objects = array(clone($act->target));
  360. // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
  361. // notice's nickname and %3$s is the content of the favorited notice.)
  362. $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
  363. $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
  364. $notice_or_user->getRendered());
  365. if($entry['rsvp']) {
  366. $act->content = $options['rendered'];
  367. }
  368. $act->verb = ActivityVerb::FAVORITE;
  369. if(strtolower($entry['rsvp'][0]) == 'yes') {
  370. $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
  371. } else if(strtolower($entry['rsvp'][0]) == 'no') {
  372. $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
  373. } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
  374. $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
  375. }
  376. $act->id = $source;
  377. $act->link = $entry['url'][0];
  378. $options['source'] = 'linkback';
  379. $options['mentions'] = $options['replies'];
  380. unset($options['reply_to']);
  381. unset($options['repeat_of']);
  382. try {
  383. $saved = Notice::saveActivity($act, $profile, $options);
  384. } catch (Exception $e) {
  385. common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
  386. return false;
  387. }
  388. common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
  389. } else {
  390. // Fallback is to make a notice manually
  391. try {
  392. $saved = Notice::saveNew($profile->id,
  393. $content,
  394. 'linkback',
  395. $options);
  396. } catch (Exception $e) {
  397. common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
  398. return false;
  399. }
  400. common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
  401. }
  402. return $saved->getLocalUrl();
  403. }