]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/discovery.php
8aba31328e5af18969f6312ddba0c1d4b56af2a7
[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
43     public $methods = array();
44
45     public function __construct()
46     {
47         $this->registerMethod('Discovery_LRDD_Host_Meta');
48         $this->registerMethod('Discovery_LRDD_Link_Header');
49         $this->registerMethod('Discovery_LRDD_Link_HTML');
50     }
51
52
53     public function registerMethod($class)
54     {
55         $this->methods[] = $class;
56     }
57     
58     /**
59      * Given a "user id" make sure it's normalized to either a webfinger
60      * acct: uri or a profile HTTP URL.
61      */
62     public static function normalize($user_id)
63     {
64         if (substr($user_id, 0, 5) == 'http:' ||
65             substr($user_id, 0, 6) == 'https:' ||
66             substr($user_id, 0, 5) == 'acct:') {
67             return $user_id;
68         }
69
70         if (strpos($user_id, '@') !== FALSE) {
71             return 'acct:' . $user_id;
72         }
73
74         return 'http://' . $user_id;
75     }
76
77     public static function isWebfinger($user_id)
78     {
79         $uri = Discovery::normalize($user_id);
80         
81         return (substr($uri, 0, 5) == 'acct:');
82     }
83
84     /**
85      * This implements the actual lookup procedure
86      */
87     public function lookup($id)
88     {
89         // Normalize the incoming $id to make sure we have a uri
90         $uri = $this->normalize($id);
91
92         foreach ($this->methods as $class) {
93             $links = call_user_func(array($class, 'discover'), $uri);
94
95             if ($link = Discovery::getService($links, Discovery::LRDD_REL)) {
96                 // Load the LRDD XRD
97                 if ($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         foreach ($links as $link) {
115             if ($link['rel'] == $service) {
116                 return $link;
117             }
118         }
119     }
120     
121
122     public static function applyTemplate($template, $id)
123     {
124         $template = str_replace('{uri}', urlencode($id), $template);
125
126         return $template;
127     }
128
129     
130     public static function fetchXrd($url)
131     {
132         try {
133             $client = new HTTPClient();
134             $response = $client->get($url);
135         } catch (HTTP_Request2_Exception $e) {
136             return false;
137         }
138
139         if ($response->getStatus() != 200) {
140             return false;
141         }
142
143         return XRD::parse($response->getBody());
144     }    
145 }
146
147 interface Discovery_LRDD
148 {
149     public function discover($uri);
150 }
151
152 class Discovery_LRDD_Host_Meta implements Discovery_LRDD
153 {
154     public function discover($uri)
155     {
156         if (Discovery::isWebfinger($uri)) {
157             // We have a webfinger acct: - start with host-meta
158             list($name, $domain) = explode('@', $id);
159         } else {
160             $domain = @parse_url($uri, PHP_URL_HOST);
161         }
162
163         $url = 'http://'. $domain .'/.well-known/host-meta';
164
165         $xrd = Discovery::fetchXrd($url);
166
167         if ($xrd) {
168             if ($xrd->host != $domain) {
169                 return false;
170             }
171             
172             return $xrd->links;
173         }
174     }
175 }
176
177 class Discovery_LRDD_Link_Header implements Discovery_LRDD
178 {
179     public function discover($uri)
180     {
181         try {
182             $client = new HTTPClient();
183             $response = $client->get($url);
184         } catch (HTTP_Request2_Exception $e) {
185             return false;
186         }
187
188         if ($response->getStatus() != 200) {
189             return false;
190         }
191
192         $link_header = $response->getHeader('Link');
193         if (!$link_header) {
194             return false;
195         }
196         
197         return Discovery_LRDD_Link_Header::parseHeader($header);
198     }
199
200     protected static function parseHeader($header)
201     {
202         preg_match('/^<[^>]+>/', $header, $uri_reference);
203         if (empty($uri_reference)) return;
204         
205         $link_uri = trim($uri_reference[0], '<>');
206         $link_rel = array();
207         $link_type = null;
208         
209         // remove uri-reference from header
210         $header = substr($header, strlen($uri_reference[0]));
211         
212         // parse link-params
213         $params = explode($header, ';');
214         
215         foreach ($params as $param) {
216             if (empty($param)) continue;
217             list($param_name, $param_value) = explode('=', $param, 2);
218             $param_name = trim($param_name);
219             $param_value = preg_replace('(^"|"$)', '', trim($param_value));
220             
221             // for now we only care about 'rel' and 'type' link params
222             // TODO do something with the other links-params
223             switch ($param_name) {
224             case 'rel':
225                 $link_rel = trim($param_value);
226                 break;
227                 
228             case 'type':
229                 $link_type = trim($param_value);
230             }
231         }
232         
233         return array(
234             'href' => $link_uri,
235             'rel' => $link_rel,
236             'type' => $link_type);
237     }
238 }
239
240 class Discovery_LRDD_Link_HTML implements Discovery_LRDD
241 {
242     public function discover($uri)
243     {
244         try {
245             $client = new HTTPClient();
246             $response = $client->get($url);
247         } catch (HTTP_Request2_Exception $e) {
248             return false;
249         }
250
251         if ($response->getStatus() != 200) {
252             return false;
253         }
254
255         return Discovery_LRDD_Link_HTML::parse($response->getBody());
256     }
257
258
259     public function parse($html)
260     {
261         $links = array();
262         
263         preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
264         $head_html = $head_matches[2];
265         
266         preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
267         
268         foreach ($link_matches[0] as $link_html) {
269             $link_url = null;
270             $link_rel = null;
271             $link_type = null;
272             
273             preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
274             if ( isset($rel_matches[3]) ) {
275                 $link_rel = $rel_matches[3];
276             } else if ( isset($rel_matches[1]) ) {
277                 $link_rel = $rel_matches[1];
278             }
279             
280             preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
281             if ( isset($href_matches[3]) ) {
282                 $link_uri = $href_matches[3];
283             } else if ( isset($href_matches[1]) ) {
284                 $link_uri = $href_matches[1];
285             }
286             
287             preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
288             if ( isset($type_matches[3]) ) {
289                 $link_type = $type_matches[3];
290             } else if ( isset($type_matches[1]) ) {
291                 $link_type = $type_matches[1];
292             }
293             
294             $links[] = array(
295                 'href' => $link_url,
296                 'rel' => $link_rel,
297                 'type' => $link_type,
298             );
299         }
300         
301         return $links;
302     }
303 }