3 * StatusNet, the distributed open-source microblogging tool
5 * Plugin to do linkbacks for notices containing links
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @copyright 2009 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
34 require_once(__DIR__ . '/lib/util.php');
36 define('LINKBACKPLUGIN_VERSION', '0.1');
39 * Plugin to do linkbacks for notices containing URLs
41 * After new notices are saved, we check their text for URLs. If there
42 * are URLs, we test each URL to see if it supports any
46 * @author Evan Prodromou <evan@status.net>
47 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48 * @link http://status.net/
52 class LinkbackPlugin extends Plugin
56 function __construct()
58 parent::__construct();
61 function onHandleQueuedNotice(Notice $notice)
63 if (!$notice->isLocal() || !$notice->isPublic()) {
67 // Try to avoid actually mucking with the
69 $c = $notice->content;
70 $this->notice = $notice;
72 if (!$notice->getProfile()->getPref('linkbackplugin', 'disable_linkbacks')) {
74 common_replace_urls_callback($c, array($this, 'linkbackUrl'));
78 if ($notice->isRepeat()) {
79 $repeat = Notice::getByID($notice->repeat_of);
80 $this->linkbackUrl($repeat->getUrl());
81 } elseif (!empty($notice->reply_to)) {
82 $parent = $notice->getParent();
83 $this->linkbackUrl($parent->getUrl());
85 } catch (InvalidUrlException $e) {
86 // can't send linkback to notice if we don't have a remote HTTP(S) URL
87 // but we can still ping the attention-receivers below
88 } catch (NoParentNoticeException $e) {
89 // can't send linkback to non-existing parent URL
93 // doubling up getReplies and getAttentionProfileIDs because we're not entirely migrated yet
94 $replyProfiles = Profile::multiGet('id', array_unique(array_merge($notice->getReplies(), $notice->getAttentionProfileIDs())));
95 foreach ($replyProfiles->fetchAll('profileurl') as $profileurl) {
96 if (common_valid_http_url($profileurl)) {
97 $this->linkbackUrl($profileurl);
104 function linkbackUrl($url)
106 common_log(LOG_DEBUG,"Attempting linkback for " . $url);
109 $url = htmlspecialchars_decode($orig);
110 $scheme = parse_url($url, PHP_URL_SCHEME);
111 if (!in_array($scheme, array('http', 'https'))) {
115 // XXX: Do a HEAD first to save some time/bandwidth
117 $httpclient = new HTTPClient();
118 $response = $httpclient->get($url, ["User-Agent: {$this->userAgent()}",
119 "Accept: application/html+xml,text/html"]);
121 if (!in_array($response->getStatus(), array(200, 206))) {
122 throw new Exception('Invalid response code for GET request');
124 } catch (Exception $e) {
125 // something didn't work out in our GET request
129 // XXX: Should handle relative-URI resolution in these detections
131 $wm = $this->getWebmention($response);
133 // It is the webmention receiver's job to resolve source
134 // Ref: https://github.com/converspace/webmention/issues/43
135 $this->webmention($url, $wm);
137 $pb = $this->getPingback($response);
139 // Pingback still looks for exact URL in our source, so we
140 // must send what we have
141 $this->pingback($url, $pb);
143 $tb = $this->getTrackback($response);
145 $this->trackback($response->getEffectiveUrl(), $tb);
153 // Based on https://github.com/indieweb/mention-client-php
154 // which is licensed Apache 2.0
155 function getWebmention(HTTP_Request2_Response $response) {
156 $link = $response->getHeader('Link');
157 if (!is_null($link)) {
158 // XXX: the fetcher gives back a comma-separated string of all Link headers, I hope the parsing works reliably
159 if (preg_match('~<((?:https?://)?[^>]+)>; rel="webmention"~', $link, $match)) {
161 } elseif (preg_match('~<((?:https?://)?[^>]+)>; rel="http://webmention.org/?"~', $link, $match)) {
166 // FIXME: Do proper DOM traversal
167 if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]*\/?>/i', $response->getBody(), $match)
168 || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $response->getBody(), $match)) {
170 } elseif (preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="http:\/\/webmention\.org\/?"[ ]*\/?>/i', $response->getBody(), $match)
171 || preg_match('/<(?:link|a)[ ]+rel="http:\/\/webmention\.org\/?"[ ]+href="([^"]+)"[ ]*\/?>/i', $response->getBody(), $match)) {
176 function webmention($url, $endpoint) {
177 $source = $this->notice->getUrl();
184 $request = HTTPClient::start();
186 $response = $request->post($endpoint,
188 'Content-type: application/x-www-form-urlencoded',
189 'Accept: application/json'
194 if(!in_array($response->getStatus(), array(200,202))) {
195 common_log(LOG_WARNING,
196 "Webmention request failed for '$url' ($endpoint)");
198 } catch (Exception $e) {
199 common_log(LOG_WARNING, "Webmention request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
203 function getPingback(HTTP_Request2_Response $response) {
204 if ($response->getHeader('X-Pingback')) {
205 return $response->getHeader('X-Pingback');
206 } elseif (preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]*\/?>/i', $response->getBody(), $match)
207 || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $response->getBody(), $match)) {
212 function pingback($url, $endpoint)
214 $args = array($this->notice->getUrl(), $url);
216 if (!extension_loaded('xmlrpc')) {
217 if (!dl('xmlrpc.so')) {
218 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
223 $request = HTTPClient::start();
225 $request->setBody(xmlrpc_encode_request('pingback.ping', $args));
226 $response = $request->post($endpoint,
227 array('Content-Type: text/xml'),
229 $response = xmlrpc_decode($response->getBody());
230 if (xmlrpc_is_fault($response)) {
231 common_log(LOG_WARNING,
232 "Pingback error for '$url' ($endpoint): ".
233 "$response[faultString] ($response[faultCode])");
236 "Pingback success for '$url' ($endpoint): ".
239 } catch (Exception $e) {
240 common_log(LOG_WARNING, "Pingback request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
244 // Largely cadged from trackback_cls.php by
245 // Ran Aroussi <ran@blogish.org>, GPL2 or any later version
246 // http://phptrackback.sourceforge.net/
247 function getTrackback(HTTP_Request2_Response $response)
249 $text = $response->getBody();
250 $url = $response->getEffectiveUrl();
252 if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
253 for ($i = 0; $i < count($match); $i++) {
254 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
255 $rdf_array[] = trim($match[$i][1]);
259 // Loop through the RDFs array and extract trackback URIs
261 $tb_array = array(); // <- holds list of trackback URIs
263 if (!empty($rdf_array)) {
265 for ($i = 0; $i < count($rdf_array); $i++) {
266 if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
267 $tb_array[] = trim($array[1]);
275 if (empty($tb_array)) {
282 if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
283 foreach ($match[1] as $atag) {
284 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
294 function trackback($url, $endpoint)
296 $profile = $this->notice->getProfile();
298 // TRANS: Trackback title.
299 // TRANS: %1$s is a profile nickname, %2$s is a timestamp.
300 $args = array('title' => sprintf(_m('%1$s\'s status on %2$s'),
301 $profile->getNickname(),
302 common_exact_date($this->notice->getCreated())),
303 'excerpt' => $this->notice->getContent(),
304 'url' => $this->notice->getUrl(),
305 'blog_name' => $profile->getNickname());
308 $httpclient = new HTTPClient(null, HTTPClient::METHOD_POST);
309 $response = $httpclient->post($endpoint, ["User-Agent: {$this->userAgent()}"], $args);
310 if ($response->getStatus() === 200) {
311 common_log(LOG_INFO, "Trackback success for '$url' ($endpoint): "._ve($response->getBody()));
313 common_log(LOG_WARNING, "Trackback error for '$url' ($endpoint): "._ve($response->getBody()));
315 } catch (Exception $e) {
316 common_log(LOG_INFO, "Trackback error for '$url' ($endpoint): "._ve($e->getMessage()));
321 public function onRouterInitialized(URLMapper $m)
323 $m->connect('main/linkback/webmention', array('action' => 'webmention'));
324 $m->connect('main/linkback/pingback', array('action' => 'pingback'));
327 public function onStartShowHTML($action)
329 header('Link: <' . common_local_url('webmention') . '>; rel="webmention"', false);
330 header('X-Pingback: ' . common_local_url('pingback'));
333 public function version()
335 return LINKBACKPLUGIN_VERSION;
338 function onPluginVersion(array &$versions)
340 $versions[] = array('name' => 'Linkback',
341 'version' => LINKBACKPLUGIN_VERSION,
342 'author' => 'Evan Prodromou',
343 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/Linkback',
345 // TRANS: Plugin description.
346 _m('Notify blog authors when their posts have been linked in '.
347 'microblog notices using '.
348 '<a href="http://www.hixie.ch/specs/pingback/pingback">Pingback</a> '.
349 'or <a href="http://www.movabletype.org/docs/mttrackback.html">Trackback</a> protocols.'));
353 public function onStartInitializeRouter(URLMapper $m)
355 $m->connect('settings/linkback', array('action' => 'linkbacksettings'));
359 function onEndAccountSettingsNav($action)
361 $action_name = $action->trimmed('action');
363 $action->menuItem(common_local_url('linkbacksettings'),
364 // TRANS: OpenID plugin menu item on user settings page.
365 _m('MENU', 'Send Linkbacks'),
366 // TRANS: OpenID plugin tooltip for user settings menu item.
367 _m('Opt-out of sending linkbacks.'),
368 $action_name === 'linkbacksettings');
372 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
374 // If we don't handle this, keep the event handler going
375 if (!in_array($notice->source, array('linkback'))) {
380 $url = $notice->getUrl();
381 // If getUrl() throws exception, $url is never set
383 $bits = parse_url($url);
384 $domain = $bits['host'];
385 if (substr($domain, 0, 4) == 'www.') {
386 $name = substr($domain, 4);
391 // TRANS: Title. %s is a domain name.
392 $title = sprintf(_m('Sent from %s via Linkback'), $domain);
394 // Abort event handler, we have a name and URL!
396 } catch (InvalidUrlException $e) {
397 // This just means we don't have the notice source data