]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/LinkbackPlugin.php
Allow users to opt out of sending linkbacks
[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
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)
62     {
63         if ($notice->is_local == 1) {
64             // Try to avoid actually mucking with the
65             // notice content
66             $c = $notice->content;
67             $this->notice = $notice;
68
69             if(!$notice->getProfile()->
70                 getPref("linkbackplugin", "disable_linkbacks")
71             ) {
72                 // Ignoring results
73                 common_replace_urls_callback($c,
74                                              array($this, 'linkbackUrl'));
75             }
76
77             if($notice->isRepeat()) {
78                 $repeat = Notice::getByID($notice->repeat_of);
79                 $this->linkbackUrl($repeat->getUrl());
80             } else if(!empty($notice->reply_to)) {
81                 $parent = $notice->getParent();
82                 $this->linkbackUrl($parent->getUrl());
83             }
84         }
85         return true;
86     }
87
88     function linkbackUrl($url)
89     {
90         common_log(LOG_DEBUG,"Attempting linkback for " . $url);
91
92         $orig = $url;
93         $url = htmlspecialchars_decode($orig);
94         $scheme = parse_url($url, PHP_URL_SCHEME);
95         if (!in_array($scheme, array('http', 'https'))) {
96             return $orig;
97         }
98
99         // XXX: Do a HEAD first to save some time/bandwidth
100
101         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
102
103         $result = $fetcher->get($url,
104                                 array('User-Agent: ' . $this->userAgent(),
105                                       'Accept: application/html+xml,text/html'));
106
107         if (!in_array($result->status, array('200', '206'))) {
108             return $orig;
109         }
110
111         // XXX: Should handle relative-URI resolution in these detections
112
113         $wm = $this->getWebmention($result);
114         if(!empty($wm)) {
115             // It is the webmention receiver's job to resolve source
116             // Ref: https://github.com/converspace/webmention/issues/43
117             $this->webmention($url, $wm);
118         } else {
119             $pb = $this->getPingback($result);
120             if (!empty($pb)) {
121                 // Pingback still looks for exact URL in our source, so we
122                 // must send what we have
123                 $this->pingback($url, $pb);
124             } else {
125                 $tb = $this->getTrackback($result);
126                 if (!empty($tb)) {
127                     $this->trackback($result->final_url, $tb);
128                 }
129             }
130         }
131
132         return $orig;
133     }
134
135     // Based on https://github.com/indieweb/mention-client-php
136     // which is licensed Apache 2.0
137     function getWebmention($result) {
138         // XXX: the fetcher only gives back one of each header, so this may fail on multiple Link headers
139         if(preg_match('~<((?:https?://)?[^>]+)>; rel="webmention"~', $result->headers['Link'], $match)) {
140             return $match[1];
141         } elseif(preg_match('~<((?:https?://)?[^>]+)>; rel="http://webmention.org/?"~', $result->headers['Link'], $match)) {
142             return $match[1];
143         }
144
145         if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]*\/?>/i', $result->body, $match)
146            || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?webmention ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
147             return $match[1];
148         } elseif(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="http:\/\/webmention\.org\/?"[ ]*\/?>/i', $result->body, $match)
149                  || preg_match('/<(?:link|a)[ ]+rel="http:\/\/webmention\.org\/?"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
150             return $match[1];
151         }
152     }
153
154     function webmention($url, $endpoint) {
155         $source = $this->notice->getUrl();
156
157         $payload = array(
158             'source' => $source,
159             'target' => $url
160         );
161
162         $request = HTTPClient::start();
163         try {
164             $response = $request->post($endpoint,
165                 array(
166                     'Content-type: application/x-www-form-urlencoded',
167                     'Accept: application/json'
168                 ),
169                 $payload
170             );
171
172             if(!in_array($response->getStatus(), array(200,202))) {
173                 common_log(LOG_WARNING,
174                            "Webmention request failed for '$url' ($endpoint)");
175             }
176         } catch (HTTP_Request2_Exception $e) {
177             common_log(LOG_WARNING,
178                        "Webmention request failed for '$url' ($endpoint)");
179         }
180     }
181
182     function getPingback($result) {
183         if (array_key_exists('X-Pingback', $result->headers)) {
184             return $result->headers['X-Pingback'];
185         } else if(preg_match('/<(?:link|a)[ ]+href="([^"]+)"[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]*\/?>/i', $result->body, $match)
186                   || preg_match('/<(?:link|a)[ ]+rel="[^" ]* ?pingback ?[^" ]*"[ ]+href="([^"]+)"[ ]*\/?>/i', $result->body, $match)) {
187             return $match[1];
188         }
189     }
190
191     function pingback($url, $endpoint)
192     {
193         $args = array($this->notice->getUrl(), $url);
194
195         if (!extension_loaded('xmlrpc')) {
196             if (!dl('xmlrpc.so')) {
197                 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
198                 return;
199             }
200         }
201
202         $request = HTTPClient::start();
203         try {
204             $request->setBody(xmlrpc_encode_request('pingback.ping', $args));
205             $response = $request->post($endpoint,
206                 array('Content-Type: text/xml'),
207                 false);
208             $response = xmlrpc_decode($response->getBody());
209             if (xmlrpc_is_fault($response)) {
210                 common_log(LOG_WARNING,
211                        "Pingback error for '$url' ($endpoint): ".
212                        "$response[faultString] ($response[faultCode])");
213             } else {
214                 common_log(LOG_INFO,
215                        "Pingback success for '$url' ($endpoint): ".
216                        "'$response'");
217             }
218         } catch (HTTP_Request2_Exception $e) {
219             common_log(LOG_WARNING,
220                    "Pingback request failed for '$url' ($endpoint)");
221         }
222     }
223
224     // Largely cadged from trackback_cls.php by
225     // Ran Aroussi <ran@blogish.org>, GPL2 or any later version
226     // http://phptrackback.sourceforge.net/
227     function getTrackback($result)
228     {
229         $text = $result->body;
230         $url = $result->final_url;
231
232         if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
233             for ($i = 0; $i < count($match); $i++) {
234                 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
235                     $rdf_array[] = trim($match[$i][1]);
236                 }
237             }
238
239             // Loop through the RDFs array and extract trackback URIs
240
241             $tb_array = array(); // <- holds list of trackback URIs
242
243             if (!empty($rdf_array)) {
244
245                 for ($i = 0; $i < count($rdf_array); $i++) {
246                     if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
247                         $tb_array[] = trim($array[1]);
248                         break;
249                     }
250                 }
251             }
252
253             // Return Trackbacks
254
255             if (empty($tb_array)) {
256                 return null;
257             } else {
258                 return $tb_array[0];
259             }
260         }
261
262         if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
263             foreach ($match[1] as $atag) {
264                 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
265                     return $url[1];
266                 }
267             }
268         }
269
270         return null;
271
272     }
273
274     function trackback($url, $endpoint)
275     {
276         $profile = $this->notice->getProfile();
277
278         // TRANS: Trackback title.
279         // TRANS: %1$s is a profile nickname, %2$s is a timestamp.
280         $args = array('title' => sprintf(_m('%1$s\'s status on %2$s'),
281                                          $profile->nickname,
282                                          common_exact_date($this->notice->created)),
283                       'excerpt' => $this->notice->content,
284                       'url' => $this->notice->getUrl(),
285                       'blog_name' => $profile->nickname);
286
287         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
288
289         $result = $fetcher->post($endpoint,
290                                  http_build_query($args),
291                                  array('User-Agent: ' . $this->userAgent()));
292
293         if ($result->status != '200') {
294             common_log(LOG_WARNING,
295                        "Trackback error for '$url' ($endpoint): ".
296                        "$result->body");
297         } else {
298             common_log(LOG_INFO,
299                        "Trackback success for '$url' ($endpoint): ".
300                        "'$result->body'");
301         }
302     }
303
304     public function version()
305     {
306         return LINKBACKPLUGIN_VERSION;
307     }
308
309     function onPluginVersion(array &$versions)
310     {
311         $versions[] = array('name' => 'Linkback',
312                             'version' => LINKBACKPLUGIN_VERSION,
313                             'author' => 'Evan Prodromou',
314                             'homepage' => 'http://status.net/wiki/Plugin:Linkback',
315                             'rawdescription' =>
316                             // TRANS: Plugin description.
317                             _m('Notify blog authors when their posts have been linked in '.
318                                'microblog notices using '.
319                                '<a href="http://www.hixie.ch/specs/pingback/pingback">Pingback</a> '.
320                                'or <a href="http://www.movabletype.org/docs/mttrackback.html">Trackback</a> protocols.'));
321         return true;
322     }
323
324     public function onStartInitializeRouter(URLMapper $m)
325     {
326         $m->connect('settings/linkback', array('action' => 'linkbacksettings'));
327         return true;
328     }
329
330     function onEndAccountSettingsNav($action)
331     {
332         $action_name = $action->trimmed('action');
333
334         $action->menuItem(common_local_url('linkbacksettings'),
335                           // TRANS: OpenID plugin menu item on user settings page.
336                           _m('MENU', 'Send Linkbacks'),
337                           // TRANS: OpenID plugin tooltip for user settings menu item.
338                           _m('Opt-out of sending linkbacks.'),
339                           $action_name === 'linkbacksettings');
340         return true;
341     }
342 }