3 * StatusNet, the distributed open-source microblogging tool
7 * LICENCE: This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 * @author Evan Prodromou <evan@status.net>
23 * @author Craig Andrews <candrews@integralblue.com>
24 * @copyright 2009-2010 StatusNet, Inc.
25 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
35 * Plugin for OpenID authentication and identity
37 * This class enables consumer support for OpenID, the distributed authentication
38 * and identity system.
42 * @author Evan Prodromou <evan@status.net>
43 * @author Craig Andrews <candrews@integralblue.com>
44 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
45 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46 * @link http://status.net/
47 * @link http://openid.net/
49 class OpenIDPlugin extends Plugin
51 // Plugin parameter: set true to disallow non-OpenID logins
52 // If set, overrides the setting in database or $config['site']['openidonly']
53 public $openidOnly = null;
58 if ($this->openidOnly !== null) {
60 $config['site']['openidonly'] = (bool)$this->openidOnly;
65 * Add OpenID-related paths to the router table
67 * Hook for RouterInitialized event.
69 * @param Net_URL_Mapper $m URL mapper
71 * @return boolean hook return
73 function onStartInitializeRouter($m)
75 $m->connect('main/openid', array('action' => 'openidlogin'));
76 $m->connect('main/openidtrust', array('action' => 'openidtrust'));
77 $m->connect('settings/openid', array('action' => 'openidsettings'));
78 $m->connect('index.php?action=finishopenidlogin',
79 array('action' => 'finishopenidlogin'));
80 $m->connect('index.php?action=finishaddopenid',
81 array('action' => 'finishaddopenid'));
82 $m->connect('main/openidserver', array('action' => 'openidserver'));
83 $m->connect('panel/openid', array('action' => 'openidadminpanel'));
89 * In OpenID-only mode, disable paths for password stuff
91 * @param string $path path to connect
92 * @param array $defaults path defaults
93 * @param array $rules path rules
94 * @param array $result unused
96 * @return boolean hook return
98 function onStartConnectPath(&$path, &$defaults, &$rules, &$result)
100 if (common_config('site', 'openidonly')) {
101 // Note that we should not remove the login and register
102 // actions. Lots of auth-related things link to them,
103 // such as when visiting a private site without a session
104 // or revalidating a remembered login for admin work.
106 // We take those two over with redirects to ourselves
107 // over in onArgsInitialize().
108 static $block = array('main/recoverpassword',
109 'settings/password');
111 if (in_array($path, $block)) {
120 * If we've been hit with password-login args, redirect
122 * @param array $args args (URL, Get, post)
124 * @return boolean hook return
126 function onArgsInitialize($args)
128 if (common_config('site', 'openidonly')) {
129 if (array_key_exists('action', $args)) {
130 $action = trim($args['action']);
131 if (in_array($action, array('login', 'register'))) {
132 common_redirect(common_local_url('openidlogin'));
134 } else if ($action == 'passwordsettings') {
135 common_redirect(common_local_url('openidsettings'));
137 } else if ($action == 'recoverpassword') {
138 // TRANS: Client exception thrown when an action is not available.
139 throw new ClientException(_m('Unavailable action.'));
147 * Public XRDS output hook
149 * Puts the bits of code needed by some OpenID providers to show
150 * we're good citizens.
152 * @param Action $action Action being executed
153 * @param XMLOutputter &$xrdsOutputter Output channel
155 * @return boolean hook return
157 function onEndPublicXRDS($action, &$xrdsOutputter)
159 $xrdsOutputter->elementStart('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
160 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
161 'version' => '2.0'));
162 $xrdsOutputter->element('Type', null, 'xri://$xrds*simple');
164 foreach (array('finishopenidlogin', 'finishaddopenid') as $finish) {
165 $xrdsOutputter->showXrdsService(Auth_OpenID_RP_RETURN_TO_URL_TYPE,
166 common_local_url($finish));
169 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/server',
170 common_local_url('openidserver'),
173 'http://specs.openid.net/auth/2.0/identifier_select');
174 $xrdsOutputter->elementEnd('XRD');
178 * User XRDS output hook
180 * Puts the bits of code needed to discover OpenID endpoints.
182 * @param Action $action Action being executed
183 * @param XMLOutputter &$xrdsOutputter Output channel
185 * @return boolean hook return
187 function onEndUserXRDS($action, &$xrdsOutputter)
189 $xrdsOutputter->elementStart('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
190 'xml:id' => 'openid',
191 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
192 'version' => '2.0'));
193 $xrdsOutputter->element('Type', null, 'xri://$xrds*simple');
196 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/return_to',
197 common_local_url('finishopenidlogin'));
200 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/signon',
201 common_local_url('openidserver'),
204 common_profile_url($action->user->nickname));
205 $xrdsOutputter->elementEnd('XRD');
209 * If we're in OpenID-only mode, hide all the main menu except OpenID login.
211 * @param Action $action Action being run
213 * @return boolean hook return
215 function onStartPrimaryNav($action)
217 if (common_config('site', 'openidonly') && !common_logged_in()) {
218 // TRANS: Tooltip for main menu option "Login"
219 $tooltip = _m('TOOLTIP', 'Login to the site.');
220 $action->menuItem(common_local_url('openidlogin'),
221 // TRANS: Main menu option when not logged in to log in
226 // TRANS: Tooltip for main menu option "Help"
227 $tooltip = _m('TOOLTIP', 'Help me!');
228 $action->menuItem(common_local_url('doc', array('title' => 'help')),
229 // TRANS: Main menu option for help on the StatusNet site
234 if (!common_config('site', 'private')) {
235 // TRANS: Tooltip for main menu option "Search"
236 $tooltip = _m('TOOLTIP', 'Search for people or text.');
237 $action->menuItem(common_local_url('peoplesearch'),
238 // TRANS: Main menu option when logged in or when the StatusNet instance is not private
239 _m('MENU', 'Search'), $tooltip, false, 'nav_search');
241 Event::handle('EndPrimaryNav', array($action));
250 * If we're in openidOnly mode, we disable the menu for all other login.
252 * @param Action $action Action being executed
254 * @return boolean hook return
256 function onStartLoginGroupNav($action)
258 if (common_config('site', 'openidonly')) {
259 $this->showOpenIDLoginTab($action);
260 // Even though we replace this code, we
261 // DON'T run the End* hook, to keep others from
262 // adding tabs. Not nice, but.
270 * Menu item for login
272 * @param Action $action Action being executed
274 * @return boolean hook return
276 function onEndLoginGroupNav($action)
278 $this->showOpenIDLoginTab($action);
284 * Show menu item for login
286 * @param Action $action Action being executed
290 function showOpenIDLoginTab($action)
292 $action_name = $action->trimmed('action');
294 $action->menuItem(common_local_url('openidlogin'),
295 // TRANS: OpenID plugin menu item on site logon page.
296 _m('MENU', 'OpenID'),
297 // TRANS: OpenID plugin tooltip for logon menu item.
298 _m('Login or register with OpenID.'),
299 $action_name === 'openidlogin');
303 * Show menu item for password
305 * We hide it in openID-only mode
307 * @param Action $menu Widget for menu
308 * @param void &$unused Unused value
312 function onStartAccountSettingsPasswordMenuItem($menu, &$unused) {
313 if (common_config('site', 'openidonly')) {
320 * Menu item for OpenID settings
322 * @param Action $action Action being executed
324 * @return boolean hook return
326 function onEndAccountSettingsNav($action)
328 $action_name = $action->trimmed('action');
330 $action->menuItem(common_local_url('openidsettings'),
331 // TRANS: OpenID plugin menu item on user settings page.
332 _m('MENU', 'OpenID'),
333 // TRANS: OpenID plugin tooltip for user settings menu item.
334 _m('Add or remove OpenIDs.'),
335 $action_name === 'openidsettings');
343 * Loads our classes if they're requested.
345 * @param string $cls Class requested
347 * @return boolean hook return
349 function onAutoload($cls)
353 case 'OpenidloginAction':
354 case 'FinishopenidloginAction':
355 case 'FinishaddopenidAction':
357 case 'PublicxrdsAction':
358 case 'OpenidsettingsAction':
359 case 'OpenidserverAction':
360 case 'OpenidtrustAction':
361 case 'OpenidadminpanelAction':
362 require_once dirname(__FILE__) . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
365 require_once dirname(__FILE__) . '/User_openid.php';
367 case 'User_openid_trustroot':
368 require_once dirname(__FILE__) . '/User_openid_trustroot.php';
370 case 'Auth_OpenID_TeamsExtension':
371 case 'Auth_OpenID_TeamsRequest':
372 case 'Auth_OpenID_TeamsResponse':
373 require_once dirname(__FILE__) . '/extlib/teams-extension.php';
383 * These actions should use https when SSL support is 'sometimes'
385 * @param Action $action Action to form an URL for
386 * @param boolean &$ssl Whether to mark it for SSL
388 * @return boolean hook return
390 function onSensitiveAction($action, &$ssl)
394 case 'finishopenidlogin':
395 case 'finishaddopenid':
406 * These actions should be visible even when the site is marked private
408 * @param Action $action Action to show
409 * @param boolean &$login Whether it's a login action
411 * @return boolean hook return
413 function onLoginAction($action, &$login)
418 case 'finishopenidlogin':
428 * We include a <meta> element linking to the userxrds page, for OpenID
429 * client-side authentication.
431 * @param Action $action Action being shown
435 function onEndShowHeadElements($action)
437 if ($action instanceof ShowstreamAction) {
438 $action->element('link', array('rel' => 'openid2.provider',
439 'href' => common_local_url('openidserver')));
440 $action->element('link', array('rel' => 'openid2.local_id',
441 'href' => $action->profile->profileurl));
442 $action->element('link', array('rel' => 'openid.server',
443 'href' => common_local_url('openidserver')));
444 $action->element('link', array('rel' => 'openid.delegate',
445 'href' => $action->profile->profileurl));
451 * Redirect to OpenID login if they have an OpenID
453 * @param Action $action Action being executed
454 * @param User $user User doing the action
456 * @return boolean whether to continue
458 function onRedirectToLogin($action, $user)
460 if (common_config('site', 'openid_only') || (!empty($user) && User_openid::hasOpenID($user->id))) {
461 common_redirect(common_local_url('openidlogin'), 303);
468 * Show some extra instructions for using OpenID
470 * @param Action $action Action being executed
472 * @return boolean hook value
474 function onEndShowPageNotice($action)
476 $name = $action->trimmed('action');
481 if (common_logged_in()) {
482 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
483 // TRANS: This message contains Markdown links in the form (description)[link].
484 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
485 '[Add an OpenID to your account](%%action.openidsettings%%)!');
487 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
488 // TRANS: This message contains Markdown links in the form (description)[link].
489 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
490 'Try our [OpenID registration]'.
491 '(%%action.openidlogin%%)!)');
495 // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
496 // TRANS: This message contains Markdown links in the form (description)[link].
497 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
498 'Try our [OpenID login]'.
499 '(%%action.openidlogin%%)!)');
505 $output = common_markup_to_html($instr);
506 $action->raw($output);
511 * Load our document if requested
513 * @param string &$title Title to fetch
514 * @param string &$output HTML to output
516 * @return boolean hook value
518 function onStartLoadDoc(&$title, &$output)
520 if ($title == 'openid') {
521 $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
523 $c = file_get_contents($filename);
524 $output = common_markup_to_html($c);
525 return false; // success!
532 * Add our document to the global menu
534 * @param string $title Title being fetched
535 * @param string &$output HTML being output
537 * @return boolean hook value
539 function onEndLoadDoc($title, &$output)
541 if ($title == 'help') {
542 // TRANS: Item on help page. This message contains Markdown links in the form [description](link).
543 $menuitem = _m('* [OpenID](%%doc.openid%%) - What OpenID is and how to use it with this service.');
545 $output .= common_markup_to_html($menuitem);
554 * Assure that our data objects are available in the DB
556 * @return boolean hook value
558 function onCheckSchema()
560 $schema = Schema::get();
561 $schema->ensureTable('user_openid',
562 array(new ColumnDef('canonical', 'varchar',
563 '255', false, 'PRI'),
564 new ColumnDef('display', 'varchar',
565 '255', false, 'UNI'),
566 new ColumnDef('user_id', 'integer',
568 new ColumnDef('created', 'datetime',
570 new ColumnDef('modified', 'timestamp')));
571 $schema->ensureTable('user_openid_trustroot',
572 array(new ColumnDef('trustroot', 'varchar',
573 '255', false, 'PRI'),
574 new ColumnDef('user_id', 'integer',
576 new ColumnDef('created', 'datetime',
578 new ColumnDef('modified', 'timestamp')));
583 * Add our tables to be deleted when a user is deleted
585 * @param User $user User being deleted
586 * @param array &$tables Array of table names
588 * @return boolean hook value
590 function onUserDeleteRelated($user, &$tables)
592 $tables[] = 'User_openid';
593 $tables[] = 'User_openid_trustroot';
598 * Add an OpenID tab to the admin panel
600 * @param Widget $nav Admin panel nav
602 * @return boolean hook value
604 function onEndAdminPanelNav($nav)
606 if (AdminPanelAction::canAdmin('openid')) {
608 $action_name = $nav->action->trimmed('action');
611 common_local_url('openidadminpanel'),
612 // TRANS: OpenID configuration menu item.
614 // TRANS: Tooltip for OpenID configuration menu item.
615 _m('OpenID configuration.'),
616 $action_name == 'openidadminpanel',
617 'nav_openid_admin_panel'
625 * Add OpenID information to the Account Management Control Document
626 * Event supplied by the Account Manager plugin
628 * @param array &$amcd Array that expresses the AMCD
630 * @return boolean hook value
633 function onEndAccountManagementControlDocument(&$amcd)
635 $amcd['auth-methods']['openid'] = array(
638 'path' => common_local_url('openidlogin'),
640 'identity' => 'openid_url'
647 * Add our version information to output
649 * @param array &$versions Array of version-data arrays
651 * @return boolean hook value
653 function onPluginVersion(&$versions)
655 $versions[] = array('name' => 'OpenID',
656 'version' => STATUSNET_VERSION,
657 'author' => 'Evan Prodromou, Craig Andrews',
658 'homepage' => 'http://status.net/wiki/Plugin:OpenID',
660 // TRANS: Plugin description.
661 _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
665 function onStartOAuthLoginForm($action, &$button)
667 if (common_config('site', 'openidonly')) {
668 // Cancel the regular password login form, we won't need it.
669 $this->showOAuthLoginForm($action);
670 // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
671 $button = _m('BUTTON', 'Continue');
674 // Leave the regular password login form in place.
675 // We'll add an OpenID link at bottom...?
681 * @fixme merge with common code for main OpenID login form
682 * @param HTMLOutputter $action
684 protected function showOAuthLoginForm($action)
686 $action->elementStart('fieldset');
687 // TRANS: OpenID plugin logon form legend.
688 $action->element('legend', null, _m('LEGEND','OpenID login'));
690 $action->elementStart('ul', 'form_data');
691 $action->elementStart('li');
692 $provider = common_config('openid', 'trusted_provider');
693 $appendUsername = common_config('openid', 'append_username');
695 // TRANS: Field label.
696 $action->element('label', array(), _m('OpenID provider'));
697 $action->element('span', array(), $provider);
698 if ($appendUsername) {
699 $action->element('input', array('id' => 'openid_username',
700 'name' => 'openid_username',
701 'style' => 'float: none'));
703 $action->element('p', 'form_guide',
704 // TRANS: Form guide.
705 ($appendUsername ? _m('Enter your username.') . ' ' : '') .
706 // TRANS: Form guide.
707 _m('You will be sent to the provider\'s site for authentication.'));
708 $action->hidden('openid_url', $provider);
710 // TRANS: OpenID plugin logon form field label.
711 $action->input('openid_url', _m('OpenID URL'),
713 // TRANS: OpenID plugin logon form field instructions.
714 _m('Your OpenID URL.'));
716 $action->elementEnd('li');
717 $action->elementEnd('ul');
719 $action->elementEnd('fieldset');
723 * Handle a POST user credential check in apioauthauthorization.
724 * If given an OpenID URL, we'll pass us over to the regular things
725 * and then redirect back here on completion.
727 * @fixme merge with common code for main OpenID login form
728 * @param HTMLOutputter $action
730 function onStartOAuthLoginCheck($action, &$user)
732 $provider = common_config('openid', 'trusted_provider');
734 $openid_url = $provider;
735 if (common_config('openid', 'append_username')) {
736 $openid_url .= $action->trimmed('openid_username');
739 $openid_url = $action->trimmed('openid_url');
743 require_once dirname(__FILE__) . '/openid.php';
744 oid_assert_allowed($openid_url);
746 $returnto = common_local_url(
750 'oauth_token' => $action->arg('oauth_token'),
751 'mode' => $action->arg('mode')
754 common_set_returnto($returnto);
756 // This will redirect if functional...
757 $result = oid_authenticate($openid_url,
758 'finishopenidlogin');
759 if (is_string($result)) { # error message
760 throw new ServerException($result);
770 * Add link in user's XRD file to allow OpenID login.
772 * This link in the XRD should let users log in with their
773 * Webfinger identity to services that support it. See
774 * http://webfinger.org/login for an example.
776 * @param XRD &$xrd Currently-displaying XRD object
777 * @param User $user The user that it's for
779 * @return boolean hook value (always true)
782 function onEndXrdActionLinks(&$xrd, $user)
784 $profile = $user->getProfile();
786 if (!empty($profile)) {
787 $xrd->links[] = array('rel' => 'http://specs.openid.net/auth/2.0/provider',
788 'href' => $profile->profileurl);