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 // Resolve target (https://github.com/converspace/webmention/issues/43)
28 $request = HTTPClient::start();
31 $response = $request->head($target);
32 } catch(Exception $ex) {
37 $notice = Notice::fromUri($response->getEffectiveUrl());
38 } catch(UnknownUriException $ex) {
39 preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
40 $notice = Notice::getKV('id', $match[1]);
43 if($notice instanceof Notice && $notice->isLocal()) {
50 // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
51 function linkback_find_entry($mf2, $target) {
52 if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
53 $mf2['items'] = $mf2['items'][0]['children'];
56 $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
58 foreach ($entries as $entry) {
59 foreach ((array)$entry['properties'] as $key => $values) {
60 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
61 return $entry['properties'];
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); })) > 0
71 return $entry['properties'];
75 // check content for the link
76 if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
77 return $entry['properties'];
78 // check summary for the link
79 } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
80 return $entry['properties'];
85 // Default to first one
86 if(count($entries) > 0) {
87 return $entries[0]['properties'];
93 function linkback_entry_type($entry, $mf2, $target) {
94 if(!$entry) { return 'mention'; }
96 if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
97 foreach($mf2['rels']['in-reply-to'] as $url) {
98 if(linkback_lenient_target_match($url, $target)) {
105 'in-reply-to' => 'reply',
106 'repost-of' => 'repost',
111 foreach((array)$entry as $key => $values) {
112 if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
113 if($classes[$key]) { return $classes[$key]; }
116 foreach ($values as $obj) {
117 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
118 isset($obj['properties']) && isset($obj['properties']['url']) &&
119 count(array_filter($obj['properties']['url'],
120 function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
122 if($classes[$key]) { return $classes[$key]; }
130 function linkback_is_dupe($key, $url) {
131 $dupe = Notice::getKV('uri', $url);
132 if ($dupe instanceof Notice) {
133 common_log(LOG_INFO, "Linkback: ignoring duplicate post: $url");
141 function linkback_hcard($mf2, $url) {
142 if(empty($mf2['items'])) {
147 foreach($mf2['items'] as $item) {
148 if(!in_array('h-card', $item['type'])) {
152 // We found a match, return it immediately
153 if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
154 return $item['properties'];
156 // Let's keep all the hcards for later, to return one of them at least
157 $hcards[] = $item['properties'];
161 // No match immediately for the url we expected, but there were h-cards found
162 if (count($hcards) > 0) {
169 function linkback_notice($source, $notice, $entry, $author, $mf2) {
170 $content = $entry['content'] ? $entry['content'][0]['html'] :
171 ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
173 $rendered = common_purify($content);
175 if($entry['type'] == 'mention') {
176 $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
177 $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
180 $content = common_strip_html($rendered);
181 $shortened = common_shorten_links($content);
182 if(Notice::contentTooLong($shortened)) {
183 $content = substr($content,
185 Notice::maxContent() - (mb_strlen($source) + 2));
186 $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
187 $content .= ' ' . $source;
190 $options = array('is_local' => Notice::REMOTE,
191 'url' => $entry['url'][0],
193 'rendered' => $rendered,
194 'replies' => array(),
196 'peopletags' => array(),
200 // TODO: when mentioning a user and not a post, neither of these but set replies above
201 if($entry['type'] == 'repost') {
202 $options['repeat_of'] = $notice->id;
204 $options['reply_to'] = $notice->id;
207 if($entry['published'] || $entry['updated']) {
208 $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
211 if($entry['photo']) {
212 $options['urls'][] = $entry['photo'][0];
215 foreach((array)$entry['category'] as $tag) {
216 $tag = common_canonical_tag($tag);
217 if($tag) { $options['tags'][] = $tag; }
221 if($mf2['rels'] && $mf2['rels']['enclosure']) {
222 foreach($mf2['rels']['enclosure'] as $url) {
223 $options['urls'][] = $url;
227 if($mf2['rels'] && $mf2['rels']['tag']) {
228 foreach($mf2['rels']['tag'] as $url) {
229 preg_match('/\/([^\/]+)\/*$/', $url, $match);
230 $tag = common_canonical_tag($match[1]);
231 if($tag) { $options['tags'][] = $tag; }
235 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
236 $options['urls'] = array();
239 return array($content, $options);
242 function linkback_profile($entry, $mf2, $response, $target) {
243 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
244 $author = $entry['properties']['author'][0]['properties'];
246 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
250 $author = array('name' => array($entry['name']));
253 if(!$author['url']) {
254 $author['url'] = array($response->getEffectiveUrl());
257 $user = User::getKV('uri', $author['url'][0]);
258 if ($user instanceof User) {
259 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
263 $profile = Profile::fromUri($author['url'][0]);
264 if(!($profile instanceof Profile)) {
265 $profile = Profile::getKV('profileurl', $author['url'][0]);
268 if(!($profile instanceof Profile)) {
269 $profile = new Profile();
270 $profile->profileurl = $author['url'][0];
271 $profile->fullname = $author['name'][0];
272 $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
273 $profile->created = common_sql_now();
277 return array($profile, $author);
280 function linkback_save($source, $target, $response, $notice) {
281 if($dupe = linkback_is_dupe('uri', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
282 if($dupe = linkback_is_dupe('url', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
283 if($dupe = linkback_is_dupe('uri', $source)) { return $dupe->getLocalUrl(); }
284 if($dupe = linkback_is_dupe('url', $source)) { return $dupe->getLocalUrl(); }
286 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
287 $mf2 = $mf2->parse();
289 $entry = linkback_find_entry($mf2, $target);
291 preg_match('/<title>([^<]+)', $response->getBody(), $match);
293 'content' => array('html' => $response->getBody()),
294 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
299 $entry['url'] = array($response->getEffectiveUrl());
302 if($dupe = linkback_is_dupe('uri', $entry['url'][0])) { return $dupe->getLocalUrl(); }
303 if($dupe = linkback_is_dupe('url', $entry['url'][0])) { return $dupe->getLocalUrl(); }
305 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
306 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
307 list($content, $options) = linkback_notice($source, $notice, $entry, $author, $mf2);
309 if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
310 $act = new Activity();
311 $act->type = ActivityObject::ACTIVITY;
312 $act->time = $options['created'] ? strtotime($options['created']) : time();
313 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
314 $act->actor = $profile->asActivityObject();
315 $act->target = $notice->asActivityObject();
316 $act->objects = array(clone($act->target));
318 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
319 // notice's nickname and %3$s is the content of the favorited notice.)
320 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
321 $profile->getNickname(), $notice->getProfile()->getNickname(),
322 $notice->rendered ?: $notice->content);
324 $act->content = $options['rendered'];
327 $act->verb = ActivityVerb::FAVORITE;
328 if(strtolower($entry['rsvp'][0]) == 'yes') {
329 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
330 } else if(strtolower($entry['rsvp'][0]) == 'no') {
331 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
332 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
333 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
337 $act->link = $entry['url'][0];
339 $options['source'] = 'linkback';
340 $options['mentions'] = $options['replies'];
341 unset($options['reply_to']);
342 unset($options['repeat_of']);
345 $saved = Notice::saveActivity($act, $profile, $options);
346 } catch (Exception $e) {
347 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
350 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
352 // Fallback is to make a notice manually
354 $saved = Notice::saveNew($profile->id,
358 } catch (Exception $e) {
359 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
362 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
365 return $saved->getLocalUrl();