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