]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/discovery.php
Merge branch '1.0.x' of git://gitorious.org/statusnet/mainline
[quix0rs-gnu-social.git] / lib / discovery.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * Use Hammer discovery stack to find out interesting things about an URI
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  * @category  Discovery
24  * @package   StatusNet
25  * @author    James Walker <james@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * This class implements LRDD-based service discovery based on the "Hammer Draft"
37  * (including webfinger)
38  *
39  * @category  Discovery
40  * @package   StatusNet
41  * @author    James Walker <james@status.net>
42  * @copyright 2010 StatusNet, Inc.
43  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
44  * @link      http://status.net/
45  *
46  * @see       http://groups.google.com/group/webfinger/browse_thread/thread/9f3d93a479e91bbf
47  */
48 class Discovery
49 {
50     const LRDD_REL    = 'lrdd';
51     const PROFILEPAGE = 'http://webfinger.net/rel/profile-page';
52     const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from';
53     const HCARD       = 'http://microformats.org/profile/hcard';
54
55     public $methods = array();
56
57     /**
58      * Constructor for a discovery object
59      *
60      * Registers different discovery methods.
61      *
62      * @return Discovery this
63      */
64
65     public function __construct()
66     {
67         $this->registerMethod('Discovery_LRDD_Host_Meta');
68         $this->registerMethod('Discovery_LRDD_Link_Header');
69         $this->registerMethod('Discovery_LRDD_Link_HTML');
70     }
71
72     /**
73      * Register a discovery class
74      *
75      * @param string $class Class name
76      *
77      * @return void
78      */
79     public function registerMethod($class)
80     {
81         $this->methods[] = $class;
82     }
83
84     /**
85      * Given a "user id" make sure it's normalized to either a webfinger
86      * acct: uri or a profile HTTP URL.
87      *
88      * @param string $user_id User ID to normalize
89      *
90      * @return string normalized acct: or http(s)?: URI
91      */
92     public static function normalize($user_id)
93     {
94         if (substr($user_id, 0, 5) == 'http:' ||
95             substr($user_id, 0, 6) == 'https:' ||
96             substr($user_id, 0, 5) == 'acct:') {
97             return $user_id;
98         }
99
100         if (strpos($user_id, '@') !== false) {
101             return 'acct:' . $user_id;
102         }
103
104         return 'http://' . $user_id;
105     }
106
107     /**
108      * Determine if a string is a Webfinger ID
109      *
110      * Webfinger IDs look like foo@example.com or acct:foo@example.com
111      *
112      * @param string $user_id ID to check
113      *
114      * @return boolean true if $user_id is a Webfinger, else false
115      */
116     public static function isWebfinger($user_id)
117     {
118         $uri = Discovery::normalize($user_id);
119
120         return (substr($uri, 0, 5) == 'acct:');
121     }
122
123     /**
124      * Given a user ID, return the first available XRD
125      *
126      * @param string $id User ID URI
127      *
128      * @return XRD XRD object for the user
129      */
130     public function lookup($id)
131     {
132         // Normalize the incoming $id to make sure we have a uri
133         $uri = $this->normalize($id);
134
135         foreach ($this->methods as $class) {
136             $links = call_user_func(array($class, 'discover'), $uri);
137             if ($link = Discovery::getService($links, Discovery::LRDD_REL)) {
138                 // Load the LRDD XRD
139                 if (!empty($link['template'])) {
140                     $xrd_uri = Discovery::applyTemplate($link['template'], $uri);
141                 } else {
142                     $xrd_uri = $link['href'];
143                 }
144
145                 $xrd = $this->fetchXrd($xrd_uri);
146                 if ($xrd) {
147                     return $xrd;
148                 }
149             }
150         }
151
152         // TRANS: Exception. %s is an ID.
153         throw new Exception(sprintf(_('Unable to find services for %s.'), $id));
154     }
155
156     /**
157      * Given an array of links, returns the matching service
158      *
159      * @param array  $links   Links to check
160      * @param string $service Service to find
161      *
162      * @return array $link assoc array representing the link
163      */
164     public static function getService($links, $service)
165     {
166         if (!is_array($links)) {
167             return false;
168         }
169
170         foreach ($links as $link) {
171             if ($link['rel'] == $service) {
172                 return $link;
173             }
174         }
175     }
176
177     /**
178      * Apply a template using an ID
179      *
180      * Replaces {uri} in template string with the ID given.
181      *
182      * @param string $template Template to match
183      * @param string $id       User ID to replace with
184      *
185      * @return string replaced values
186      */
187     public static function applyTemplate($template, $id)
188     {
189         $template = str_replace('{uri}', urlencode($id), $template);
190
191         return $template;
192     }
193
194     /**
195      * Fetch an XRD file and parse
196      *
197      * @param string $url URL of the XRD
198      *
199      * @return XRD object representing the XRD file
200      */
201     public static function fetchXrd($url)
202     {
203         try {
204             $client   = new HTTPClient();
205             $response = $client->get($url);
206         } catch (HTTP_Request2_Exception $e) {
207             return false;
208         }
209
210         if ($response->getStatus() != 200) {
211             return false;
212         }
213
214         return XRD::parse($response->getBody());
215     }
216 }
217
218 /**
219  * Abstract interface for discovery
220  *
221  * Objects that implement this interface can retrieve an array of
222  * XRD links for the URI.
223  *
224  * @category  Discovery
225  * @package   StatusNet
226  * @author    James Walker <james@status.net>
227  * @copyright 2010 StatusNet, Inc.
228  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
229  * @link      http://status.net/
230  */
231 interface Discovery_LRDD
232 {
233     /**
234      * Discover interesting info about the URI
235      *
236      * @param string $uri URI to inquire about
237      *
238      * @return array Links in the XRD file
239      */
240     public function discover($uri);
241 }
242
243 /**
244  * Implementation of discovery using host-meta file
245  *
246  * Discovers XRD file for a user by going to the organization's
247  * host-meta file and trying to find a template for LRDD.
248  *
249  * @category  Discovery
250  * @package   StatusNet
251  * @author    James Walker <james@status.net>
252  * @copyright 2010 StatusNet, Inc.
253  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
254  * @link      http://status.net/
255  */
256 class Discovery_LRDD_Host_Meta implements Discovery_LRDD
257 {
258     /**
259      * Discovery core method
260      *
261      * For Webfinger and HTTP URIs, fetch the host-meta file
262      * and look for LRDD templates
263      *
264      * @param string $uri URI to inquire about
265      *
266      * @return array Links in the XRD file
267      */
268     public function discover($uri)
269     {
270         if (Discovery::isWebfinger($uri)) {
271             // We have a webfinger acct: - start with host-meta
272             list($name, $domain) = explode('@', $uri);
273         } else {
274             $domain = parse_url($uri, PHP_URL_HOST);
275         }
276
277         $url = 'http://'. $domain .'/.well-known/host-meta';
278
279         $xrd = Discovery::fetchXrd($url);
280
281         if ($xrd) {
282             if ($xrd->host != $domain) {
283                 return false;
284             }
285
286             return $xrd->links;
287         }
288     }
289 }
290
291 /**
292  * Implementation of discovery using HTTP Link header
293  *
294  * Discovers XRD file for a user by fetching the URL and reading any
295  * Link: headers in the HTTP response.
296  *
297  * @category  Discovery
298  * @package   StatusNet
299  * @author    James Walker <james@status.net>
300  * @copyright 2010 StatusNet, Inc.
301  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
302  * @link      http://status.net/
303  */
304 class Discovery_LRDD_Link_Header implements Discovery_LRDD
305 {
306     /**
307      * Discovery core method
308      *
309      * For HTTP IDs fetch the URL and look for Link headers.
310      *
311      * @param string $uri URI to inquire about
312      *
313      * @return array Links in the XRD file
314      *
315      * @todo fail out of Webfinger URIs faster
316      */
317     public function discover($uri)
318     {
319         try {
320             $client   = new HTTPClient();
321             $response = $client->get($uri);
322         } catch (HTTP_Request2_Exception $e) {
323             return false;
324         }
325
326         if ($response->getStatus() != 200) {
327             return false;
328         }
329
330         $link_header = $response->getHeader('Link');
331         if (!$link_header) {
332             //            return false;
333         }
334
335         return array(Discovery_LRDD_Link_Header::parseHeader($link_header));
336     }
337
338     /**
339      * Given a string or array of headers, returns XRD-like assoc array
340      *
341      * @param string|array $header string or array of strings for headers
342      *
343      * @return array Link header in XRD-like format
344      */
345     protected static function parseHeader($header)
346     {
347         $lh = new LinkHeader($header);
348
349         return array('href' => $lh->href,
350                      'rel'  => $lh->rel,
351                      'type' => $lh->type);
352     }
353 }
354
355 /**
356  * Implementation of discovery using HTML <link> element
357  *
358  * Discovers XRD file for a user by fetching the URL and reading any
359  * <link> elements in the HTML response.
360  *
361  * @category  Discovery
362  * @package   StatusNet
363  * @author    James Walker <james@status.net>
364  * @copyright 2010 StatusNet, Inc.
365  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
366  * @link      http://status.net/
367  */
368 class Discovery_LRDD_Link_HTML implements Discovery_LRDD
369 {
370     /**
371      * Discovery core method
372      *
373      * For HTTP IDs, fetch the URL and look for <link> elements
374      * in the HTML response.
375      *
376      * @param string $uri URI to inquire about
377      *
378      * @return array Links in XRD-ish assoc array
379      *
380      * @todo fail out of Webfinger URIs faster
381      */
382     public function discover($uri)
383     {
384         try {
385             $client   = new HTTPClient();
386             $response = $client->get($uri);
387         } catch (HTTP_Request2_Exception $e) {
388             return false;
389         }
390
391         if ($response->getStatus() != 200) {
392             return false;
393         }
394
395         return Discovery_LRDD_Link_HTML::parse($response->getBody());
396     }
397
398     /**
399      * Parse HTML and return <link> elements
400      *
401      * Given an HTML string, scans the string for <link> elements
402      *
403      * @param string $html HTML to scan
404      *
405      * @return array array of associative arrays in XRD-ish format
406      */
407     public function parse($html)
408     {
409         $links = array();
410
411         preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
412         $head_html = $head_matches[2];
413
414         preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
415
416         foreach ($link_matches[0] as $link_html) {
417             $link_url  = null;
418             $link_rel  = null;
419             $link_type = null;
420
421             preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
422             if ( isset($rel_matches[3]) ) {
423                 $link_rel = $rel_matches[3];
424             } else if ( isset($rel_matches[1]) ) {
425                 $link_rel = $rel_matches[1];
426             }
427
428             preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
429             if ( isset($href_matches[3]) ) {
430                 $link_uri = $href_matches[3];
431             } else if ( isset($href_matches[1]) ) {
432                 $link_uri = $href_matches[1];
433             }
434
435             preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
436             if ( isset($type_matches[3]) ) {
437                 $link_type = $type_matches[3];
438             } else if ( isset($type_matches[1]) ) {
439                 $link_type = $type_matches[1];
440             }
441
442             $links[] = array(
443                 'href' => $link_url,
444                 'rel' => $link_rel,
445                 'type' => $link_type,
446             );
447         }
448
449         return $links;
450     }
451 }