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.
40 * Depends on: WebFinger plugin for HostMeta-lookup (user@host format)
44 * @author Evan Prodromou <evan@status.net>
45 * @author Craig Andrews <candrews@integralblue.com>
46 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
47 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48 * @link http://status.net/
49 * @link http://openid.net/
51 class OpenIDPlugin extends Plugin
53 // Plugin parameter: set true to disallow non-OpenID logins
54 // If set, overrides the setting in database or $config['site']['openidonly']
55 public $openidOnly = null;
60 if ($this->openidOnly !== null) {
62 $config['site']['openidonly'] = (bool)$this->openidOnly;
67 * Add OpenID-related paths to the router table
69 * Hook for RouterInitialized event.
71 * @param URLMapper $m URL mapper
73 * @return boolean hook return
75 public function onStartInitializeRouter(URLMapper $m)
77 $m->connect('main/openid', array('action' => 'openidlogin'));
78 $m->connect('main/openidtrust', array('action' => 'openidtrust'));
79 $m->connect('settings/openid', array('action' => 'openidsettings'));
80 $m->connect('index.php?action=finishopenidlogin',
81 array('action' => 'finishopenidlogin'));
82 $m->connect('index.php?action=finishaddopenid',
83 array('action' => 'finishaddopenid'));
84 $m->connect('main/openidserver', array('action' => 'openidserver'));
85 $m->connect('panel/openid', array('action' => 'openidadminpanel'));
91 * In OpenID-only mode, disable paths for password stuff
93 * @param string $path path to connect
94 * @param array $defaults path defaults
95 * @param array $rules path rules
96 * @param array $result unused
98 * @return boolean hook return
100 function onStartConnectPath(&$path, &$defaults, &$rules, &$result)
102 if (common_config('site', 'openidonly')) {
103 // Note that we should not remove the login and register
104 // actions. Lots of auth-related things link to them,
105 // such as when visiting a private site without a session
106 // or revalidating a remembered login for admin work.
108 // We take those two over with redirects to ourselves
109 // over in onArgsInitialize().
110 static $block = array('main/recoverpassword',
111 'settings/password');
113 if (in_array($path, $block)) {
122 * If we've been hit with password-login args, redirect
124 * @param array $args args (URL, Get, post)
126 * @return boolean hook return
128 function onArgsInitialize($args)
130 if (common_config('site', 'openidonly')) {
131 if (array_key_exists('action', $args)) {
132 $action = trim($args['action']);
133 if (in_array($action, array('login', 'register'))) {
134 common_redirect(common_local_url('openidlogin'));
135 } else if ($action == 'passwordsettings') {
136 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 'Auth_OpenID_TeamsExtension':
354 case 'Auth_OpenID_TeamsRequest':
355 case 'Auth_OpenID_TeamsResponse':
356 require_once dirname(__FILE__) . '/extlib/teams-extension.php';
360 return parent::onAutoload($cls);
366 * These actions should use https when SSL support is 'sometimes'
368 * @param Action $action Action to form an URL for
369 * @param boolean &$ssl Whether to mark it for SSL
371 * @return boolean hook return
373 function onSensitiveAction($action, &$ssl)
377 case 'finishopenidlogin':
378 case 'finishaddopenid':
389 * These actions should be visible even when the site is marked private
391 * @param Action $action Action to show
392 * @param boolean &$login Whether it's a login action
394 * @return boolean hook return
396 function onLoginAction($action, &$login)
401 case 'finishopenidlogin':
411 * We include a <meta> element linking to the webfinger resource page,
412 * for OpenID client-side authentication.
414 * @param Action $action Action being shown
418 function onEndShowHeadElements($action)
420 if ($action instanceof ShowstreamAction) {
421 $action->element('link', array('rel' => 'openid2.provider',
422 'href' => common_local_url('openidserver')));
423 $action->element('link', array('rel' => 'openid2.local_id',
424 'href' => $action->profile->profileurl));
425 $action->element('link', array('rel' => 'openid.server',
426 'href' => common_local_url('openidserver')));
427 $action->element('link', array('rel' => 'openid.delegate',
428 'href' => $action->profile->profileurl));
434 * Redirect to OpenID login if they have an OpenID
436 * @param Action $action Action being executed
437 * @param User $user User doing the action
439 * @return boolean whether to continue
441 function onRedirectToLogin($action, $user)
443 if (common_config('site', 'openid_only') || (!empty($user) && User_openid::hasOpenID($user->id))) {
444 common_redirect(common_local_url('openidlogin'), 303);
450 * Show some extra instructions for using OpenID
452 * @param Action $action Action being executed
454 * @return boolean hook value
456 function onEndShowPageNotice($action)
458 $name = $action->trimmed('action');
463 if (common_logged_in()) {
464 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
465 // TRANS: This message contains Markdown links in the form (description)[link].
466 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
467 '[Add an OpenID to your account](%%action.openidsettings%%)!');
469 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
470 // TRANS: This message contains Markdown links in the form (description)[link].
471 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
472 'Try our [OpenID registration]'.
473 '(%%action.openidlogin%%)!)');
477 // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
478 // TRANS: This message contains Markdown links in the form (description)[link].
479 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
480 'Try our [OpenID login]'.
481 '(%%action.openidlogin%%)!)');
487 $output = common_markup_to_html($instr);
488 $action->raw($output);
493 * Load our document if requested
495 * @param string &$title Title to fetch
496 * @param string &$output HTML to output
498 * @return boolean hook value
500 function onStartLoadDoc(&$title, &$output)
502 if ($title == 'openid') {
503 $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
505 $c = file_get_contents($filename);
506 $output = common_markup_to_html($c);
507 return false; // success!
514 * Add our document to the global menu
516 * @param string $title Title being fetched
517 * @param string &$output HTML being output
519 * @return boolean hook value
521 function onEndDocsMenu(&$items) {
522 $items[] = array('doc',
523 array('title' => 'openid'),
524 _m('MENU', 'OpenID'),
525 _('Logging in with OpenID'),
533 * Assure that our data objects are available in the DB
535 * @return boolean hook value
537 function onCheckSchema()
539 $schema = Schema::get();
540 $schema->ensureTable('user_openid', User_openid::schemaDef());
541 $schema->ensureTable('user_openid_trustroot', User_openid_trustroot::schemaDef());
542 $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());
544 /* These are used by JanRain OpenID library */
546 $schema->ensureTable('oid_associations',
549 'server_url' => array('type' => 'blob', 'not null' => true),
550 'handle' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'default' => ''), // character set latin1,
551 'secret' => array('type' => 'blob'),
552 'issued' => array('type' => 'int'),
553 'lifetime' => array('type' => 'int'),
554 'assoc_type' => array('type' => 'varchar', 'length' => 64),
556 'primary key' => array(array('server_url', 191), 'handle'),
558 $schema->ensureTable('oid_nonces',
561 'server_url' => array('type' => 'varchar', 'length' => 2047),
562 'timestamp' => array('type' => 'int'),
563 'salt' => array('type' => 'char', 'length' => 40),
565 'unique keys' => array(
566 'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 191), 'timestamp', 'salt'),
574 * Add our tables to be deleted when a user is deleted
576 * @param User $user User being deleted
577 * @param array &$tables Array of table names
579 * @return boolean hook value
581 function onUserDeleteRelated($user, &$tables)
583 $tables[] = 'User_openid';
584 $tables[] = 'User_openid_trustroot';
589 * Add an OpenID tab to the admin panel
591 * @param Widget $nav Admin panel nav
593 * @return boolean hook value
595 function onEndAdminPanelNav($nav)
597 if (AdminPanelAction::canAdmin('openid')) {
599 $action_name = $nav->action->trimmed('action');
602 common_local_url('openidadminpanel'),
603 // TRANS: OpenID configuration menu item.
605 // TRANS: Tooltip for OpenID configuration menu item.
606 _m('OpenID configuration.'),
607 $action_name == 'openidadminpanel',
608 'nav_openid_admin_panel'
616 * Add OpenID information to the Account Management Control Document
617 * Event supplied by the Account Manager plugin
619 * @param array &$amcd Array that expresses the AMCD
621 * @return boolean hook value
624 function onEndAccountManagementControlDocument(&$amcd)
626 $amcd['auth-methods']['openid'] = array(
629 'path' => common_local_url('openidlogin'),
631 'identity' => 'openid_url'
638 * Add our version information to output
640 * @param array &$versions Array of version-data arrays
642 * @return boolean hook value
644 function onPluginVersion(array &$versions)
646 $versions[] = array('name' => 'OpenID',
647 'version' => GNUSOCIAL_VERSION,
648 'author' => 'Evan Prodromou, Craig Andrews',
649 'homepage' => 'http://status.net/wiki/Plugin:OpenID',
651 // TRANS: Plugin description.
652 _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
656 function onStartOAuthLoginForm($action, &$button)
658 if (common_config('site', 'openidonly')) {
659 // Cancel the regular password login form, we won't need it.
660 $this->showOAuthLoginForm($action);
661 // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
662 $button = _m('BUTTON', 'Continue');
665 // Leave the regular password login form in place.
666 // We'll add an OpenID link at bottom...?
672 * @fixme merge with common code for main OpenID login form
673 * @param HTMLOutputter $action
675 protected function showOAuthLoginForm($action)
677 $action->elementStart('fieldset');
678 // TRANS: OpenID plugin logon form legend.
679 $action->element('legend', null, _m('LEGEND','OpenID login'));
681 $action->elementStart('ul', 'form_data');
682 $action->elementStart('li');
683 $provider = common_config('openid', 'trusted_provider');
684 $appendUsername = common_config('openid', 'append_username');
686 // TRANS: Field label.
687 $action->element('label', array(), _m('OpenID provider'));
688 $action->element('span', array(), $provider);
689 if ($appendUsername) {
690 $action->element('input', array('id' => 'openid_username',
691 'name' => 'openid_username',
692 'style' => 'float: none'));
694 $action->element('p', 'form_guide',
695 // TRANS: Form guide.
696 ($appendUsername ? _m('Enter your username.') . ' ' : '') .
697 // TRANS: Form guide.
698 _m('You will be sent to the provider\'s site for authentication.'));
699 $action->hidden('openid_url', $provider);
701 // TRANS: OpenID plugin logon form field label.
702 $action->input('openid_url', _m('OpenID URL'),
704 // TRANS: OpenID plugin logon form field instructions.
705 _m('Your OpenID URL.'));
707 $action->elementEnd('li');
708 $action->elementEnd('ul');
710 $action->elementEnd('fieldset');
714 * Handle a POST user credential check in apioauthauthorization.
715 * If given an OpenID URL, we'll pass us over to the regular things
716 * and then redirect back here on completion.
718 * @fixme merge with common code for main OpenID login form
719 * @param HTMLOutputter $action
721 function onStartOAuthLoginCheck($action, &$user)
723 $provider = common_config('openid', 'trusted_provider');
725 $openid_url = $provider;
726 if (common_config('openid', 'append_username')) {
727 $openid_url .= $action->trimmed('openid_username');
730 $openid_url = $action->trimmed('openid_url');
734 require_once dirname(__FILE__) . '/openid.php';
735 oid_assert_allowed($openid_url);
737 $returnto = common_local_url(
741 'oauth_token' => $action->arg('oauth_token'),
742 'mode' => $action->arg('mode')
745 common_set_returnto($returnto);
747 // This will redirect if functional...
748 $result = oid_authenticate($openid_url,
749 'finishopenidlogin');
750 if (is_string($result)) { # error message
751 throw new ServerException($result);
761 * Add link in user's XRD file to allow OpenID login.
763 * This link in the XRD should let users log in with their
764 * Webfinger identity to services that support it. See
765 * http://webfinger.org/login for an example.
767 * @param XML_XRD $xrd Currently-displaying resource descriptor
768 * @param Profile $target The profile that it's for
770 * @return boolean hook value (always true)
773 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
775 $xrd->links[] = new XML_XRD_Element_Link(
776 'http://specs.openid.net/auth/2.0/provider',
777 $target->profileurl);
783 * Add links in the user's profile block to their OpenID URLs.
785 * @param Profile $profile The profile being shown
786 * @param Array &$links Writeable array of arrays (href, text, image).
788 * @return boolean hook value (true)
791 function onOtherAccountProfiles($profile, &$links)
793 $prefs = User_openid_prefs::getKV('user_id', $profile->id);
795 if (empty($prefs) || !$prefs->hide_profile_link) {
797 $oid = new User_openid();
799 $oid->user_id = $profile->id;
802 while ($oid->fetch()) {
803 $links[] = array('href' => $oid->display,
804 'text' => _('OpenID'),
805 'image' => $this->path("icons/openid-16x16.gif"));