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('uri', $url);
146 if ($dupe instanceof Notice) {
147 common_log(LOG_INFO, "Linkback: ignoring duplicate post: $url");
155 function linkback_hcard($mf2, $url) {
156 if(empty($mf2['items'])) {
161 foreach($mf2['items'] as $item) {
162 if(!in_array('h-card', $item['type'])) {
166 // We found a match, return it immediately
167 if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
168 return $item['properties'];
170 // Let's keep all the hcards for later, to return one of them at least
171 $hcards[] = $item['properties'];
175 // No match immediately for the url we expected, but there were h-cards found
176 if (count($hcards) > 0) {
183 function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
184 $content = $entry['content'] ? $entry['content'][0]['html'] :
185 ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
187 $rendered = common_purify($content);
189 if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
190 $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
191 $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
194 $content = common_strip_html($rendered);
195 $shortened = common_shorten_links($content);
196 if(Notice::contentTooLong($shortened)) {
197 $content = substr($content,
199 Notice::maxContent() - (mb_strlen($source) + 2));
200 $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
201 $content .= ' ' . $source;
204 $options = array('is_local' => Notice::REMOTE,
205 'url' => $entry['url'][0],
207 'rendered' => $rendered,
208 'replies' => array(),
210 'peopletags' => array(),
214 if($notice_or_user instanceof User) {
215 $options['replies'][] = $notice_or_user->getUri();
217 if($entry['type'] == 'repost') {
218 $options['repeat_of'] = $notice_or_user->id;
220 $options['reply_to'] = $notice_or_user->id;
224 if($entry['published'] || $entry['updated']) {
225 $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
228 if($entry['photo']) {
229 $options['urls'][] = $entry['photo'][0];
232 foreach((array)$entry['category'] as $tag) {
233 $tag = common_canonical_tag($tag);
234 if($tag) { $options['tags'][] = $tag; }
238 if($mf2['rels'] && $mf2['rels']['enclosure']) {
239 foreach($mf2['rels']['enclosure'] as $url) {
240 $options['urls'][] = $url;
244 if($mf2['rels'] && $mf2['rels']['tag']) {
245 foreach($mf2['rels']['tag'] as $url) {
246 preg_match('/\/([^\/]+)\/*$/', $url, $match);
247 $tag = common_canonical_tag($match[1]);
248 if($tag) { $options['tags'][] = $tag; }
252 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
253 $options['urls'] = array();
256 return array($content, $options);
259 function linkback_profile($entry, $mf2, $response, $target) {
260 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
261 $author = $entry['properties']['author'][0]['properties'];
263 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
267 $author = array('name' => array($entry['name']));
270 if(!$author['url']) {
271 $author['url'] = array($response->getEffectiveUrl());
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");
280 $profile = Profile::fromUri($author['url'][0]);
281 if(!($profile instanceof Profile)) {
282 $profile = Profile::getKV('profileurl', $author['url'][0]);
285 if(!($profile instanceof Profile)) {
286 $profile = new Profile();
287 $profile->profileurl = $author['url'][0];
288 $profile->fullname = $author['name'][0];
289 $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
290 $profile->created = common_sql_now();
294 return array($profile, $author);
297 function linkback_save($source, $target, $response, $notice_or_user) {
298 if($dupe = linkback_is_dupe('uri', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
299 if($dupe = linkback_is_dupe('url', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
300 if($dupe = linkback_is_dupe('uri', $source)) { return $dupe->getLocalUrl(); }
301 if($dupe = linkback_is_dupe('url', $source)) { return $dupe->getLocalUrl(); }
303 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
304 $mf2 = $mf2->parse();
306 $entry = linkback_find_entry($mf2, $target);
308 preg_match('/<title>([^<]+)', $response->getBody(), $match);
310 'content' => array('html' => $response->getBody()),
311 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
316 $entry['url'] = array($response->getEffectiveUrl());
319 if($dupe = linkback_is_dupe('uri', $entry['url'][0])) { return $dupe->getLocalUrl(); }
320 if($dupe = linkback_is_dupe('url', $entry['url'][0])) { return $dupe->getLocalUrl(); }
322 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
323 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
324 list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
326 if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
327 $act = new Activity();
328 $act->type = ActivityObject::ACTIVITY;
329 $act->time = $options['created'] ? strtotime($options['created']) : time();
330 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
331 $act->actor = $profile->asActivityObject();
332 $act->target = $notice_or_user->asActivityObject();
333 $act->objects = array(clone($act->target));
335 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
336 // notice's nickname and %3$s is the content of the favorited notice.)
337 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
338 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
339 $notice_or_user->rendered ?: $notice_or_user->content);
341 $act->content = $options['rendered'];
344 $act->verb = ActivityVerb::FAVORITE;
345 if(strtolower($entry['rsvp'][0]) == 'yes') {
346 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
347 } else if(strtolower($entry['rsvp'][0]) == 'no') {
348 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
349 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
350 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
354 $act->link = $entry['url'][0];
356 $options['source'] = 'linkback';
357 $options['mentions'] = $options['replies'];
358 unset($options['reply_to']);
359 unset($options['repeat_of']);
362 $saved = Notice::saveActivity($act, $profile, $options);
363 } catch (Exception $e) {
364 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
367 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
369 // Fallback is to make a notice manually
371 $saved = Notice::saveNew($profile->id,
375 } catch (Exception $e) {
376 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
379 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
382 return $saved->getLocalUrl();