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