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