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) === 0) {
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) === FALSE) {
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()) !== FALSE) {
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) !== FALSE; })) > 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) !== FALSE; })) > 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) !== FALSE) {
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) != FALSE; })) > 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) != FALSE; })) > 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(strtotime($entry['published'][0]))
247 : common_sql_date(strtotime($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_avatar($profile, $url) {
284 // Ripped from OStatus plugin for now
285 $temp_filename = tempnam(sys_get_temp_dir(), 'linback_avatar');
287 $imgData = HTTPClient::quickGet($url);
288 // Make sure it's at least an image file. ImageFile can do the rest.
289 if (false === getimagesizefromstring($imgData)) {
292 file_put_contents($temp_filename, $imgData);
293 unset($imgData); // No need to carry this in memory.
295 $imagefile = new ImageFile(null, $temp_filename);
296 $filename = Avatar::filename($profile->id,
297 image_type_to_extension($imagefile->type),
300 rename($temp_filename, Avatar::path($filename));
301 } catch (Exception $e) {
302 unlink($temp_filename);
305 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
306 // keep from accidentally saving images from command-line (queues)
307 // that can't be read from web server, which causes hard-to-notice
308 // problems later on:
310 // http://status.net/open-source/issues/2663
311 chmod(Avatar::path($filename), 0644);
313 $profile->setOriginal($filename);
316 function linkback_profile($entry, $mf2, $response, $target) {
317 if(isset($entry['author']) && isset($entry['author'][0]['properties'])) {
318 $author = $entry['author'][0]['properties'];
320 $author = linkback_hcard($mf2, $response->getEffectiveUrl());
324 $author = array('name' => $entry['name']);
327 if (!isset($author['url']) || empty($author['url'])) {
328 $author['url'] = array($response->getEffectiveUrl());
331 $user = User::getKV('uri', $author['url'][0]);
332 if ($user instanceof User) {
333 common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
338 $profile = Profile::fromUri($author['url'][0]);
339 } catch(UnknownUriException $ex) {
340 $profile = Profile::getKV('profileurl', $author['url'][0]);
343 // XXX: Is this a good way to create the profile?
344 if (!$profile instanceof Profile) {
345 $profile = new Profile();
346 $profile->profileurl = $author['url'][0];
347 $profile->fullname = $author['name'][0];
348 $profile->nickname = isset($author['nickname']) ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
349 $profile->created = common_sql_now();
352 if($author['photo'] && $author['photo'][0]) {
353 linkback_avatar($profile, $author['photo'][0]);
357 return array($profile, $author);
360 function linkback_save($source, $target, $response, $notice_or_user) {
361 $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
362 if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
363 if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
364 if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
366 $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
367 $mf2 = $mf2->parse();
369 $entry = linkback_find_entry($mf2, $target);
371 preg_match('/<title>([^<]+)', $response->getBody(), $match);
373 'content' => array('html' => $response->getBody()),
374 'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
379 $entry['url'] = array($response->getEffectiveUrl());
382 if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
383 if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
385 $entry['type'] = linkback_entry_type($entry, $mf2, $target);
386 list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
387 list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
390 $orig = clone($dupe);
393 // Ignore duplicate save error
394 try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
395 try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
396 try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
398 if (isset($options['reply_to'])) {
399 $dupe->reply_to = $options['reply_to'];
401 if (isset($options['repeat_of'])) {
402 $dupe->repeat_of = $options['repeat_of'];
404 if ($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
405 $parent = Notice::getKV('id', $dupe->repeat_of ?: $dupe->reply_to);
406 if($parent instanceof Notice) {
407 // If we changed the reply_to or repeat_of we might live in a new conversation now
408 $dupe->conversation = $parent->conversation;
411 if($dupe->update($orig)) { $saved = $dupe; }
412 if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
413 // Delete empty conversation
414 $emptyConversation = Conversation::getKV('id', $orig->conversation);
415 $emptyConversation->delete();
417 } catch (Exception $e) {
418 common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
421 common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
422 } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
423 $act = new Activity();
424 $act->type = ActivityObject::ACTIVITY;
425 $act->time = $options['created'] ? strtotime($options['created']) : time();
426 $act->title = $entry["name"] ? $entry["name"][0] : _m("Favor");
427 $act->actor = $profile->asActivityObject();
428 $act->target = $notice_or_user->asActivityObject();
429 $act->objects = array(clone($act->target));
431 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
432 // notice's nickname and %3$s is the content of the favorited notice.)
433 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
434 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
435 $notice_or_user->getRendered());
437 $act->content = $options['rendered'];
440 $act->verb = ActivityVerb::FAVORITE;
441 if(strtolower($entry['rsvp'][0]) == 'yes') {
442 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
443 } else if(strtolower($entry['rsvp'][0]) == 'no') {
444 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
445 } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
446 $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
450 $act->link = $entry['url'][0];
452 $options['source'] = 'linkback';
453 $options['mentions'] = $options['replies'];
454 unset($options['reply_to']);
455 unset($options['repeat_of']);
458 $saved = Notice::saveActivity($act, $profile, $options);
459 } catch (Exception $e) {
460 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
463 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
465 // Fallback is to make a notice manually
467 $saved = Notice::saveNew($profile->id,
471 } catch (Exception $e) {
472 common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
475 common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
478 return $saved->getLocalUrl();