]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/LinkbackPlugin.php
Merge branch 'master' into testing
[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             // Ignoring results
69             common_replace_urls_callback($c,
70                                          array($this, 'linkbackUrl'));
71         }
72         return true;
73     }
74
75     function linkbackUrl($url)
76     {
77         common_log(LOG_DEBUG,"Attempting linkback for " . $url);
78
79         $orig = $url;
80         $url = htmlspecialchars_decode($orig);
81         $scheme = parse_url($url, PHP_URL_SCHEME);
82         if (!in_array($scheme, array('http', 'https'))) {
83             return $orig;
84         }
85
86         // XXX: Do a HEAD first to save some time/bandwidth
87
88         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
89
90         $result = $fetcher->get($url,
91                                 array('User-Agent: ' . $this->userAgent(),
92                                       'Accept: application/html+xml,text/html'));
93
94         if (!in_array($result->status, array('200', '206'))) {
95             return $orig;
96         }
97
98         $pb = null;
99         $tb = null;
100
101         if (array_key_exists('X-Pingback', $result->headers)) {
102             $pb = $result->headers['X-Pingback'];
103         } else if (preg_match('/<link rel="pingback" href="([^"]+)" ?\/?>/',
104                               $result->body,
105                               $match)) {
106             $pb = $match[1];
107         }
108
109         if (!empty($pb)) {
110             $this->pingback($result->final_url, $pb);
111         } else {
112             $tb = $this->getTrackback($result->body, $result->final_url);
113             if (!empty($tb)) {
114                 $this->trackback($result->final_url, $tb);
115             }
116         }
117
118         return $orig;
119     }
120
121     function pingback($url, $endpoint)
122     {
123         $args = array($this->notice->uri, $url);
124
125         if (!extension_loaded('xmlrpc')) {
126             if (!dl('xmlrpc.so')) {
127                 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
128                 return;
129             }
130         }
131
132         $request = HTTPClient::start();
133         try {
134             $response = $request->post($endpoint,
135                 array('Content-Type: text/xml'),
136                 xmlrpc_encode_request('pingback.ping', $args));
137             $response = xmlrpc_decode($response->getBody());
138             if (xmlrpc_is_fault($response)) {
139                 common_log(LOG_WARNING,
140                        "Pingback error for '$url' ($endpoint): ".
141                        "$response[faultString] ($response[faultCode])");
142             } else {
143                 common_log(LOG_INFO,
144                        "Pingback success for '$url' ($endpoint): ".
145                        "'$response'");
146             }
147         } catch (HTTP_Request2_Exception $e) {
148             common_log(LOG_WARNING,
149                    "Pingback request failed for '$url' ($endpoint)");
150         }
151     }
152
153     // Largely cadged from trackback_cls.php by
154     // Ran Aroussi <ran@blogish.org>, GPL2 or any later version
155     // http://phptrackback.sourceforge.net/
156     function getTrackback($text, $url)
157     {
158         if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
159             for ($i = 0; $i < count($match); $i++) {
160                 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
161                     $rdf_array[] = trim($match[$i][1]);
162                 }
163             }
164
165             // Loop through the RDFs array and extract trackback URIs
166
167             $tb_array = array(); // <- holds list of trackback URIs
168
169             if (!empty($rdf_array)) {
170
171                 for ($i = 0; $i < count($rdf_array); $i++) {
172                     if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
173                         $tb_array[] = trim($array[1]);
174                         break;
175                     }
176                 }
177             }
178
179             // Return Trackbacks
180
181             if (empty($tb_array)) {
182                 return null;
183             } else {
184                 return $tb_array[0];
185             }
186         }
187
188         if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
189             foreach ($match[1] as $atag) {
190                 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
191                     return $url[1];
192                 }
193             }
194         }
195
196         return null;
197
198     }
199
200     function trackback($url, $endpoint)
201     {
202         $profile = $this->notice->getProfile();
203
204         // TRANS: Trackback title.
205         // TRANS: %1$s is a profile nickname, %2$s is a timestamp.
206         $args = array('title' => sprintf(_m('%1$s\'s status on %2$s'),
207                                          $profile->nickname,
208                                          common_exact_date($this->notice->created)),
209                       'excerpt' => $this->notice->content,
210                       'url' => $this->notice->uri,
211                       'blog_name' => $profile->nickname);
212
213         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
214
215         $result = $fetcher->post($endpoint,
216                                  http_build_query($args),
217                                  array('User-Agent: ' . $this->userAgent()));
218
219         if ($result->status != '200') {
220             common_log(LOG_WARNING,
221                        "Trackback error for '$url' ($endpoint): ".
222                        "$result->body");
223         } else {
224             common_log(LOG_INFO,
225                        "Trackback success for '$url' ($endpoint): ".
226                        "'$result->body'");
227         }
228     }
229
230     function userAgent()
231     {
232         return 'LinkbackPlugin/'.LINKBACKPLUGIN_VERSION .
233           ' StatusNet/' . STATUSNET_VERSION;
234     }
235
236     function onPluginVersion(&$versions)
237     {
238         $versions[] = array('name' => 'Linkback',
239                             'version' => LINKBACKPLUGIN_VERSION,
240                             'author' => 'Evan Prodromou',
241                             'homepage' => 'http://status.net/wiki/Plugin:Linkback',
242                             'rawdescription' =>
243                             // TRANS: Plugin description.
244                             _m('Notify blog authors when their posts have been linked in '.
245                                'microblog notices using '.
246                                '<a href="http://www.hixie.ch/specs/pingback/pingback">Pingback</a> '.
247                                'or <a href="http://www.movabletype.org/docs/mttrackback.html">Trackback</a> protocols.'));
248         return true;
249     }
250 }