]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/LinkbackPlugin.php
Catch NoHttpResponseException when using HTTPClient
[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('Auth/Yadis/Yadis.php');
35 require_once(__DIR__ . '/lib/util.php');
36
37 define('LINKBACKPLUGIN_VERSION', '0.1');
38
39 /**
40  * Plugin to do linkbacks for notices containing URLs
41  *
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
44  *
45  * @category Plugin
46  * @package  StatusNet
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/
50  *
51  * @see      Event
52  */
53 class LinkbackPlugin extends Plugin
54 {
55     var $notice = null;
56
57     function __construct()
58     {
59         parent::__construct();
60     }
61
62     function onHandleQueuedNotice($notice)
63     {
64         if (intval($notice->is_local) === Notice::LOCAL_PUBLIC) {
65             // Try to avoid actually mucking with the
66             // notice content
67             $c = $notice->content;
68             $this->notice = $notice;
69
70             if(!$notice->getProfile()->
71                 getPref("linkbackplugin", "disable_linkbacks")
72             ) {
73                 // Ignoring results
74                 common_replace_urls_callback($c,
75                                              array($this, 'linkbackUrl'));
76             }
77
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());
84             }
85
86             $replyProfiles = Profile::multiGet('id', $notice->getReplies());
87             foreach($replyProfiles->fetchAll('profileurl') as $profileurl) {
88                 $this->linkbackUrl($profileurl);
89             }
90         }
91         return true;
92     }
93
94     function linkbackUrl($url)
95     {
96         common_log(LOG_DEBUG,"Attempting linkback for " . $url);
97
98         $orig = $url;
99         $url = htmlspecialchars_decode($orig);
100         $scheme = parse_url($url, PHP_URL_SCHEME);
101         if (!in_array($scheme, array('http', 'https'))) {
102             return $orig;
103         }
104
105         // XXX: Do a HEAD first to save some time/bandwidth
106
107         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
108
109         $result = $fetcher->get($url,
110                                 array('User-Agent: ' . $this->userAgent(),
111                                       'Accept: application/html+xml,text/html'));
112
113         if (!in_array($result->status, array('200', '206'))) {
114             return $orig;
115         }
116
117         // XXX: Should handle relative-URI resolution in these detections
118
119         $wm = $this->getWebmention($result);
120         if(!empty($wm)) {
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);
124         } else {
125             $pb = $this->getPingback($result);
126             if (!empty($pb)) {
127                 // Pingback still looks for exact URL in our source, so we
128                 // must send what we have
129                 $this->pingback($url, $pb);
130             } else {
131                 $tb = $this->getTrackback($result);
132                 if (!empty($tb)) {
133                     $this->trackback($result->final_url, $tb);
134                 }
135             }
136         }
137
138         return $orig;
139     }
140
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)) {
147                 return $match[1];
148             } elseif(preg_match('~<((?:https?://)?[^>]+)>; rel="http://webmention.org/?"~', $result->headers['Link'], $match)) {
149                 return $match[1];
150             }
151         }
152
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)) {
156             return $match[1];
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)) {
159             return $match[1];
160         }
161     }
162
163     function webmention($url, $endpoint) {
164         $source = $this->notice->getUrl();
165
166         $payload = array(
167             'source' => $source,
168             'target' => $url
169         );
170
171         $request = HTTPClient::start();
172         try {
173             $response = $request->post($endpoint,
174                 array(
175                     'Content-type: application/x-www-form-urlencoded',
176                     'Accept: application/json'
177                 ),
178                 $payload
179             );
180
181             if(!in_array($response->getStatus(), array(200,202))) {
182                 common_log(LOG_WARNING,
183                            "Webmention request failed for '$url' ($endpoint)");
184             }
185         } catch (Exception $e) {
186             common_log(LOG_WARNING, "Webmention request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
187         }
188     }
189
190     function getPingback($result) {
191         if (array_key_exists('X-Pingback', $result->headers)) {
192             return $result->headers['X-Pingback'];
193         } else if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]*\/?>/i', $result->body, $match)
194                   || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
195             return $match[1];
196         }
197     }
198
199     function pingback($url, $endpoint)
200     {
201         $args = array($this->notice->getUrl(), $url);
202
203         if (!extension_loaded('xmlrpc')) {
204             if (!dl('xmlrpc.so')) {
205                 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
206                 return;
207             }
208         }
209
210         $request = HTTPClient::start();
211         try {
212             $request->setBody(xmlrpc_encode_request('pingback.ping', $args));
213             $response = $request->post($endpoint,
214                 array('Content-Type: text/xml'),
215                 false);
216             $response = xmlrpc_decode($response->getBody());
217             if (xmlrpc_is_fault($response)) {
218                 common_log(LOG_WARNING,
219                        "Pingback error for '$url' ($endpoint): ".
220                        "$response[faultString] ($response[faultCode])");
221             } else {
222                 common_log(LOG_INFO,
223                        "Pingback success for '$url' ($endpoint): ".
224                        "'$response'");
225             }
226         } catch (Exception $e) {
227             common_log(LOG_WARNING, "Pingback request failed for '{$url}' ({$endpoint}): {$e->getMessage()}");
228         }
229     }
230
231     // Largely cadged from trackback_cls.php by
232     // Ran Aroussi <ran@blogish.org>, GPL2 or any later version
233     // http://phptrackback.sourceforge.net/
234     function getTrackback($result)
235     {
236         $text = $result->body;
237         $url = $result->final_url;
238
239         if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
240             for ($i = 0; $i < count($match); $i++) {
241                 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
242                     $rdf_array[] = trim($match[$i][1]);
243                 }
244             }
245
246             // Loop through the RDFs array and extract trackback URIs
247
248             $tb_array = array(); // <- holds list of trackback URIs
249
250             if (!empty($rdf_array)) {
251
252                 for ($i = 0; $i < count($rdf_array); $i++) {
253                     if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
254                         $tb_array[] = trim($array[1]);
255                         break;
256                     }
257                 }
258             }
259
260             // Return Trackbacks
261
262             if (empty($tb_array)) {
263                 return null;
264             } else {
265                 return $tb_array[0];
266             }
267         }
268
269         if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
270             foreach ($match[1] as $atag) {
271                 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
272                     return $url[1];
273                 }
274             }
275         }
276
277         return null;
278
279     }
280
281     function trackback($url, $endpoint)
282     {
283         $profile = $this->notice->getProfile();
284
285         // TRANS: Trackback title.
286         // TRANS: %1$s is a profile nickname, %2$s is a timestamp.
287         $args = array('title' => sprintf(_m('%1$s\'s status on %2$s'),
288                                          $profile->nickname,
289                                          common_exact_date($this->notice->created)),
290                       'excerpt' => $this->notice->content,
291                       'url' => $this->notice->getUrl(),
292                       'blog_name' => $profile->nickname);
293
294         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
295
296         $result = $fetcher->post($endpoint,
297                                  http_build_query($args),
298                                  array('User-Agent: ' . $this->userAgent()));
299
300         if ($result->status != '200') {
301             common_log(LOG_WARNING,
302                        "Trackback error for '$url' ($endpoint): ".
303                        "$result->body");
304         } else {
305             common_log(LOG_INFO,
306                        "Trackback success for '$url' ($endpoint): ".
307                        "'$result->body'");
308         }
309     }
310
311
312     public function onRouterInitialized(URLMapper $m)
313     {
314         $m->connect('main/linkback/webmention', array('action' => 'webmention'));
315         $m->connect('main/linkback/pingback', array('action' => 'pingback'));
316     }
317
318     public function onStartShowHTML($action)
319     {
320         header('Link: <' . common_local_url('webmention') . '>; rel="webmention"', false);
321         header('X-Pingback: ' . common_local_url('pingback'));
322     }
323
324     public function version()
325     {
326         return LINKBACKPLUGIN_VERSION;
327     }
328
329     function onPluginVersion(array &$versions)
330     {
331         $versions[] = array('name' => 'Linkback',
332                             'version' => LINKBACKPLUGIN_VERSION,
333                             'author' => 'Evan Prodromou',
334                             'homepage' => 'http://status.net/wiki/Plugin:Linkback',
335                             'rawdescription' =>
336                             // TRANS: Plugin description.
337                             _m('Notify blog authors when their posts have been linked in '.
338                                'microblog notices using '.
339                                '<a href="http://www.hixie.ch/specs/pingback/pingback">Pingback</a> '.
340                                'or <a href="http://www.movabletype.org/docs/mttrackback.html">Trackback</a> protocols.'));
341         return true;
342     }
343
344     public function onStartInitializeRouter(URLMapper $m)
345     {
346         $m->connect('settings/linkback', array('action' => 'linkbacksettings'));
347         return true;
348     }
349
350     function onEndAccountSettingsNav($action)
351     {
352         $action_name = $action->trimmed('action');
353
354         $action->menuItem(common_local_url('linkbacksettings'),
355                           // TRANS: OpenID plugin menu item on user settings page.
356                           _m('MENU', 'Send Linkbacks'),
357                           // TRANS: OpenID plugin tooltip for user settings menu item.
358                           _m('Opt-out of sending linkbacks.'),
359                           $action_name === 'linkbacksettings');
360         return true;
361     }
362
363     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
364     {
365         // If we don't handle this, keep the event handler going
366         if (!in_array($notice->source, array('linkback'))) {
367             return true;
368         }
369
370         try {
371             $url = $notice->getUrl();
372             // If getUrl() throws exception, $url is never set
373
374             $bits = parse_url($url);
375             $domain = $bits['host'];
376             if (substr($domain, 0, 4) == 'www.') {
377                 $name = substr($domain, 4);
378             } else {
379                 $name = $domain;
380             }
381
382             // TRANS: Title. %s is a domain name.
383             $title = sprintf(_m('Sent from %s via Linkback'), $domain);
384
385             // Abort event handler, we have a name and URL!
386             return false;
387         } catch (InvalidUrlException $e) {
388             // This just means we don't have the notice source data
389             return true;
390         }
391     }
392 }