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