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 = isset($entry['content']) ? $entry['content'][0]['html'] :
205 (isset($entry['summary']) ? $entry['summary'][0] : $entry['name'][0]);
207 $rendered = common_purify($content);
209 if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
210 $name = isset($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 (isset($entry['published']) || isset($entry['updated'])) {
245 $options['created'] = isset($entry['published'])
246 ? common_sql_date($entry['published'][0])
247 : common_sql_date($entry['updated'][0]);
250 if (isset($entry['photo']) && common_valid_http_url($entry['photo'])) {
251 $options['urls'][] = $entry['photo'][0];
252 } elseif (isset($entry['photo'])) {
253 common_debug('Linkback got invalid HTTP URL for photo: '._ve($entry['photo']));
256 foreach((array)$entry['category'] as $tag) {
257 $tag = common_canonical_tag($tag);
258 if($tag) { $options['tags'][] = $tag; }
262 if($mf2['rels'] && $mf2['rels']['enclosure']) {
263 foreach($mf2['rels']['enclosure'] as $url) {
264 $options['urls'][] = $url;
268 if($mf2['rels'] && $mf2['rels']['tag']) {
269 foreach($mf2['rels']['tag'] as $url) {
270 preg_match('/\/([^\/]+)\/*$/', $url, $match);
271 $tag = common_canonical_tag($match[1]);
272 if($tag) { $options['tags'][] = $tag; }
276 if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
277 $options['urls'] = array();
280 return array($content, $options);
283 function linkback_profile($entry, $mf2, $response, $target) {
284 if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
285 $author = $entry['properties']['author'][0]['properties'];
287 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
291 $author = array('name' => $entry['name']);
294 if (!isset($author['url']) || empty($author['url'])) {
295 $author['url'] = array($response->getEffectiveUrl());
298 $user = User::getKV('uri', $author['url'][0]);
299 if ($user instanceof User) {
300 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
305 $profile = Profile::fromUri($author['url'][0]);
306 } catch(UnknownUriException $ex) {
307 $profile = Profile::getKV('profileurl', $author['url'][0]);
310 // XXX: Is this a good way to create the profile?
311 if (!$profile instanceof Profile) {
312 $profile = new Profile();
313 $profile->profileurl = $author['url'][0];
314 $profile->fullname = $author['name'][0];
315 $profile->nickname = isset($author['nickname']) ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
316 $profile->created = common_sql_now();
320 return array($profile, $author);
323 function linkback_save($source, $target, $response, $notice_or_user) {
324 $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
325 if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
326 if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
327 if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
329 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
330 $mf2 = $mf2->parse();
332 $entry = linkback_find_entry($mf2, $target);
334 preg_match('/<title>([^<]+)', $response->getBody(), $match);
336 'content' => array('html' => $response->getBody()),
337 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
342 $entry['url'] = array($response->getEffectiveUrl());
345 if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
346 if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
348 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
349 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
350 list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
353 $orig = clone($dupe);
356 // Ignore duplicate save error
357 try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
358 try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
359 try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
361 if($options['reply_to']) { $dupe->reply_to = $options['reply_to']; }
362 if($options['repeat_of']) { $dupe->repeat_of = $options['repeat_of']; }
363 if($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
364 $parent = Notice::getKV('id', $dupe->repost_of ? $dupe->repost_of : $dupe->reply_to);
365 if($parent instanceof Notice) {
366 // If we changed the reply_to or repeat_of we might live in a new conversation now
367 $dupe->conversation = $parent->conversation;
370 if($dupe->update($orig)) { $saved = $dupe; }
371 if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
372 // Delete empty conversation
373 $emptyConversation = Conversation::getKV('id', $orig->conversation);
374 $emptyConversation->delete();
376 } catch (Exception $e) {
377 common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
380 common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
381 } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
382 $act = new Activity();
383 $act->type = ActivityObject::ACTIVITY;
384 $act->time = $options['created'] ? strtotime($options['created']) : time();
385 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
386 $act->actor = $profile->asActivityObject();
387 $act->target = $notice_or_user->asActivityObject();
388 $act->objects = array(clone($act->target));
390 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
391 // notice's nickname and %3$s is the content of the favorited notice.)
392 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
393 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
394 $notice_or_user->getRendered());
396 $act->content = $options['rendered'];
399 $act->verb = ActivityVerb::FAVORITE;
400 if(strtolower($entry['rsvp'][0]) == 'yes') {
401 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
402 } else if(strtolower($entry['rsvp'][0]) == 'no') {
403 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
404 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
405 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
409 $act->link = $entry['url'][0];
411 $options['source'] = 'linkback';
412 $options['mentions'] = $options['replies'];
413 unset($options['reply_to']);
414 unset($options['repeat_of']);
417 $saved = Notice::saveActivity($act, $profile, $options);
418 } catch (Exception $e) {
419 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
422 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
424 // Fallback is to make a notice manually
426 $saved = Notice::saveNew($profile->id,
430 } catch (Exception $e) {
431 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
434 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
437 return $saved->getLocalUrl();