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('Auth/Yadis/Yadis.php');
35 require_once(__DIR__ . '/lib/util.php');
37 define('LINKBACKPLUGIN_VERSION', '0.1');
40 * Plugin to do linkbacks for notices containing URLs
42 * After new notices are saved, we check their text for URLs. If there
43 * are URLs, we test each URL to see if it supports any
47 * @author Evan Prodromou <evan@status.net>
48 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
49 * @link http://status.net/
53 class LinkbackPlugin extends Plugin
57 function __construct()
59 parent::__construct();
62 function onHandleQueuedNotice($notice)
64 if (intval($notice->is_local) === Notice::LOCAL_PUBLIC) {
65 // Try to avoid actually mucking with the
67 $c = $notice->content;
68 $this->notice = $notice;
70 if(!$notice->getProfile()->
71 getPref("linkbackplugin", "disable_linkbacks")
74 common_replace_urls_callback($c,
75 array($this, 'linkbackUrl'));
78 if($notice->isRepeat()) {
79 $repeat = Notice::getByID($notice->repeat_of);
80 $this->linkbackUrl($repeat->getUrl());
81 } else if(!empty($notice->reply_to)) {
82 $parent = $notice->getParent();
83 $this->linkbackUrl($parent->getUrl());
86 $replyProfiles = Profile::multiGet('id', $notice->getReplies());
87 foreach($replyProfiles->fetchAll('profileurl') as $profileurl) {
88 $this->linkbackUrl($profileurl);
94 function linkbackUrl($url)
96 common_log(LOG_DEBUG,"Attempting linkback for " . $url);
99 $url = htmlspecialchars_decode($orig);
100 $scheme = parse_url($url, PHP_URL_SCHEME);
101 if (!in_array($scheme, array('http', 'https'))) {
105 // XXX: Do a HEAD first to save some time/bandwidth
107 $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
109 $result = $fetcher->get($url,
110 array('User-Agent: ' . $this->userAgent(),
111 'Accept: application/html+xml,text/html'));
113 if (!in_array($result->status, array('200', '206'))) {
117 // XXX: Should handle relative-URI resolution in these detections
119 $wm = $this->getWebmention($result);
121 // It is the webmention receiver's job to resolve source
122 // Ref: https://github.com/converspace/webmention/issues/43
123 $this->webmention($url, $wm);
125 $pb = $this->getPingback($result);
127 // Pingback still looks for exact URL in our source, so we
128 // must send what we have
129 $this->pingback($url, $pb);
131 $tb = $this->getTrackback($result);
133 $this->trackback($result->final_url, $tb);
141 // Based on https://github.com/indieweb/mention-client-php
142 // which is licensed Apache 2.0
143 function getWebmention($result) {
144 if (isset($result->headers['Link'])) {
145 // XXX: the fetcher only gives back one of each header, so this may fail on multiple Link headers
146 if(preg_match('~<((?:https?://)?[^>]+)>; rel="webmention"~', $result->headers['Link'], $match)) {
148 } elseif(preg_match('~<((?:https?://)?[^>]+)>; rel="http://webmention.org/?"~', $result->headers['Link'], $match)) {
153 // FIXME: Do proper DOM traversal
154 if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]*\/?>/i', $result->body, $match)
155 || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
157 } elseif(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="http:\/\/webmention\.org\/?"[ ]*\/?>/i', $result->body, $match)
158 || preg_match('/<(?:link|a)[ ]+rel="http:\/\/webmention\.org\/?"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
163 function webmention($url, $endpoint) {
164 $source = $this->notice->getUrl();
171 $request = HTTPClient::start();
173 $response = $request->post($endpoint,
175 'Content-type: application/x-www-form-urlencoded',
176 'Accept: application/json'
181 if(!in_array($response->getStatus(), array(200,202))) {
182 common_log(LOG_WARNING,
183 "Webmention request failed for '$url' ($endpoint)");
185 } catch (HTTP_Request2_Exception $e) {
186 common_log(LOG_WARNING,
187 "Webmention request failed for '$url' ($endpoint)");
191 function getPingback($result) {
192 if (array_key_exists('X-Pingback', $result->headers)) {
193 return $result->headers['X-Pingback'];
194 } else if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]*\/?>/i', $result->body, $match)
195 || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
200 function pingback($url, $endpoint)
202 $args = array($this->notice->getUrl(), $url);
204 if (!extension_loaded('xmlrpc')) {
205 if (!dl('xmlrpc.so')) {
206 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
211 $request = HTTPClient::start();
213 $request->setBody(xmlrpc_encode_request('pingback.ping', $args));
214 $response = $request->post($endpoint,
215 array('Content-Type: text/xml'),
217 $response = xmlrpc_decode($response->getBody());
218 if (xmlrpc_is_fault($response)) {
219 common_log(LOG_WARNING,
220 "Pingback error for '$url' ($endpoint): ".
221 "$response[faultString] ($response[faultCode])");
224 "Pingback success for '$url' ($endpoint): ".
227 } catch (HTTP_Request2_Exception $e) {
228 common_log(LOG_WARNING,
229 "Pingback request failed for '$url' ($endpoint)");
233 // Largely cadged from trackback_cls.php by
234 // Ran Aroussi <ran@blogish.org>, GPL2 or any later version
235 // http://phptrackback.sourceforge.net/
236 function getTrackback($result)
238 $text = $result->body;
239 $url = $result->final_url;
241 if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
242 for ($i = 0; $i < count($match); $i++) {
243 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
244 $rdf_array[] = trim($match[$i][1]);
248 // Loop through the RDFs array and extract trackback URIs
250 $tb_array = array(); // <- holds list of trackback URIs
252 if (!empty($rdf_array)) {
254 for ($i = 0; $i < count($rdf_array); $i++) {
255 if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
256 $tb_array[] = trim($array[1]);
264 if (empty($tb_array)) {
271 if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
272 foreach ($match[1] as $atag) {
273 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
283 function trackback($url, $endpoint)
285 $profile = $this->notice->getProfile();
287 // TRANS: Trackback title.
288 // TRANS: %1$s is a profile nickname, %2$s is a timestamp.
289 $args = array('title' => sprintf(_m('%1$s\'s status on %2$s'),
291 common_exact_date($this->notice->created)),
292 'excerpt' => $this->notice->content,
293 'url' => $this->notice->getUrl(),
294 'blog_name' => $profile->nickname);
296 $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
298 $result = $fetcher->post($endpoint,
299 http_build_query($args),
300 array('User-Agent: ' . $this->userAgent()));
302 if ($result->status != '200') {
303 common_log(LOG_WARNING,
304 "Trackback error for '$url' ($endpoint): ".
308 "Trackback success for '$url' ($endpoint): ".
314 public function onRouterInitialized(URLMapper $m)
316 $m->connect('main/linkback/webmention', array('action' => 'webmention'));
317 $m->connect('main/linkback/pingback', array('action' => 'pingback'));
320 public function onStartShowHTML($action)
322 header('Link: <' . common_local_url('webmention') . '>; rel="webmention"', false);
323 header('X-Pingback: ' . common_local_url('pingback'));
326 public function version()
328 return LINKBACKPLUGIN_VERSION;
331 function onPluginVersion(array &$versions)
333 $versions[] = array('name' => 'Linkback',
334 'version' => LINKBACKPLUGIN_VERSION,
335 'author' => 'Evan Prodromou',
336 'homepage' => 'http://status.net/wiki/Plugin:Linkback',
338 // TRANS: Plugin description.
339 _m('Notify blog authors when their posts have been linked in '.
340 'microblog notices using '.
341 '<a href="http://www.hixie.ch/specs/pingback/pingback">Pingback</a> '.
342 'or <a href="http://www.movabletype.org/docs/mttrackback.html">Trackback</a> protocols.'));
346 public function onStartInitializeRouter(URLMapper $m)
348 $m->connect('settings/linkback', array('action' => 'linkbacksettings'));
352 function onEndAccountSettingsNav($action)
354 $action_name = $action->trimmed('action');
356 $action->menuItem(common_local_url('linkbacksettings'),
357 // TRANS: OpenID plugin menu item on user settings page.
358 _m('MENU', 'Send Linkbacks'),
359 // TRANS: OpenID plugin tooltip for user settings menu item.
360 _m('Opt-out of sending linkbacks.'),
361 $action_name === 'linkbacksettings');
365 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
367 // If we don't handle this, keep the event handler going
368 if (!in_array($notice->source, array('linkback'))) {
373 $url = $notice->getUrl();
374 // If getUrl() throws exception, $url is never set
376 $bits = parse_url($url);
377 $domain = $bits['host'];
378 if (substr($domain, 0, 4) == 'www.') {
379 $name = substr($domain, 4);
384 // TRANS: Title. %s is a domain name.
385 $title = sprintf(_m('Sent from %s via Linkback'), $domain);
387 // Abort event handler, we have a name and URL!
389 } catch (InvalidUrlException $e) {
390 // This just means we don't have the notice source data