3 function linkback_lenient_target_match($body, $target) {
4 return strpos(''.$body, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', preg_replace('/\/+$/', '', preg_replace( '/#.*/', '', $target))));
7 function linkback_get_source($source, $target) {
8 $request = HTTPClient::start();
11 $response = $request->get($source);
12 } catch(Exception $ex) {
16 $body = htmlspecialchars_decode($response->getBody());
17 // We're slightly more lenient in our link detection than the spec requires
18 if(!linkback_lenient_target_match($body, $target)) {
25 function linkback_get_target($target) {
26 // TODO: linkback to a user should work for attention
27 // TODO: ignore remote notices and users
28 // Resolve target (https://github.com/converspace/webmention/issues/43)
29 $request = HTTPClient::start();
32 $response = $request->head($target);
33 } catch(Exception $ex) {
38 return Notice::fromUri($response->getEffectiveUrl());
39 } catch(UnknownUriException $ex) {
40 preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
41 return Notice::getKV('id', $match[1]);
47 // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
48 function linkback_find_entry($mf2, $target) {
49 if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
50 $mf2['items'] = $mf2['items'][0]['children'];
53 $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
55 foreach ($entries as $entry) {
56 foreach ((array)$entry['properties'] as $key => $values) {
57 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
58 return $entry['properties'];
61 // check included h-* formats and their links
62 foreach ($values as $obj) {
63 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
64 isset($obj['properties']) && isset($obj['properties']['url']) &&
65 count(array_filter($obj['properties']['url'],
66 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
68 return $entry['properties'];
72 // check content for the link
73 if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
74 return $entry['properties'];
75 // check summary for the link
76 } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
77 return $entry['properties'];
82 // Default to first one
83 if(count($entries) > 0) {
84 return $entries[0]['properties'];
90 function linkback_entry_type($entry, $mf2, $target) {
91 if(!$entry) { return 'mention'; }
93 if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
94 foreach($mf2['rels']['in-reply-to'] as $url) {
95 if(linkback_lenient_target_match($url, $target)) {
102 'in-reply-to' => 'reply',
103 'repost-of' => 'repost',
108 foreach((array)$entry as $key => $values) {
109 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
110 if($classes[$key]) { return $classes[$key]; }
113 foreach ($values as $obj) {
114 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
115 isset($obj['properties']) && isset($obj['properties']['url']) &&
116 count(array_filter($obj['properties']['url'],
117 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
119 if($classes[$key]) { return $classes[$key]; }
127 function linkback_is_dupe($key, $url) {
128 $dupe = Notice::getKV('uri', $url);
129 if ($dupe instanceof Notice) {
130 common_log(LOG_INFO, "Linkback: ignoring duplicate post: $url");
138 function linkback_hcard($mf2, $url) {
139 if(empty($mf2['items'])) {
144 foreach($mf2['items'] as $item) {
145 if(!in_array('h-card', $item['type'])) {
149 // We found a match, return it immediately
150 if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
151 return $item['properties'];
153 // Let's keep all the hcards for later, to return one of them at least
154 $hcards[] = $item['properties'];
158 // No match immediately for the url we expected, but there were h-cards found
159 if (count($hcards) > 0) {
166 function linkback_notice($source, $notice, $entry, $author, $mf2) {
167 $content = $entry['content'] ? $entry['content'][0]['html'] :
168 ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
170 $rendered = common_purify($content);
172 if($entry['type'] == 'mention') {
173 $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
174 $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
177 $content = common_strip_html($rendered);
178 $shortened = common_shorten_links($content);
179 if(Notice::contentTooLong($shortened)) {
180 $content = substr($content,
182 Notice::maxContent() - (mb_strlen($source) + 2));
183 $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
184 $content .= ' ' . $source;
187 $options = array('is_local' => Notice::REMOTE,
188 'url' => $entry['url'][0],
190 'rendered' => $rendered,
191 'replies' => array(),
193 'peopletags' => array(),
197 // TODO: when mentioning a user and not a post, neither of these but set replies above
198 if($entry['type'] == 'repost') {
199 $options['repeat_of'] = $notice->id;
201 $options['reply_to'] = $notice->id;
204 if($entry['published'] || $entry['updated']) {
205 $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
208 if($entry['photo']) {
209 $options['urls'][] = $entry['photo'][0];
212 foreach((array)$entry['category'] as $tag) {
213 $tag = common_canonical_tag($tag);
214 if($tag) { $options['tags'][] = $tag; }
218 if($mf2['rels'] && $mf2['rels']['enclosure']) {
219 foreach($mf2['rels']['enclosure'] as $url) {
220 $options['urls'][] = $url;
224 if($mf2['rels'] && $mf2['rels']['tag']) {
225 foreach($mf2['rels']['tag'] as $url) {
226 preg_match('/\/([^\/]+)\/*$/', $url, $match);
227 $tag = common_canonical_tag($match[1]);
228 if($tag) { $options['tags'][] = $tag; }
232 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
233 $options['urls'] = array();
236 return array($content, $options);
239 function linkback_profile($entry, $mf2, $response, $target) {
240 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
241 $author = $entry['properties']['author'][0]['properties'];
243 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
247 $author = array('name' => array($entry['name']));
250 if(!$author['url']) {
251 $author['url'] = array($response->getEffectiveUrl());
254 $user = User::getKV('uri', $author['url'][0]);
255 if ($user instanceof User) {
256 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
260 $profile = Profile::fromUri($author['url'][0]);
261 if(!($profile instanceof Profile)) {
262 $profile = Profile::getKV('profileurl', $author['url'][0]);
265 if(!($profile instanceof Profile)) {
266 $profile = new Profile();
267 $profile->profileurl = $author['url'][0];
268 $profile->fullname = $author['name'][0];
269 $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
270 $profile->created = common_sql_now();
274 return array($profile, $author);
277 function linkback_save($source, $target, $response, $notice) {
278 if($dupe = linkback_is_dupe('uri', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
279 if($dupe = linkback_is_dupe('url', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
280 if($dupe = linkback_is_dupe('uri', $source)) { return $dupe->getLocalUrl(); }
281 if($dupe = linkback_is_dupe('url', $source)) { return $dupe->getLocalUrl(); }
283 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
284 $mf2 = $mf2->parse();
286 $entry = linkback_find_entry($mf2, $target);
288 preg_match('/<title>([^<]+)', $response->getBody(), $match);
290 'content' => array('html' => $response->getBody()),
291 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
296 $entry['url'] = array($response->getEffectiveUrl());
299 if($dupe = linkback_is_dupe('uri', $entry['url'][0])) { return $dupe->getLocalUrl(); }
300 if($dupe = linkback_is_dupe('url', $entry['url'][0])) { return $dupe->getLocalUrl(); }
302 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
303 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
304 list($content, $options) = linkback_notice($source, $notice, $entry, $author, $mf2);
306 if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
307 $act = new Activity();
308 $act->type = ActivityObject::ACTIVITY;
309 $act->time = $options['created'] ? strtotime($options['created']) : time();
310 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
311 $act->actor = $profile->asActivityObject();
312 $act->target = $notice->asActivityObject();
313 $act->objects = array(clone($act->target));
315 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
316 // notice's nickname and %3$s is the content of the favorited notice.)
317 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
318 $profile->getNickname(), $notice->getProfile()->getNickname(),
319 $notice->rendered ?: $notice->content);
321 $act->content = $options['rendered'];
324 $act->verb = ActivityVerb::FAVORITE;
325 if(strtolower($entry['rsvp'][0]) == 'yes') {
326 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
327 } else if(strtolower($entry['rsvp'][0]) == 'no') {
328 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
329 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
330 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
334 $act->link = $entry['url'][0];
336 $options['source'] = 'linkback';
337 $options['mentions'] = $options['replies'];
338 unset($options['reply_to']);
339 unset($options['repeat_of']);
342 $saved = Notice::saveActivity($act, $profile, $options);
343 } catch (Exception $e) {
344 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
347 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
349 // Fallback is to make a notice manually
351 $saved = Notice::saveNew($profile->id,
355 } catch (Exception $e) {
356 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
359 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
362 return $saved->getLocalUrl();