]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/discovery.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / plugins / OStatus / lib / discovery.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * A sample module to show best practices for StatusNet plugins
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @package   StatusNet
24  * @author    James Walker <james@status.net>
25  * @copyright 2010 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
27  * @link      http://status.net/
28  */
29
30 /**
31  * This class implements LRDD-based service discovery based on the "Hammer Draft"
32  * (including webfinger)
33  *
34  * @see http://groups.google.com/group/webfinger/browse_thread/thread/9f3d93a479e91bbf
35  */
36 class Discovery
37 {
38
39     const LRDD_REL = 'lrdd';
40     const PROFILEPAGE = 'http://webfinger.net/rel/profile-page';
41     const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from';
42     const HCARD = 'http://microformats.org/profile/hcard';
43     
44     public $methods = array();
45
46     public function __construct()
47     {
48         $this->registerMethod('Discovery_LRDD_Host_Meta');
49         $this->registerMethod('Discovery_LRDD_Link_Header');
50         $this->registerMethod('Discovery_LRDD_Link_HTML');
51     }
52
53
54     public function registerMethod($class)
55     {
56         $this->methods[] = $class;
57     }
58     
59     /**
60      * Given a "user id" make sure it's normalized to either a webfinger
61      * acct: uri or a profile HTTP URL.
62      */
63     public static function normalize($user_id)
64     {
65         if (substr($user_id, 0, 5) == 'http:' ||
66             substr($user_id, 0, 6) == 'https:' ||
67             substr($user_id, 0, 5) == 'acct:') {
68             return $user_id;
69         }
70
71         if (strpos($user_id, '@') !== FALSE) {
72             return 'acct:' . $user_id;
73         }
74
75         return 'http://' . $user_id;
76     }
77
78     public static function isWebfinger($user_id)
79     {
80         $uri = Discovery::normalize($user_id);
81         
82         return (substr($uri, 0, 5) == 'acct:');
83     }
84
85     /**
86      * This implements the actual lookup procedure
87      */
88     public function lookup($id)
89     {
90         // Normalize the incoming $id to make sure we have a uri
91         $uri = $this->normalize($id);
92
93         foreach ($this->methods as $class) {
94             $links = call_user_func(array($class, 'discover'), $uri);
95             if ($link = Discovery::getService($links, Discovery::LRDD_REL)) {
96                 // Load the LRDD XRD
97                 if (!empty($link['template'])) {
98                     $xrd_uri = Discovery::applyTemplate($link['template'], $uri);
99                 } else {
100                     $xrd_uri = $link['href'];
101                 }
102                 
103                 $xrd = $this->fetchXrd($xrd_uri);
104                 if ($xrd) {
105                     return $xrd;
106                 }
107             }
108         }
109
110         throw new Exception('Unable to find services for '. $id);
111     }
112
113     public static function getService($links, $service) {
114         if (!is_array($links)) {
115             return false;
116         }
117         
118         foreach ($links as $link) {
119             if ($link['rel'] == $service) {
120                 return $link;
121             }
122         }
123     }
124     
125
126     public static function applyTemplate($template, $id)
127     {
128         $template = str_replace('{uri}', urlencode($id), $template);
129
130         return $template;
131     }
132
133     
134     public static function fetchXrd($url)
135     {
136         try {
137             $client = new HTTPClient();
138             $response = $client->get($url);
139         } catch (HTTP_Request2_Exception $e) {
140             return false;
141         }
142
143         if ($response->getStatus() != 200) {
144             return false;
145         }
146
147         return XRD::parse($response->getBody());
148     }
149 }
150
151 interface Discovery_LRDD
152 {
153     public function discover($uri);
154 }
155
156 class Discovery_LRDD_Host_Meta implements Discovery_LRDD
157 {
158     public function discover($uri)
159     {
160         if (!Discovery::isWebfinger($uri)) {
161             return false;
162         }
163
164         // We have a webfinger acct: - start with host-meta
165         list($name, $domain) = explode('@', $uri);
166         $url = 'http://'. $domain .'/.well-known/host-meta';
167
168         $xrd = Discovery::fetchXrd($url);
169
170         if ($xrd) {
171             if ($xrd->host != $domain) {
172                 return false;
173             }
174             
175             return $xrd->links;
176         }
177     }
178 }
179
180 class Discovery_LRDD_Link_Header implements Discovery_LRDD
181 {
182     public function discover($uri)
183     {
184         try {
185             $client = new HTTPClient();
186             $response = $client->get($uri);
187         } catch (HTTP_Request2_Exception $e) {
188             return false;
189         }
190              
191         if ($response->getStatus() != 200) {
192             return false;
193         }
194
195         $link_header = $response->getHeader('Link');
196         if (!$link_header) {
197             //            return false;
198         }
199         
200         return Discovery_LRDD_Link_Header::parseHeader($link_header);
201     }
202
203     protected static function parseHeader($header)
204     {
205         preg_match('/^<[^>]+>/', $header, $uri_reference);
206         //if (empty($uri_reference)) return;
207
208         $links = array();
209         
210         $link_uri = trim($uri_reference[0], '<>');
211         $link_rel = array();
212         $link_type = null;
213         
214         // remove uri-reference from header
215         $header = substr($header, strlen($uri_reference[0]));
216         
217         // parse link-params
218         $params = explode(';', $header);
219         
220         foreach ($params as $param) {
221             if (empty($param)) continue;
222             list($param_name, $param_value) = explode('=', $param, 2);
223             $param_name = trim($param_name);
224             $param_value = preg_replace('(^"|"$)', '', trim($param_value));
225             
226             // for now we only care about 'rel' and 'type' link params
227             // TODO do something with the other links-params
228             switch ($param_name) {
229             case 'rel':
230                 $link_rel = trim($param_value);
231                 break;
232                 
233             case 'type':
234                 $link_type = trim($param_value);
235             }
236         }
237
238         $links[] =  array(
239             'href' => $link_uri,
240             'rel' => $link_rel,
241             'type' => $link_type);
242
243         return $links;
244     }
245 }
246
247 class Discovery_LRDD_Link_HTML implements Discovery_LRDD
248 {
249     public function discover($uri)
250     {
251         try {
252             $client = new HTTPClient();
253             $response = $client->get($uri);
254         } catch (HTTP_Request2_Exception $e) {
255             return false;
256         }
257
258         if ($response->getStatus() != 200) {
259             return false;
260         }
261
262         return Discovery_LRDD_Link_HTML::parse($response->getBody());
263     }
264
265
266     public function parse($html)
267     {
268         $links = array();
269         
270         preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
271         $head_html = $head_matches[2];
272         
273         preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
274         
275         foreach ($link_matches[0] as $link_html) {
276             $link_url = null;
277             $link_rel = null;
278             $link_type = null;
279             
280             preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
281             if ( isset($rel_matches[3]) ) {
282                 $link_rel = $rel_matches[3];
283             } else if ( isset($rel_matches[1]) ) {
284                 $link_rel = $rel_matches[1];
285             }
286             
287             preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
288             if ( isset($href_matches[3]) ) {
289                 $link_uri = $href_matches[3];
290             } else if ( isset($href_matches[1]) ) {
291                 $link_uri = $href_matches[1];
292             }
293             
294             preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
295             if ( isset($type_matches[3]) ) {
296                 $link_type = $type_matches[3];
297             } else if ( isset($type_matches[1]) ) {
298                 $link_type = $type_matches[1];
299             }
300             
301             $links[] = array(
302                 'href' => $link_url,
303                 'rel' => $link_rel,
304                 'type' => $link_type,
305             );
306         }
307         
308         return $links;
309     }
310 }