]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/openid.php
Merge branch 'master' of git.gnu.io:gnu/gnu-social into nightly
[quix0rs-gnu-social.git] / plugins / OpenID / openid.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 require_once('Auth/OpenID.php');
25 require_once('Auth/OpenID/Consumer.php');
26 require_once('Auth/OpenID/Server.php');
27 require_once('Auth/OpenID/SReg.php');
28 require_once('Auth/OpenID/MySQLStore.php');
29
30 // About one year cookie expiry
31
32 define('OPENID_COOKIE_EXPIRY', round(365.25 * 24 * 60 * 60));
33 define('OPENID_COOKIE_KEY', 'lastusedopenid');
34
35 function oid_store()
36 {
37     static $store = null;
38     if (!$store) {
39         // Can't be called statically
40         $user = new User();
41         $conn = $user->getDatabaseConnection();
42         $store = new Auth_OpenID_MySQLStore($conn);
43     }
44     return $store;
45 }
46
47 function oid_consumer()
48 {
49     $store = oid_store();
50     $consumer = new Auth_OpenID_Consumer($store);
51     return $consumer;
52 }
53
54 function oid_server()
55 {
56     $store = oid_store();
57     $server = new Auth_OpenID_Server($store, common_local_url('openidserver'));
58     return $server;
59 }
60
61 function oid_clear_last()
62 {
63     oid_set_last('');
64 }
65
66 function oid_set_last($openid_url)
67 {
68     common_set_cookie(OPENID_COOKIE_KEY,
69                      $openid_url,
70                      time() + OPENID_COOKIE_EXPIRY);
71 }
72
73 function oid_get_last()
74 {
75     if (empty($_COOKIE[OPENID_COOKIE_KEY])) {
76         return null;
77     }
78     $openid_url = $_COOKIE[OPENID_COOKIE_KEY];
79     if ($openid_url && strlen($openid_url) > 0) {
80         return $openid_url;
81     } else {
82         return null;
83     }
84 }
85
86 function oid_link_user($id, $canonical, $display)
87 {
88     global $_PEAR;
89
90     $oid = new User_openid();
91     $oid->user_id = $id;
92     $oid->canonical = $canonical;
93     $oid->display = $display;
94     $oid->created = common_sql_now();
95
96     if (!$oid->insert()) {
97         $err = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
98         return false;
99     }
100
101     return true;
102 }
103
104 function oid_get_user($openid_url)
105 {
106     $user = null;
107     $oid = User_openid::getKV('canonical', $openid_url);
108     if ($oid) {
109         $user = User::getKV('id', $oid->user_id);
110     }
111     return $user;
112 }
113
114 function oid_check_immediate($openid_url, $backto=null)
115 {
116     if (!$backto) {
117         $action = $_REQUEST['action'];
118         $args = common_copy_args($_GET);
119         unset($args['action']);
120         $backto = common_local_url($action, $args);
121     }
122
123     common_ensure_session();
124
125     $_SESSION['openid_immediate_backto'] = $backto;
126
127     oid_authenticate($openid_url,
128                      'finishimmediate',
129                      true);
130 }
131
132 function oid_authenticate($openid_url, $returnto, $immediate=false)
133 {
134     $openid_url = Auth_OpenID::normalizeUrl($openid_url);
135     if (!common_valid_http_url($openid_url)) {
136         throw new ClientException(_m('No valid URL provided for OpenID.'));
137     }
138
139     $consumer = oid_consumer();
140
141     if (!$consumer) {
142         // TRANS: OpenID plugin server error.
143         throw new ServerException(_m('Cannot instantiate OpenID consumer object.'));
144     }
145
146     common_ensure_session();
147
148     $auth_request = $consumer->begin($openid_url);
149
150     // Handle failure status return values.
151     if (!$auth_request) {
152         common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
153         // TRANS: OpenID plugin message. Given when an OpenID is not valid.
154         throw new ServerException(_m('Not a valid OpenID.'));
155     } else if (Auth_OpenID::isFailure($auth_request)) {
156         common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
157         // TRANS: OpenID plugin server error. Given when the OpenID authentication request fails.
158         // TRANS: %s is the failure message.
159         throw new ServerException(sprintf(_m('OpenID failure: %s.'), $auth_request->message));
160     }
161
162     $sreg_request = Auth_OpenID_SRegRequest::build(// Required
163                                                    array(),
164                                                    // Optional
165                                                    array('nickname',
166                                                          'email',
167                                                          'fullname',
168                                                          'language',
169                                                          'timezone',
170                                                          'postcode',
171                                                          'country'));
172
173     if ($sreg_request) {
174         $auth_request->addExtension($sreg_request);
175     }
176
177     $requiredTeam = common_config('openid', 'required_team');
178     if ($requiredTeam) {
179         // LaunchPad OpenID extension
180         $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
181         if ($team_request) {
182             $auth_request->addExtension($team_request);
183         }
184     }
185
186     $trust_root = common_root_url(true);
187     $process_url = common_local_url($returnto);
188
189     // Net::OpenID::Server as used on LiveJournal appears to incorrectly
190     // reject POST requests for data submissions that OpenID 1.1 specs
191     // as GET, although 2.0 allows them:
192     // https://rt.cpan.org/Public/Bug/Display.html?id=42202
193     //
194     // Our OpenID libraries would have switched in the redirect automatically
195     // if it were detecting 1.1 compatibility mode, however the server is
196     // advertising itself as 2.0-compatible, so we got switched to the POST.
197     //
198     // Since the GET should always work anyway, we'll just take out the
199     // autosubmitter for now.
200     // 
201     //if ($auth_request->shouldSendRedirect()) {
202         $redirect_url = $auth_request->redirectURL($trust_root,
203                                                    $process_url,
204                                                    $immediate);
205         if (Auth_OpenID::isFailure($redirect_url)) {
206             // TRANS: OpenID plugin server error. Given when the OpenID authentication request cannot be redirected.
207             // TRANS: %s is the failure message.
208             throw new ServerException(sprintf(_m('Could not redirect to server: %s.'), $redirect_url->message));
209         }
210         common_redirect($redirect_url, 303);
211     /*
212     } else {
213         // Generate form markup and render it.
214         $form_id = 'openid_message';
215         $form_html = $auth_request->formMarkup($trust_root, $process_url,
216                                                $immediate, array('id' => $form_id));
217
218         // XXX: This is cheap, but things choke if we don't escape ampersands
219         // in the HTML attributes
220
221         $form_html = preg_replace('/&/', '&amp;', $form_html);
222
223         // Display an error if the form markup couldn't be generated;
224         // otherwise, render the HTML.
225         if (Auth_OpenID::isFailure($form_html)) {
226             // TRANS: OpenID plugin server error if the form markup could not be generated.
227             // TRANS: %s is the failure message.
228             common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
229         } else {
230             $action = new AutosubmitAction(); // see below
231             $action->form_html = $form_html;
232             $action->form_id = $form_id;
233             $action->prepare(array('action' => 'autosubmit'));
234             $action->handle(array('action' => 'autosubmit'));
235         }
236     }
237     */
238 }
239
240 // Half-assed attempt at a module-private function
241
242 function _oid_print_instructions()
243 {
244     common_element('div', 'instructions',
245                    // TRANS: OpenID plugin user instructions.
246                    _m('This form should automatically submit itself. '.
247                       'If not, click the submit button to go to your '.
248                       'OpenID provider.'));
249 }
250
251 /**
252  * Update a user from sreg parameters
253  * @param User $user
254  * @param array $sreg fields from OpenID sreg response
255  * @access private
256  */
257 function oid_update_user($user, $sreg)
258 {
259     $profile = $user->getProfile();
260
261     $orig_profile = clone($profile);
262
263     if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
264         $profile->fullname = $sreg['fullname'];
265     }
266
267     if (!empty($sreg['country'])) {
268         if ($sreg['postcode']) {
269             // XXX: use postcode to get city and region
270             // XXX: also, store postcode somewhere -- it's valuable!
271             $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
272         } else {
273             $profile->location = $sreg['country'];
274         }
275     }
276
277     // XXX save language if it's passed
278     // XXX save timezone if it's passed
279
280     if (!$profile->update($orig_profile)) {
281         // TRANS: OpenID plugin server error.
282         common_server_error(_m('Error saving the profile.'));
283         return false;
284     }
285
286     $orig_user = clone($user);
287
288     if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
289         $user->email = $sreg['email'];
290     }
291
292     if (!$user->update($orig_user)) {
293         // TRANS: OpenID plugin server error.
294         common_server_error(_m('Error saving the user.'));
295         return false;
296     }
297
298     return true;
299 }
300
301 function oid_assert_allowed($url)
302 {
303     $blacklist = common_config('openid', 'blacklist');
304     $whitelist = common_config('openid', 'whitelist');
305
306     if (empty($blacklist)) {
307         $blacklist = array();
308     }
309
310     if (empty($whitelist)) {
311         $whitelist = array();
312     }
313
314     foreach ($blacklist as $pattern) {
315         if (preg_match("/$pattern/", $url)) {
316             common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
317             foreach ($whitelist as $exception) {
318                 if (preg_match("/$exception/", $url)) {
319                     common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
320                     return;
321                 }
322             }
323             // TRANS: OpenID plugin client exception (403).
324             throw new ClientException(_m('Unauthorized URL used for OpenID login.'), 403);
325         }
326     }
327
328     return;
329 }
330
331 /**
332  * Check the teams available in the given OpenID response
333  * Using Launchpad's OpenID teams extension
334  *
335  * @return boolean whether this user is acceptable
336  */
337 function oid_check_teams($response)
338 {
339     $requiredTeam = common_config('openid', 'required_team');
340     if ($requiredTeam) {
341         $team_resp = new Auth_OpenID_TeamsResponse($response);
342         if ($team_resp) {
343             $teams = $team_resp->getTeams();
344         } else {
345             $teams = array();
346         }
347
348         $match = in_array($requiredTeam, $teams);
349         $is = $match ? 'is' : 'is not';
350         common_log(LOG_DEBUG, "Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
351
352         return $match;
353     }
354
355     return true;
356 }
357
358 class AutosubmitAction extends Action
359 {
360     var $form_html = null;
361     var $form_id = null;
362
363     function handle()
364     {
365         parent::handle();
366         $this->showPage();
367     }
368
369     function title()
370     {
371         // TRANS: Title
372         return _m('OpenID Login Submission');
373     }
374
375     function showContent()
376     {
377         $this->raw('<p style="margin: 20px 80px">');
378         // @todo FIXME: This would be better using standard CSS class, but the present theme's a bit scary.
379         $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
380                                     // for some reason the base CSS sets <img>s as block display?!
381                                     'style' => 'display: inline'));
382         // TRANS: OpenID plugin message used while requesting authorization user's OpenID login provider.
383         $this->text(_m('Requesting authorization from your login provider...'));
384         $this->raw('</p>');
385         $this->raw('<p style="margin-top: 60px; font-style: italic">');
386         // TRANS: OpenID plugin message. User instruction while requesting authorization user's OpenID login provider.
387         $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
388         $this->raw('</p>');
389         $this->raw($this->form_html);
390     }
391
392     function showScripts()
393     {
394         parent::showScripts();
395         $this->element('script', null,
396                        'document.getElementById(\'' . $this->form_id . '\').submit();');
397     }
398 }