]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LinkbackPlugin.php
escape slash in regexp
[quix0rs-gnu-social.git] / plugins / LinkbackPlugin.php
1 <?php
2 /**
3  * Laconica, 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   Laconica
24  * @author    Evan Prodromou <evan@controlyourself.ca>
25  * @copyright 2009 Control Yourself, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://laconi.ca/
28  */
29
30 if (!defined('LACONICA')) {
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  Laconica
46  * @author   Evan Prodromou <evan@controlyourself.ca>
47  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48  * @link     http://laconi.ca/
49  *
50  * @see      Event
51  */
52
53 class LinkbackPlugin extends Plugin
54 {
55     var $notice = null;
56
57     function __construct()
58     {
59         parent::__construct();
60     }
61
62     function onEndNoticeSave($notice)
63     {
64         if ($notice->is_local == 1) {
65             // Try to avoid actually mucking with the
66             // notice content
67             $c = $notice->content;
68             $this->notice = $notice;
69             // Ignoring results
70             common_replace_urls_callback($c,
71                                          array($this, 'linkbackUrl'));
72         }
73         return true;
74     }
75
76     function linkbackUrl($url)
77     {
78         $orig = $url;
79         $url = htmlspecialchars_decode($orig);
80         $scheme = parse_url($url, PHP_URL_SCHEME);
81         if (!in_array($scheme, array('http', 'https'))) {
82             return $orig;
83         }
84
85         // XXX: Do a HEAD first to save some time/bandwidth
86
87         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
88
89         $result = $fetcher->get($url,
90                                 array('User-Agent: ' . $this->userAgent(),
91                                       'Accept: application/html+xml,text/html'));
92
93         if (!in_array($result->status, array('200', '206'))) {
94             return $orig;
95         }
96
97         $pb = null;
98         $tb = null;
99
100         if (array_key_exists('X-Pingback', $result->headers)) {
101             $pb = $result->headers['X-Pingback'];
102         } else if (preg_match('/<link rel="pingback" href="([^"]+)" ?\/?>/',
103                               $result->body,
104                               $match)) {
105             $pb = $match[1];
106         }
107
108         if (!empty($pb)) {
109             $this->pingback($result->final_url, $pb);
110         } else {
111             $tb = $this->getTrackback($result->body, $result->final_url);
112             if (!empty($tb)) {
113                 $this->trackback($result->final_url, $tb);
114             }
115         }
116
117         return $orig;
118     }
119
120     function pingback($url, $endpoint)
121     {
122         $args = array($this->notice->uri, $url);
123
124         $request = xmlrpc_encode_request('pingback.ping', $args);
125         $context = stream_context_create(array('http' => array('method' => "POST",
126                                                                'header' =>
127                                                                "Content-Type: text/xml\r\n".
128                                                                "User-Agent: " . $this->userAgent(),
129                                                                'content' => $request)));
130         $file = file_get_contents($endpoint, false, $context);
131         $response = xmlrpc_decode($file);
132         if (xmlrpc_is_fault($response)) {
133             common_log(LOG_WARNING,
134                        "Pingback error for '$url' ($endpoint): ".
135                        "$response[faultString] ($response[faultCode])");
136         } else {
137             common_log(LOG_INFO,
138                        "Pingback success for '$url' ($endpoint): ".
139                        "'$response'");
140         }
141     }
142
143     // Largely cadged from trackback_cls.php by
144     // Ran Aroussi <ran@blogish.org>, GPL2
145     // http://phptrackback.sourceforge.net/
146
147     function getTrackback($text, $url)
148     {
149         if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $text, $match, PREG_SET_ORDER)) {
150             for ($i = 0; $i < count($match); $i++) {
151                 if (preg_match('|dc:identifier="' . preg_quote($url) . '"|ms', $match[$i][1])) {
152                     $rdf_array[] = trim($match[$i][1]);
153                 }
154             }
155
156             // Loop through the RDFs array and extract trackback URIs
157
158             $tb_array = array(); // <- holds list of trackback URIs
159
160             if (!empty($rdf_array)) {
161
162                 for ($i = 0; $i < count($rdf_array); $i++) {
163                     if (preg_match('/trackback:ping="([^"]+)"/', $rdf_array[$i], $array)) {
164                         $tb_array[] = trim($array[1]);
165                         break;
166                     }
167                 }
168             }
169
170             // Return Trackbacks
171
172             if (empty($tb_array)) {
173                 return null;
174             } else {
175                 return $tb_array[0];
176             }
177         }
178
179         if (preg_match_all('/(<a[^>]*?rel=[\'"]trackback[\'"][^>]*?>)/', $text, $match)) {
180             foreach ($match[1] as $atag) {
181                 if (preg_match('/href=[\'"]([^\'"]*?)[\'"]/', $atag, $url)) {
182                     return $url[1];
183                 }
184             }
185         }
186
187         return null;
188
189     }
190
191     function trackback($url, $endpoint)
192     {
193         $profile = $this->notice->getProfile();
194
195         $args = array('title' => sprintf(_('%1$s\'s status on %2$s'),
196                                          $profile->nickname,
197                                          common_exact_date($this->notice->created)),
198                       'excerpt' => $this->notice->content,
199                       'url' => $this->notice->uri,
200                       'blog_name' => $profile->nickname);
201
202         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
203
204         $result = $fetcher->post($endpoint,
205                                  http_build_query($args),
206                                  array('User-Agent: ' . $this->userAgent()));
207
208         if ($result->status != '200') {
209             common_log(LOG_WARNING,
210                        "Trackback error for '$url' ($endpoint): ".
211                        "$result->body");
212         } else {
213             common_log(LOG_INFO,
214                        "Trackback success for '$url' ($endpoint): ".
215                        "'$result->body'");
216         }
217     }
218
219     function userAgent()
220     {
221         return 'LinkbackPlugin/'.LINKBACKPLUGIN_VERSION .
222           ' Laconica/' . LACONICA_VERSION;
223     }
224 }