]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/discovery.php
Merge branch '0.9.x' of git@gitorious.org:statusnet/mainline into 1.0.x
[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     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             if ($link = Discovery::getService($links, Discovery::LRDD_REL)) {
95                 // Load the LRDD XRD
96                 if (!empty($link['template'])) {
97                     $xrd_uri = Discovery::applyTemplate($link['template'], $uri);
98                 } else {
99                     $xrd_uri = $link['href'];
100                 }
101
102                 $xrd = $this->fetchXrd($xrd_uri);
103                 if ($xrd) {
104                     return $xrd;
105                 }
106             }
107         }
108
109         throw new Exception('Unable to find services for '. $id);
110     }
111
112     public static function getService($links, $service) {
113         if (!is_array($links)) {
114             return false;
115         }
116
117         foreach ($links as $link) {
118             if ($link['rel'] == $service) {
119                 return $link;
120             }
121         }
122     }
123
124     public static function applyTemplate($template, $id)
125     {
126         $template = str_replace('{uri}', urlencode($id), $template);
127
128         return $template;
129     }
130
131     public static function fetchXrd($url)
132     {
133         try {
134             $client = new HTTPClient();
135             $response = $client->get($url);
136         } catch (HTTP_Request2_Exception $e) {
137             return false;
138         }
139
140         if ($response->getStatus() != 200) {
141             return false;
142         }
143
144         return XRD::parse($response->getBody());
145     }
146 }
147
148 interface Discovery_LRDD
149 {
150     public function discover($uri);
151 }
152
153 class Discovery_LRDD_Host_Meta implements Discovery_LRDD
154 {
155     public function discover($uri)
156     {
157         if (Discovery::isWebfinger($uri)) {
158             // We have a webfinger acct: - start with host-meta
159             list($name, $domain) = explode('@', $uri);
160         } else {
161             $domain = parse_url($uri, PHP_URL_HOST);
162         }
163         
164         $url = 'http://'. $domain .'/.well-known/host-meta';
165
166         $xrd = Discovery::fetchXrd($url);
167
168         if ($xrd) {
169             if ($xrd->host != $domain) {
170                 return false;
171             }
172
173             return $xrd->links;
174         }
175     }
176 }
177
178 class Discovery_LRDD_Link_Header implements Discovery_LRDD
179 {
180     public function discover($uri)
181     {
182         try {
183             $client = new HTTPClient();
184             $response = $client->get($uri);
185         } catch (HTTP_Request2_Exception $e) {
186             return false;
187         }
188
189         if ($response->getStatus() != 200) {
190             return false;
191         }
192
193         $link_header = $response->getHeader('Link');
194         if (!$link_header) {
195             //            return false;
196         }
197
198         return array(Discovery_LRDD_Link_Header::parseHeader($link_header));
199     }
200
201     protected static function parseHeader($header)
202     {
203         $lh = new LinkHeader($header);
204
205         return array('href' => $lh->href,
206                      'rel'  => $lh->rel,
207                      'type' => $lh->type);
208     }
209 }
210
211 class Discovery_LRDD_Link_HTML implements Discovery_LRDD
212 {
213     public function discover($uri)
214     {
215         try {
216             $client = new HTTPClient();
217             $response = $client->get($uri);
218         } catch (HTTP_Request2_Exception $e) {
219             return false;
220         }
221
222         if ($response->getStatus() != 200) {
223             return false;
224         }
225
226         return Discovery_LRDD_Link_HTML::parse($response->getBody());
227     }
228
229     public function parse($html)
230     {
231         $links = array();
232
233         preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
234         $head_html = $head_matches[2];
235
236         preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
237
238         foreach ($link_matches[0] as $link_html) {
239             $link_url = null;
240             $link_rel = null;
241             $link_type = null;
242
243             preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
244             if ( isset($rel_matches[3]) ) {
245                 $link_rel = $rel_matches[3];
246             } else if ( isset($rel_matches[1]) ) {
247                 $link_rel = $rel_matches[1];
248             }
249
250             preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
251             if ( isset($href_matches[3]) ) {
252                 $link_uri = $href_matches[3];
253             } else if ( isset($href_matches[1]) ) {
254                 $link_uri = $href_matches[1];
255             }
256
257             preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
258             if ( isset($type_matches[3]) ) {
259                 $link_type = $type_matches[3];
260             } else if ( isset($type_matches[1]) ) {
261                 $link_type = $type_matches[1];
262             }
263
264             $links[] = array(
265                 'href' => $link_url,
266                 'rel' => $link_rel,
267                 'type' => $link_type,
268             );
269         }
270
271         return $links;
272     }
273 }