]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/LinkbackPlugin.php
Use HTTPClient instead of Yadis HTTPFetcher in Linkback plugin
[quix0rs-gnu-social.git] / plugins / Linkback / LinkbackPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Plugin to do linkbacks for notices containing links
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
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/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 require_once(__DIR__ . '/lib/util.php');
35
36 define('LINKBACKPLUGIN_VERSION', '0.1');
37
38 /**
39  * Plugin to do linkbacks for notices containing URLs
40  *
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
43  *
44  * @category Plugin
45  * @package  StatusNet
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/
49  *
50  * @see      Event
51  */
52 class LinkbackPlugin extends Plugin
53 {
54     var $notice = null;
55
56     function __construct()
57     {
58         parent::__construct();
59     }
60
61     function onHandleQueuedNotice(Notice $notice)
62     {
63         if (!$notice->isLocal() || !$notice->isPublic()) {
64             return true;
65         }
66
67         // Try to avoid actually mucking with the
68         // notice content
69         $c = $notice->content;
70         $this->notice = $notice;
71
72         if (!$notice->getProfile()->getPref('linkbackplugin', 'disable_linkbacks')) {
73             // Ignoring results
74             common_replace_urls_callback($c, array($this, 'linkbackUrl'));
75         }
76
77         try {
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());
84             }
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
90             return true;
91         }
92
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);
98             }
99         }
100
101         return true;
102     }
103
104     function linkbackUrl($url)
105     {
106         common_log(LOG_DEBUG,"Attempting linkback for " . $url);
107
108         $orig = $url;
109         $url = htmlspecialchars_decode($orig);
110         $scheme = parse_url($url, PHP_URL_SCHEME);
111         if (!in_array($scheme, array('http', 'https'))) {
112             return $orig;
113         }
114
115         // XXX: Do a HEAD first to save some time/bandwidth
116         try {
117             $httpclient = new HTTPClient();
118             $response = $httpclient->get($url, ["User-Agent: {$this->userAgent()}",
119                                                 "Accept: application/html+xml,text/html"]);
120
121             if (!in_array($response->getStatus(), array(200, 206))) {
122                 throw new Exception('Invalid response code for GET request');
123             }
124         } catch (Exception $e) {
125             // something didn't work out in our GET request
126             return $orig;
127         }
128
129         // XXX: Should handle relative-URI resolution in these detections
130
131         $wm = $this->getWebmention($response);
132         if(!empty($wm)) {
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);
136         } else {
137             $pb = $this->getPingback($response);
138             if (!empty($pb)) {
139                 // Pingback still looks for exact URL in our source, so we
140                 // must send what we have
141                 $this->pingback($url, $pb);
142             } else {
143                 $tb = $this->getTrackback($response);
144                 if (!empty($tb)) {
145                     $this->trackback($response->getEffectiveUrl(), $tb);
146                 }
147             }
148         }
149
150         return $orig;
151     }
152
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)) {
160                 return $match[1];
161             } elseif (preg_match('~<((?:https?://)?[^>]+)>; rel="http://webmention.org/?"~', $link, $match)) {
162                 return $match[1];
163             }
164         }
165
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)) {
169             return $match[1];
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)) {
172             return $match[1];
173         }
174     }
175
176     function webmention($url, $endpoint) {
177         $source = $this->notice->getUrl();
178
179         $payload = array(
180             'source' => $source,
181             'target' => $url
182         );
183
184         $request = HTTPClient::start();
185         try {
186             $response = $request->post($endpoint,
187                 array(
188                     'Content-type: application/x-www-form-urlencoded',
189                     'Accept: application/json'
190                 ),
191                 $payload
192             );
193
194             if(!in_array($response->getStatus(), array(200,202))) {
195                 common_log(LOG_WARNING,
196                            "Webmention request failed for '$url' ($endpoint)");
197             }
198         } catch (Exception $e) {
199             common_log(LOG_WARNING, "Webmention request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
200         }
201     }
202
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)) {
208             return $match[1];
209         }
210     }
211
212     function pingback($url, $endpoint)
213     {
214         $args = array($this->notice->getUrl(), $url);
215
216         if (!extension_loaded('xmlrpc')) {
217             if (!dl('xmlrpc.so')) {
218                 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
219                 return;
220             }
221         }
222
223         $request = HTTPClient::start();
224         try {
225             $request->setBody(xmlrpc_encode_request('pingback.ping', $args));
226             $response = $request->post($endpoint,
227                 array('Content-Type: text/xml'),
228                 false);
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])");
234             } else {
235                 common_log(LOG_INFO,
236                        "Pingback success for '$url' ($endpoint): ".
237                        "'$response'");
238             }
239         } catch (Exception $e) {
240             common_log(LOG_WARNING, "Pingback request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
241         }
242     }
243
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)
248     {
249         $text = $response->getBody();
250         $url = $response->getEffectiveUrl();
251
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]);
256                 }
257             }
258
259             // Loop through the RDFs array and extract trackback URIs
260
261             $tb_array = array(); // <- holds list of trackback URIs
262
263             if (!empty($rdf_array)) {
264
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]);
268                         break;
269                     }
270                 }
271             }
272
273             // Return Trackbacks
274
275             if (empty($tb_array)) {
276                 return null;
277             } else {
278                 return $tb_array[0];
279             }
280         }
281
282         if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
283             foreach ($match[1] as $atag) {
284                 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
285                     return $url[1];
286                 }
287             }
288         }
289
290         return null;
291
292     }
293
294     function trackback($url, $endpoint)
295     {
296         $profile = $this->notice->getProfile();
297
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());
306
307         try {
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()));
312             } else {
313                 common_log(LOG_WARNING, "Trackback error for '$url' ($endpoint): "._ve($response->getBody()));
314             }
315         } catch (Exception $e) {
316             common_log(LOG_INFO, "Trackback error for '$url' ($endpoint): "._ve($e->getMessage()));
317         }
318     }
319
320
321     public function onRouterInitialized(URLMapper $m)
322     {
323         $m->connect('main/linkback/webmention', array('action' => 'webmention'));
324         $m->connect('main/linkback/pingback', array('action' => 'pingback'));
325     }
326
327     public function onStartShowHTML($action)
328     {
329         header('Link: <' . common_local_url('webmention') . '>; rel="webmention"', false);
330         header('X-Pingback: ' . common_local_url('pingback'));
331     }
332
333     public function version()
334     {
335         return LINKBACKPLUGIN_VERSION;
336     }
337
338     function onPluginVersion(array &$versions)
339     {
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',
344                             'rawdescription' =>
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.'));
350         return true;
351     }
352
353     public function onStartInitializeRouter(URLMapper $m)
354     {
355         $m->connect('settings/linkback', array('action' => 'linkbacksettings'));
356         return true;
357     }
358
359     function onEndAccountSettingsNav($action)
360     {
361         $action_name = $action->trimmed('action');
362
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');
369         return true;
370     }
371
372     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
373     {
374         // If we don't handle this, keep the event handler going
375         if (!in_array($notice->source, array('linkback'))) {
376             return true;
377         }
378
379         try {
380             $url = $notice->getUrl();
381             // If getUrl() throws exception, $url is never set
382
383             $bits = parse_url($url);
384             $domain = $bits['host'];
385             if (substr($domain, 0, 4) == 'www.') {
386                 $name = substr($domain, 4);
387             } else {
388                 $name = $domain;
389             }
390
391             // TRANS: Title. %s is a domain name.
392             $title = sprintf(_m('Sent from %s via Linkback'), $domain);
393
394             // Abort event handler, we have a name and URL!
395             return false;
396         } catch (InvalidUrlException $e) {
397             // This just means we don't have the notice source data
398             return true;
399         }
400     }
401 }