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 // Resolve target (https://github.com/converspace/webmention/issues/43)
27 $request = HTTPClient::start();
30 $response = $request->head($target);
31 } catch(Exception $ex) {
36 $notice = Notice::fromUri($response->getEffectiveUrl());
37 } catch(UnknownUriException $ex) {
38 preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
39 $notice = Notice::getKV('id', $match[1]);
42 if($notice instanceof Notice && $notice->isLocal()) {
45 $user = User::getKV('uri', $response->getEffectiveUrl());
47 preg_match('/\/user\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
48 $user = User::getKV('id', $match[1]);
51 preg_match('/\/([^\/\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
52 if(linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl())) {
53 $user = User::getKV('nickname', $match[1]);
56 if($user instanceof User) {
64 // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
65 function linkback_find_entry($mf2, $target) {
66 if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
67 $mf2['items'] = $mf2['items'][0]['children'];
70 $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
72 foreach ($entries as $entry) {
73 foreach ((array)$entry['properties'] as $key => $values) {
74 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
75 return $entry['properties'];
78 // check included h-* formats and their links
79 foreach ($values as $obj) {
80 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
81 isset($obj['properties']) && isset($obj['properties']['url']) &&
82 count(array_filter($obj['properties']['url'],
83 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
85 return $entry['properties'];
89 // check content for the link
90 if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
91 return $entry['properties'];
92 // check summary for the link
93 } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
94 return $entry['properties'];
99 // Default to first one
100 if(count($entries) > 0) {
101 return $entries[0]['properties'];
107 function linkback_entry_type($entry, $mf2, $target) {
108 if(!$entry) { return 'mention'; }
110 if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
111 foreach($mf2['rels']['in-reply-to'] as $url) {
112 if(linkback_lenient_target_match($url, $target)) {
119 'in-reply-to' => 'reply',
120 'repost-of' => 'repost',
125 foreach((array)$entry as $key => $values) {
126 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
127 if($classes[$key]) { return $classes[$key]; }
130 foreach ($values as $obj) {
131 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
132 isset($obj['properties']) && isset($obj['properties']['url']) &&
133 count(array_filter($obj['properties']['url'],
134 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
136 if($classes[$key]) { return $classes[$key]; }
144 function linkback_is_dupe($key, $url) {
145 $dupe = Notice::getKV($key, $url);
146 if ($dupe instanceof Notice) {
154 function linkback_hcard($mf2, $url) {
155 if(empty($mf2['items'])) {
160 foreach($mf2['items'] as $item) {
161 if(!in_array('h-card', $item['type'])) {
165 // We found a match, return it immediately
166 if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
167 return $item['properties'];
169 // Let's keep all the hcards for later, to return one of them at least
170 $hcards[] = $item['properties'];
174 // No match immediately for the url we expected, but there were h-cards found
175 if (count($hcards) > 0) {
182 function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
183 $content = $entry['content'] ? $entry['content'][0]['html'] :
184 ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
186 $rendered = common_purify($content);
188 if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
189 $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
190 $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
193 $content = common_strip_html($rendered);
194 $shortened = common_shorten_links($content);
195 if(Notice::contentTooLong($shortened)) {
196 $content = substr($content,
198 Notice::maxContent() - (mb_strlen($source) + 2));
199 $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
200 $content .= ' ' . $source;
203 $options = array('is_local' => Notice::REMOTE,
204 'url' => $entry['url'][0],
206 'rendered' => $rendered,
207 'replies' => array(),
209 'peopletags' => array(),
213 if($notice_or_user instanceof User) {
214 $options['replies'][] = $notice_or_user->getUri();
216 if($entry['type'] == 'repost') {
217 $options['repeat_of'] = $notice_or_user->id;
219 $options['reply_to'] = $notice_or_user->id;
223 if($entry['published'] || $entry['updated']) {
224 $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
227 if($entry['photo']) {
228 $options['urls'][] = $entry['photo'][0];
231 foreach((array)$entry['category'] as $tag) {
232 $tag = common_canonical_tag($tag);
233 if($tag) { $options['tags'][] = $tag; }
237 if($mf2['rels'] && $mf2['rels']['enclosure']) {
238 foreach($mf2['rels']['enclosure'] as $url) {
239 $options['urls'][] = $url;
243 if($mf2['rels'] && $mf2['rels']['tag']) {
244 foreach($mf2['rels']['tag'] as $url) {
245 preg_match('/\/([^\/]+)\/*$/', $url, $match);
246 $tag = common_canonical_tag($match[1]);
247 if($tag) { $options['tags'][] = $tag; }
251 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
252 $options['urls'] = array();
255 return array($content, $options);
258 function linkback_profile($entry, $mf2, $response, $target) {
259 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
260 $author = $entry['properties']['author'][0]['properties'];
262 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
266 $author = array('name' => array($entry['name']));
269 if(!$author['url']) {
270 $author['url'] = array($response->getEffectiveUrl());
273 $user = User::getKV('uri', $author['url'][0]);
274 if ($user instanceof User) {
275 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
280 $profile = Profile::fromUri($author['url'][0]);
281 } catch(UnknownUriException $ex) {}
283 if(!($profile instanceof Profile)) {
284 $profile = Profile::getKV('profileurl', $author['url'][0]);
287 if(!($profile instanceof Profile)) {
288 $profile = new Profile();
289 $profile->profileurl = $author['url'][0];
290 $profile->fullname = $author['name'][0];
291 $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
292 $profile->created = common_sql_now();
296 return array($profile, $author);
299 function linkback_save($source, $target, $response, $notice_or_user) {
300 $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
301 if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
302 if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
303 if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
305 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
306 $mf2 = $mf2->parse();
308 $entry = linkback_find_entry($mf2, $target);
310 preg_match('/<title>([^<]+)', $response->getBody(), $match);
312 'content' => array('html' => $response->getBody()),
313 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
318 $entry['url'] = array($response->getEffectiveUrl());
321 if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
322 if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
324 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
325 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
326 list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
329 $orig = clone($dupe);
332 // Ignore duplicate save error
333 try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
334 try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
335 try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
337 if($options['reply_to']) { $dupe->reply_to = $options['reply_to']; }
338 if($options['repost_of']) { $dupe->repost_of = $options['repost_of']; }
339 if($dupe->update($orig)) { $saved = $dupe; }
340 } catch (Exception $e) {
341 common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
344 common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
345 } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
346 $act = new Activity();
347 $act->type = ActivityObject::ACTIVITY;
348 $act->time = $options['created'] ? strtotime($options['created']) : time();
349 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
350 $act->actor = $profile->asActivityObject();
351 $act->target = $notice_or_user->asActivityObject();
352 $act->objects = array(clone($act->target));
354 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
355 // notice's nickname and %3$s is the content of the favorited notice.)
356 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
357 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
358 $notice_or_user->rendered ?: $notice_or_user->content);
360 $act->content = $options['rendered'];
363 $act->verb = ActivityVerb::FAVORITE;
364 if(strtolower($entry['rsvp'][0]) == 'yes') {
365 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
366 } else if(strtolower($entry['rsvp'][0]) == 'no') {
367 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
368 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
369 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
373 $act->link = $entry['url'][0];
375 $options['source'] = 'linkback';
376 $options['mentions'] = $options['replies'];
377 unset($options['reply_to']);
378 unset($options['repeat_of']);
381 $saved = Notice::saveActivity($act, $profile, $options);
382 } catch (Exception $e) {
383 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
386 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
388 // Fallback is to make a notice manually
390 $saved = Notice::saveNew($profile->id,
394 } catch (Exception $e) {
395 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
398 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
401 return $saved->getLocalUrl();