]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/discovery.php
Change the workflow to get better discovery
[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             return false;
159         }
160
161         // We have a webfinger acct: - start with host-meta
162         list($name, $domain) = explode('@', $uri);
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($uri);
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($link_header);
198     }
199
200     protected static function parseHeader($header)
201     {
202         $lh = new LinkHeader($header);
203
204         return array('href' => $lh->href,
205                      'rel'  => $lh->rel,
206                      'type' => $lh->type);
207     }
208 }
209
210 class Discovery_LRDD_Link_HTML implements Discovery_LRDD
211 {
212     public function discover($uri)
213     {
214         try {
215             $client = new HTTPClient();
216             $response = $client->get($uri);
217         } catch (HTTP_Request2_Exception $e) {
218             return false;
219         }
220
221         if ($response->getStatus() != 200) {
222             return false;
223         }
224
225         return Discovery_LRDD_Link_HTML::parse($response->getBody());
226     }
227
228     public function parse($html)
229     {
230         $links = array();
231
232         preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
233         $head_html = $head_matches[2];
234
235         preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
236
237         foreach ($link_matches[0] as $link_html) {
238             $link_url = null;
239             $link_rel = null;
240             $link_type = null;
241
242             preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
243             if ( isset($rel_matches[3]) ) {
244                 $link_rel = $rel_matches[3];
245             } else if ( isset($rel_matches[1]) ) {
246                 $link_rel = $rel_matches[1];
247             }
248
249             preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
250             if ( isset($href_matches[3]) ) {
251                 $link_uri = $href_matches[3];
252             } else if ( isset($href_matches[1]) ) {
253                 $link_uri = $href_matches[1];
254             }
255
256             preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
257             if ( isset($type_matches[3]) ) {
258                 $link_type = $type_matches[3];
259             } else if ( isset($type_matches[1]) ) {
260                 $link_type = $type_matches[1];
261             }
262
263             $links[] = array(
264                 'href' => $link_url,
265                 'rel' => $link_rel,
266                 'type' => $link_type,
267             );
268         }
269
270         return $links;
271     }
272 }