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 // Check if we are pinging ourselves and ignore
9 $localprefix = common_config('site', 'server') . '/' . common_config('site', 'path');
10 if(linkback_lenient_target_match($source, $localprefix)) {
11 common_debug('Ignoring self ping from ' . $source . ' to ' . $target);
15 $request = HTTPClient::start();
18 $response = $request->get($source);
19 } catch(Exception $ex) {
23 $body = htmlspecialchars_decode($response->getBody());
24 // We're slightly more lenient in our link detection than the spec requires
25 if(!linkback_lenient_target_match($body, $target)) {
32 function linkback_get_target($target) {
33 // Resolve target (https://github.com/converspace/webmention/issues/43)
34 $request = HTTPClient::start();
37 $response = $request->head($target);
38 } catch(Exception $ex) {
43 $notice = Notice::fromUri($response->getEffectiveUrl());
44 } catch(UnknownUriException $ex) {
45 preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
46 $notice = Notice::getKV('id', $match[1]);
49 if($notice instanceof Notice && $notice->isLocal()) {
52 $user = User::getKV('uri', $response->getEffectiveUrl());
54 preg_match('/\/user\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
55 $user = User::getKV('id', $match[1]);
58 preg_match('/\/([^\/\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
59 if(linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl())) {
60 $user = User::getKV('nickname', $match[1]);
63 if($user instanceof User) {
71 function linkback_is_contained_in($entry, $target) {
72 foreach ((array)$entry['properties'] as $key => $values) {
73 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
74 return $entry['properties'];
77 // check included h-* formats and their links
78 foreach ($values as $obj) {
79 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
80 isset($obj['properties']) && isset($obj['properties']['url']) &&
81 count(array_filter($obj['properties']['url'],
82 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
84 return $entry['properties'];
88 // check content for the link
89 if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
90 return $entry['properties'];
91 // check summary for the link
92 } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
93 return $entry['properties'];
97 foreach((array)$entry['children'] as $mf2) {
98 if(linkback_is_contained_in($mf2, $target)) {
99 return $entry['properties'];
106 // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
107 function linkback_find_entry($mf2, $target) {
108 if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
109 $mf2['items'] = $mf2['items'][0]['children'];
112 $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
114 foreach ($entries as $entry) {
115 if($prop = linkback_is_contained_in($entry, $target)) {
120 // Default to first one
121 if(count($entries) > 0) {
122 return $entries[0]['properties'];
128 function linkback_entry_type($entry, $mf2, $target) {
129 if(!$entry) { return 'mention'; }
131 if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
132 foreach($mf2['rels']['in-reply-to'] as $url) {
133 if(linkback_lenient_target_match($url, $target)) {
140 'in-reply-to' => 'reply',
141 'repost-of' => 'repost',
146 foreach((array)$entry as $key => $values) {
147 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
148 if($classes[$key]) { return $classes[$key]; }
151 foreach ($values as $obj) {
152 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
153 isset($obj['properties']) && isset($obj['properties']['url']) &&
154 count(array_filter($obj['properties']['url'],
155 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
157 if($classes[$key]) { return $classes[$key]; }
165 function linkback_is_dupe($key, $url) {
166 $dupe = Notice::getKV($key, $url);
167 if ($dupe instanceof Notice) {
175 function linkback_hcard($mf2, $url) {
176 if(empty($mf2['items'])) {
181 foreach($mf2['items'] as $item) {
182 if(!in_array('h-card', $item['type'])) {
186 // We found a match, return it immediately
187 if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
188 return $item['properties'];
191 // Let's keep all the hcards for later, to return one of them at least
192 $hcards[] = $item['properties'];
195 // No match immediately for the url we expected, but there were h-cards found
196 if (count($hcards) > 0) {
203 function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
204 $content = $entry['content'] ? $entry['content'][0]['html'] :
205 ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
207 $rendered = common_purify($content);
209 if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
210 $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
211 $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
214 $content = common_strip_html($rendered);
215 $shortened = common_shorten_links($content);
216 if(Notice::contentTooLong($shortened)) {
217 $content = substr($content,
219 Notice::maxContent() - (mb_strlen($source) + 2));
220 $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
221 $content .= ' ' . $source;
224 $options = array('is_local' => Notice::REMOTE,
225 'url' => $entry['url'][0],
226 'uri' => $entry['url'][0],
227 'rendered' => $rendered,
228 'replies' => array(),
230 'peopletags' => array(),
234 if($notice_or_user instanceof User) {
235 $options['replies'][] = $notice_or_user->getUri();
237 if($entry['type'] == 'repost') {
238 $options['repeat_of'] = $notice_or_user->id;
240 $options['reply_to'] = $notice_or_user->id;
244 if($entry['published'] || $entry['updated']) {
245 $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
248 if($entry['photo']) {
249 $options['urls'][] = $entry['photo'][0];
252 foreach((array)$entry['category'] as $tag) {
253 $tag = common_canonical_tag($tag);
254 if($tag) { $options['tags'][] = $tag; }
258 if($mf2['rels'] && $mf2['rels']['enclosure']) {
259 foreach($mf2['rels']['enclosure'] as $url) {
260 $options['urls'][] = $url;
264 if($mf2['rels'] && $mf2['rels']['tag']) {
265 foreach($mf2['rels']['tag'] as $url) {
266 preg_match('/\/([^\/]+)\/*$/', $url, $match);
267 $tag = common_canonical_tag($match[1]);
268 if($tag) { $options['tags'][] = $tag; }
272 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
273 $options['urls'] = array();
276 return array($content, $options);
279 function linkback_profile($entry, $mf2, $response, $target) {
280 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
281 $author = $entry['properties']['author'][0]['properties'];
283 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
287 $author = array('name' => $entry['name']);
290 if(!$author['url']) {
291 $author['url'] = array($response->getEffectiveUrl());
294 $user = User::getKV('uri', $author['url'][0]);
295 if ($user instanceof User) {
296 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
301 $profile = Profile::fromUri($author['url'][0]);
302 } catch(UnknownUriException $ex) {}
304 if(!($profile instanceof Profile)) {
305 $profile = Profile::getKV('profileurl', $author['url'][0]);
308 if(!($profile instanceof Profile)) {
309 $profile = new Profile();
310 $profile->profileurl = $author['url'][0];
311 $profile->fullname = $author['name'][0];
312 $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
313 $profile->created = common_sql_now();
317 return array($profile, $author);
320 function linkback_save($source, $target, $response, $notice_or_user) {
321 $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
322 if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
323 if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
324 if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
326 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
327 $mf2 = $mf2->parse();
329 $entry = linkback_find_entry($mf2, $target);
331 preg_match('/<title>([^<]+)', $response->getBody(), $match);
333 'content' => array('html' => $response->getBody()),
334 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
339 $entry['url'] = array($response->getEffectiveUrl());
342 if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
343 if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
345 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
346 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
347 list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
350 $orig = clone($dupe);
353 // Ignore duplicate save error
354 try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
355 try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
356 try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
358 if($options['reply_to']) { $dupe->reply_to = $options['reply_to']; }
359 if($options['repeat_of']) { $dupe->repeat_of = $options['repeat_of']; }
360 if($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
361 $parent = Notice::getKV('id', $dupe->repost_of ? $dupe->repost_of : $dupe->reply_to);
362 if($parent instanceof Notice) {
363 // If we changed the reply_to or repeat_of we might live in a new conversation now
364 $dupe->conversation = $parent->conversation;
367 if($dupe->update($orig)) { $saved = $dupe; }
368 if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
369 // Delete empty conversation
370 $emptyConversation = Conversation::getKV('id', $orig->conversation);
371 $emptyConversation->delete();
373 } catch (Exception $e) {
374 common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
377 common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
378 } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
379 $act = new Activity();
380 $act->type = ActivityObject::ACTIVITY;
381 $act->time = $options['created'] ? strtotime($options['created']) : time();
382 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
383 $act->actor = $profile->asActivityObject();
384 $act->target = $notice_or_user->asActivityObject();
385 $act->objects = array(clone($act->target));
387 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
388 // notice's nickname and %3$s is the content of the favorited notice.)
389 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
390 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
391 $notice_or_user->getRendered());
393 $act->content = $options['rendered'];
396 $act->verb = ActivityVerb::FAVORITE;
397 if(strtolower($entry['rsvp'][0]) == 'yes') {
398 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
399 } else if(strtolower($entry['rsvp'][0]) == 'no') {
400 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
401 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
402 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
406 $act->link = $entry['url'][0];
408 $options['source'] = 'linkback';
409 $options['mentions'] = $options['replies'];
410 unset($options['reply_to']);
411 unset($options['repeat_of']);
414 $saved = Notice::saveActivity($act, $profile, $options);
415 } catch (Exception $e) {
416 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
419 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
421 // Fallback is to make a notice manually
423 $saved = Notice::saveNew($profile->id,
427 } catch (Exception $e) {
428 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
431 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
434 return $saved->getLocalUrl();