]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/openid.php
Merge branch 'master' into testing
[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     $oid = new User_openid();
89     $oid->user_id = $id;
90     $oid->canonical = $canonical;
91     $oid->display = $display;
92     $oid->created = DB_DataObject_Cast::dateTime();
93
94     if (!$oid->insert()) {
95         $err = PEAR::getStaticProperty('DB_DataObject','lastError');
96         return false;
97     }
98
99     return true;
100 }
101
102 function oid_get_user($openid_url)
103 {
104     $user = null;
105     $oid = User_openid::staticGet('canonical', $openid_url);
106     if ($oid) {
107         $user = User::staticGet('id', $oid->user_id);
108     }
109     return $user;
110 }
111
112 function oid_check_immediate($openid_url, $backto=null)
113 {
114     if (!$backto) {
115         $action = $_REQUEST['action'];
116         $args = common_copy_args($_GET);
117         unset($args['action']);
118         $backto = common_local_url($action, $args);
119     }
120
121     common_ensure_session();
122
123     $_SESSION['openid_immediate_backto'] = $backto;
124
125     oid_authenticate($openid_url,
126                      'finishimmediate',
127                      true);
128 }
129
130 function oid_authenticate($openid_url, $returnto, $immediate=false)
131 {
132
133     $consumer = oid_consumer();
134
135     if (!$consumer) {
136         // TRANS: OpenID plugin server error.
137         common_server_error(_m('Cannot instantiate OpenID consumer object.'));
138         return false;
139     }
140
141     common_ensure_session();
142
143     $auth_request = $consumer->begin($openid_url);
144
145     // Handle failure status return values.
146     if (!$auth_request) {
147         common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
148         // TRANS: OpenID plugin message. Given when an OpenID is not valid.
149         return _m('Not a valid OpenID.');
150     } else if (Auth_OpenID::isFailure($auth_request)) {
151         common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
152         // TRANS: OpenID plugin server error. Given when the OpenID authentication request fails.
153         // TRANS: %s is the failure message.
154         return sprintf(_m('OpenID failure: %s.'), $auth_request->message);
155     }
156
157     $sreg_request = Auth_OpenID_SRegRequest::build(// Required
158                                                    array(),
159                                                    // Optional
160                                                    array('nickname',
161                                                          'email',
162                                                          'fullname',
163                                                          'language',
164                                                          'timezone',
165                                                          'postcode',
166                                                          'country'));
167
168     if ($sreg_request) {
169         $auth_request->addExtension($sreg_request);
170     }
171
172     $requiredTeam = common_config('openid', 'required_team');
173     if ($requiredTeam) {
174         // LaunchPad OpenID extension
175         $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
176         if ($team_request) {
177             $auth_request->addExtension($team_request);
178         }
179     }
180
181     $trust_root = common_root_url(true);
182     $process_url = common_local_url($returnto);
183
184     // Net::OpenID::Server as used on LiveJournal appears to incorrectly
185     // reject POST requests for data submissions that OpenID 1.1 specs
186     // as GET, although 2.0 allows them:
187     // https://rt.cpan.org/Public/Bug/Display.html?id=42202
188     //
189     // Our OpenID libraries would have switched in the redirect automatically
190     // if it were detecting 1.1 compatibility mode, however the server is
191     // advertising itself as 2.0-compatible, so we got switched to the POST.
192     //
193     // Since the GET should always work anyway, we'll just take out the
194     // autosubmitter for now.
195     // 
196     //if ($auth_request->shouldSendRedirect()) {
197         $redirect_url = $auth_request->redirectURL($trust_root,
198                                                    $process_url,
199                                                    $immediate);
200         if (!$redirect_url) {
201         } else if (Auth_OpenID::isFailure($redirect_url)) {
202             // TRANS: OpenID plugin server error. Given when the OpenID authentication request cannot be redirected.
203             // TRANS: %s is the failure message.
204             return sprintf(_m('Could not redirect to server: %s.'), $redirect_url->message);
205         } else {
206             common_redirect($redirect_url, 303);
207         }
208     /*
209     } else {
210         // Generate form markup and render it.
211         $form_id = 'openid_message';
212         $form_html = $auth_request->formMarkup($trust_root, $process_url,
213                                                $immediate, array('id' => $form_id));
214
215         // XXX: This is cheap, but things choke if we don't escape ampersands
216         // in the HTML attributes
217
218         $form_html = preg_replace('/&/', '&amp;', $form_html);
219
220         // Display an error if the form markup couldn't be generated;
221         // otherwise, render the HTML.
222         if (Auth_OpenID::isFailure($form_html)) {
223             // TRANS: OpenID plugin server error if the form markup could not be generated.
224             // TRANS: %s is the failure message.
225             common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
226         } else {
227             $action = new AutosubmitAction(); // see below
228             $action->form_html = $form_html;
229             $action->form_id = $form_id;
230             $action->prepare(array('action' => 'autosubmit'));
231             $action->handle(array('action' => 'autosubmit'));
232         }
233     }
234     */
235 }
236
237 // Half-assed attempt at a module-private function
238
239 function _oid_print_instructions()
240 {
241     common_element('div', 'instructions',
242                    // TRANS: OpenID plugin user instructions.
243                    _m('This form should automatically submit itself. '.
244                       'If not, click the submit button to go to your '.
245                       'OpenID provider.'));
246 }
247
248 /**
249  * Update a user from sreg parameters
250  * @param User $user
251  * @param array $sreg fields from OpenID sreg response
252  * @access private
253  */
254 function oid_update_user($user, $sreg)
255 {
256     $profile = $user->getProfile();
257
258     $orig_profile = clone($profile);
259
260     if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
261         $profile->fullname = $sreg['fullname'];
262     }
263
264     if (!empty($sreg['country'])) {
265         if ($sreg['postcode']) {
266             // XXX: use postcode to get city and region
267             // XXX: also, store postcode somewhere -- it's valuable!
268             $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
269         } else {
270             $profile->location = $sreg['country'];
271         }
272     }
273
274     // XXX save language if it's passed
275     // XXX save timezone if it's passed
276
277     if (!$profile->update($orig_profile)) {
278         // TRANS: OpenID plugin server error.
279         common_server_error(_m('Error saving the profile.'));
280         return false;
281     }
282
283     $orig_user = clone($user);
284
285     if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
286         $user->email = $sreg['email'];
287     }
288
289     if (!$user->update($orig_user)) {
290         // TRANS: OpenID plugin server error.
291         common_server_error(_m('Error saving the user.'));
292         return false;
293     }
294
295     return true;
296 }
297
298 function oid_assert_allowed($url)
299 {
300     $blacklist = common_config('openid', 'blacklist');
301     $whitelist = common_config('openid', 'whitelist');
302
303     if (empty($blacklist)) {
304         $blacklist = array();
305     }
306
307     if (empty($whitelist)) {
308         $whitelist = array();
309     }
310
311     foreach ($blacklist as $pattern) {
312         if (preg_match("/$pattern/", $url)) {
313             common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
314             foreach ($whitelist as $exception) {
315                 if (preg_match("/$exception/", $url)) {
316                     common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
317                     return;
318                 }
319             }
320             // TRANS: OpenID plugin client exception (403).
321             throw new ClientException(_m('Unauthorized URL used for OpenID login.'), 403);
322         }
323     }
324
325     return;
326 }
327
328 /**
329  * Check the teams available in the given OpenID response
330  * Using Launchpad's OpenID teams extension
331  *
332  * @return boolean whether this user is acceptable
333  */
334 function oid_check_teams($response)
335 {
336     $requiredTeam = common_config('openid', 'required_team');
337     if ($requiredTeam) {
338         $team_resp = new Auth_OpenID_TeamsResponse($response);
339         if ($team_resp) {
340             $teams = $team_resp->getTeams();
341         } else {
342             $teams = array();
343         }
344
345         $match = in_array($requiredTeam, $teams);
346         $is = $match ? 'is' : 'is not';
347         common_log(LOG_DEBUG, "Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
348
349         return $match;
350     }
351
352     return true;
353 }
354
355 class AutosubmitAction extends Action
356 {
357     var $form_html = null;
358     var $form_id = null;
359
360     function handle($args)
361     {
362         parent::handle($args);
363         $this->showPage();
364     }
365
366     function title()
367     {
368         // TRANS: Title
369         return _m('OpenID Login Submission');
370     }
371
372     function showContent()
373     {
374         $this->raw('<p style="margin: 20px 80px">');
375         // @todo FIXME: This would be better using standard CSS class, but the present theme's a bit scary.
376         $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
377                                     // for some reason the base CSS sets <img>s as block display?!
378                                     'style' => 'display: inline'));
379         // TRANS: OpenID plugin message used while requesting authorization user's OpenID login provider.
380         $this->text(_m('Requesting authorization from your login provider...'));
381         $this->raw('</p>');
382         $this->raw('<p style="margin-top: 60px; font-style: italic">');
383         // TRANS: OpenID plugin message. User instruction while requesting authorization user's OpenID login provider.
384         $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
385         $this->raw('</p>');
386         $this->raw($this->form_html);
387     }
388
389     function showScripts()
390     {
391         parent::showScripts();
392         $this->element('script', null,
393                        'document.getElementById(\'' . $this->form_id . '\').submit();');
394     }
395 }