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 Net_URL_Mapper $m URL mapper
73 * @return boolean hook return
75 function onStartInitializeRouter($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'));
136 } else if ($action == 'passwordsettings') {
137 common_redirect(common_local_url('openidsettings'));
139 } else if ($action == 'recoverpassword') {
140 // TRANS: Client exception thrown when an action is not available.
141 throw new ClientException(_m('Unavailable action.'));
149 * Public XRDS output hook
151 * Puts the bits of code needed by some OpenID providers to show
152 * we're good citizens.
154 * @param Action $action Action being executed
155 * @param XMLOutputter &$xrdsOutputter Output channel
157 * @return boolean hook return
159 function onEndPublicXRDS($action, &$xrdsOutputter)
161 $xrdsOutputter->elementStart('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
162 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
163 'version' => '2.0'));
164 $xrdsOutputter->element('Type', null, 'xri://$xrds*simple');
166 foreach (array('finishopenidlogin', 'finishaddopenid') as $finish) {
167 $xrdsOutputter->showXrdsService(Auth_OpenID_RP_RETURN_TO_URL_TYPE,
168 common_local_url($finish));
171 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/server',
172 common_local_url('openidserver'),
175 'http://specs.openid.net/auth/2.0/identifier_select');
176 $xrdsOutputter->elementEnd('XRD');
180 * User XRDS output hook
182 * Puts the bits of code needed to discover OpenID endpoints.
184 * @param Action $action Action being executed
185 * @param XMLOutputter &$xrdsOutputter Output channel
187 * @return boolean hook return
189 function onEndUserXRDS($action, &$xrdsOutputter)
191 $xrdsOutputter->elementStart('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
192 'xml:id' => 'openid',
193 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
194 'version' => '2.0'));
195 $xrdsOutputter->element('Type', null, 'xri://$xrds*simple');
198 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/return_to',
199 common_local_url('finishopenidlogin'));
202 $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/signon',
203 common_local_url('openidserver'),
206 common_profile_url($action->user->nickname));
207 $xrdsOutputter->elementEnd('XRD');
211 * If we're in OpenID-only mode, hide all the main menu except OpenID login.
213 * @param Action $action Action being run
215 * @return boolean hook return
217 function onStartPrimaryNav($action)
219 if (common_config('site', 'openidonly') && !common_logged_in()) {
220 // TRANS: Tooltip for main menu option "Login"
221 $tooltip = _m('TOOLTIP', 'Login to the site.');
222 $action->menuItem(common_local_url('openidlogin'),
223 // TRANS: Main menu option when not logged in to log in
228 // TRANS: Tooltip for main menu option "Help"
229 $tooltip = _m('TOOLTIP', 'Help me!');
230 $action->menuItem(common_local_url('doc', array('title' => 'help')),
231 // TRANS: Main menu option for help on the StatusNet site
236 if (!common_config('site', 'private')) {
237 // TRANS: Tooltip for main menu option "Search"
238 $tooltip = _m('TOOLTIP', 'Search for people or text.');
239 $action->menuItem(common_local_url('peoplesearch'),
240 // TRANS: Main menu option when logged in or when the StatusNet instance is not private
241 _m('MENU', 'Search'), $tooltip, false, 'nav_search');
243 Event::handle('EndPrimaryNav', array($action));
252 * If we're in openidOnly mode, we disable the menu for all other login.
254 * @param Action $action Action being executed
256 * @return boolean hook return
258 function onStartLoginGroupNav($action)
260 if (common_config('site', 'openidonly')) {
261 $this->showOpenIDLoginTab($action);
262 // Even though we replace this code, we
263 // DON'T run the End* hook, to keep others from
264 // adding tabs. Not nice, but.
272 * Menu item for login
274 * @param Action $action Action being executed
276 * @return boolean hook return
278 function onEndLoginGroupNav($action)
280 $this->showOpenIDLoginTab($action);
286 * Show menu item for login
288 * @param Action $action Action being executed
292 function showOpenIDLoginTab($action)
294 $action_name = $action->trimmed('action');
296 $action->menuItem(common_local_url('openidlogin'),
297 // TRANS: OpenID plugin menu item on site logon page.
298 _m('MENU', 'OpenID'),
299 // TRANS: OpenID plugin tooltip for logon menu item.
300 _m('Login or register with OpenID.'),
301 $action_name === 'openidlogin');
305 * Show menu item for password
307 * We hide it in openID-only mode
309 * @param Action $menu Widget for menu
310 * @param void &$unused Unused value
314 function onStartAccountSettingsPasswordMenuItem($menu, &$unused) {
315 if (common_config('site', 'openidonly')) {
322 * Menu item for OpenID settings
324 * @param Action $action Action being executed
326 * @return boolean hook return
328 function onEndAccountSettingsNav($action)
330 $action_name = $action->trimmed('action');
332 $action->menuItem(common_local_url('openidsettings'),
333 // TRANS: OpenID plugin menu item on user settings page.
334 _m('MENU', 'OpenID'),
335 // TRANS: OpenID plugin tooltip for user settings menu item.
336 _m('Add or remove OpenIDs.'),
337 $action_name === 'openidsettings');
345 * Loads our classes if they're requested.
347 * @param string $cls Class requested
349 * @return boolean hook return
351 function onAutoload($cls)
355 case 'Auth_OpenID_TeamsExtension':
356 case 'Auth_OpenID_TeamsRequest':
357 case 'Auth_OpenID_TeamsResponse':
358 require_once dirname(__FILE__) . '/extlib/teams-extension.php';
362 return parent::onAutoload($cls);
368 * These actions should use https when SSL support is 'sometimes'
370 * @param Action $action Action to form an URL for
371 * @param boolean &$ssl Whether to mark it for SSL
373 * @return boolean hook return
375 function onSensitiveAction($action, &$ssl)
379 case 'finishopenidlogin':
380 case 'finishaddopenid':
391 * These actions should be visible even when the site is marked private
393 * @param Action $action Action to show
394 * @param boolean &$login Whether it's a login action
396 * @return boolean hook return
398 function onLoginAction($action, &$login)
403 case 'finishopenidlogin':
413 * We include a <meta> element linking to the webfinger resource page,
414 * for OpenID client-side authentication.
416 * @param Action $action Action being shown
420 function onEndShowHeadElements($action)
422 if ($action instanceof ShowstreamAction) {
423 $action->element('link', array('rel' => 'openid2.provider',
424 'href' => common_local_url('openidserver')));
425 $action->element('link', array('rel' => 'openid2.local_id',
426 'href' => $action->profile->profileurl));
427 $action->element('link', array('rel' => 'openid.server',
428 'href' => common_local_url('openidserver')));
429 $action->element('link', array('rel' => 'openid.delegate',
430 'href' => $action->profile->profileurl));
436 * Redirect to OpenID login if they have an OpenID
438 * @param Action $action Action being executed
439 * @param User $user User doing the action
441 * @return boolean whether to continue
443 function onRedirectToLogin($action, $user)
445 if (common_config('site', 'openid_only') || (!empty($user) && User_openid::hasOpenID($user->id))) {
446 common_redirect(common_local_url('openidlogin'), 303);
453 * Show some extra instructions for using OpenID
455 * @param Action $action Action being executed
457 * @return boolean hook value
459 function onEndShowPageNotice($action)
461 $name = $action->trimmed('action');
466 if (common_logged_in()) {
467 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
468 // TRANS: This message contains Markdown links in the form (description)[link].
469 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
470 '[Add an OpenID to your account](%%action.openidsettings%%)!');
472 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
473 // TRANS: This message contains Markdown links in the form (description)[link].
474 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
475 'Try our [OpenID registration]'.
476 '(%%action.openidlogin%%)!)');
480 // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
481 // TRANS: This message contains Markdown links in the form (description)[link].
482 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
483 'Try our [OpenID login]'.
484 '(%%action.openidlogin%%)!)');
490 $output = common_markup_to_html($instr);
491 $action->raw($output);
496 * Load our document if requested
498 * @param string &$title Title to fetch
499 * @param string &$output HTML to output
501 * @return boolean hook value
503 function onStartLoadDoc(&$title, &$output)
505 if ($title == 'openid') {
506 $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
508 $c = file_get_contents($filename);
509 $output = common_markup_to_html($c);
510 return false; // success!
517 * Add our document to the global menu
519 * @param string $title Title being fetched
520 * @param string &$output HTML being output
522 * @return boolean hook value
524 function onEndDocsMenu(&$items) {
525 $items[] = array('doc',
526 array('title' => 'openid'),
527 _m('MENU', 'OpenID'),
528 _('Logging in with OpenID'),
536 * Assure that our data objects are available in the DB
538 * @return boolean hook value
540 function onCheckSchema()
542 $schema = Schema::get();
543 $schema->ensureTable('user_openid', User_openid::schemaDef());
544 $schema->ensureTable('user_openid_trustroot', User_openid_trustroot::schemaDef());
545 $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());
547 /* These are used by JanRain OpenID library */
549 $schema->ensureTable('oid_associations',
552 'server_url' => array('type' => 'blob', 'not null' => true),
553 'handle' => array('type' => 'varchar', 'length' => 255, 'not null' => true, 'default' => ''), // character set latin1,
554 'secret' => array('type' => 'blob'),
555 'issued' => array('type' => 'int'),
556 'lifetime' => array('type' => 'int'),
557 'assoc_type' => array('type' => 'varchar', 'length' => 64),
559 'primary key' => array(array('server_url', 255), 'handle'),
561 $schema->ensureTable('oid_nonces',
564 'server_url' => array('type' => 'varchar', 'length' => 2047),
565 'timestamp' => array('type' => 'int'),
566 'salt' => array('type' => 'char', 'length' => 40),
568 'unique keys' => array(
569 'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 255), 'timestamp', 'salt'),
577 * Add our tables to be deleted when a user is deleted
579 * @param User $user User being deleted
580 * @param array &$tables Array of table names
582 * @return boolean hook value
584 function onUserDeleteRelated($user, &$tables)
586 $tables[] = 'User_openid';
587 $tables[] = 'User_openid_trustroot';
592 * Add an OpenID tab to the admin panel
594 * @param Widget $nav Admin panel nav
596 * @return boolean hook value
598 function onEndAdminPanelNav($nav)
600 if (AdminPanelAction::canAdmin('openid')) {
602 $action_name = $nav->action->trimmed('action');
605 common_local_url('openidadminpanel'),
606 // TRANS: OpenID configuration menu item.
608 // TRANS: Tooltip for OpenID configuration menu item.
609 _m('OpenID configuration.'),
610 $action_name == 'openidadminpanel',
611 'nav_openid_admin_panel'
619 * Add OpenID information to the Account Management Control Document
620 * Event supplied by the Account Manager plugin
622 * @param array &$amcd Array that expresses the AMCD
624 * @return boolean hook value
627 function onEndAccountManagementControlDocument(&$amcd)
629 $amcd['auth-methods']['openid'] = array(
632 'path' => common_local_url('openidlogin'),
634 'identity' => 'openid_url'
641 * Add our version information to output
643 * @param array &$versions Array of version-data arrays
645 * @return boolean hook value
647 function onPluginVersion(&$versions)
649 $versions[] = array('name' => 'OpenID',
650 'version' => STATUSNET_VERSION,
651 'author' => 'Evan Prodromou, Craig Andrews',
652 'homepage' => 'http://status.net/wiki/Plugin:OpenID',
654 // TRANS: Plugin description.
655 _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
659 function onStartOAuthLoginForm($action, &$button)
661 if (common_config('site', 'openidonly')) {
662 // Cancel the regular password login form, we won't need it.
663 $this->showOAuthLoginForm($action);
664 // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
665 $button = _m('BUTTON', 'Continue');
668 // Leave the regular password login form in place.
669 // We'll add an OpenID link at bottom...?
675 * @fixme merge with common code for main OpenID login form
676 * @param HTMLOutputter $action
678 protected function showOAuthLoginForm($action)
680 $action->elementStart('fieldset');
681 // TRANS: OpenID plugin logon form legend.
682 $action->element('legend', null, _m('LEGEND','OpenID login'));
684 $action->elementStart('ul', 'form_data');
685 $action->elementStart('li');
686 $provider = common_config('openid', 'trusted_provider');
687 $appendUsername = common_config('openid', 'append_username');
689 // TRANS: Field label.
690 $action->element('label', array(), _m('OpenID provider'));
691 $action->element('span', array(), $provider);
692 if ($appendUsername) {
693 $action->element('input', array('id' => 'openid_username',
694 'name' => 'openid_username',
695 'style' => 'float: none'));
697 $action->element('p', 'form_guide',
698 // TRANS: Form guide.
699 ($appendUsername ? _m('Enter your username.') . ' ' : '') .
700 // TRANS: Form guide.
701 _m('You will be sent to the provider\'s site for authentication.'));
702 $action->hidden('openid_url', $provider);
704 // TRANS: OpenID plugin logon form field label.
705 $action->input('openid_url', _m('OpenID URL'),
707 // TRANS: OpenID plugin logon form field instructions.
708 _m('Your OpenID URL.'));
710 $action->elementEnd('li');
711 $action->elementEnd('ul');
713 $action->elementEnd('fieldset');
717 * Handle a POST user credential check in apioauthauthorization.
718 * If given an OpenID URL, we'll pass us over to the regular things
719 * and then redirect back here on completion.
721 * @fixme merge with common code for main OpenID login form
722 * @param HTMLOutputter $action
724 function onStartOAuthLoginCheck($action, &$user)
726 $provider = common_config('openid', 'trusted_provider');
728 $openid_url = $provider;
729 if (common_config('openid', 'append_username')) {
730 $openid_url .= $action->trimmed('openid_username');
733 $openid_url = $action->trimmed('openid_url');
737 require_once dirname(__FILE__) . '/openid.php';
738 oid_assert_allowed($openid_url);
740 $returnto = common_local_url(
744 'oauth_token' => $action->arg('oauth_token'),
745 'mode' => $action->arg('mode')
748 common_set_returnto($returnto);
750 // This will redirect if functional...
751 $result = oid_authenticate($openid_url,
752 'finishopenidlogin');
753 if (is_string($result)) { # error message
754 throw new ServerException($result);
764 * Add link in user's XRD file to allow OpenID login.
766 * This link in the XRD should let users log in with their
767 * Webfinger identity to services that support it. See
768 * http://webfinger.org/login for an example.
770 * @param XML_XRD $xrd Currently-displaying resource descriptor
771 * @param Profile $target The profile that it's for
773 * @return boolean hook value (always true)
776 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
778 $xrd->links[] = new XML_XRD_Element_Link(
779 'http://specs.openid.net/auth/2.0/provider',
780 $target->profileurl);
786 * Add links in the user's profile block to their OpenID URLs.
788 * @param Profile $profile The profile being shown
789 * @param Array &$links Writeable array of arrays (href, text, image).
791 * @return boolean hook value (true)
794 function onOtherAccountProfiles($profile, &$links)
796 $prefs = User_openid_prefs::getKV('user_id', $profile->id);
798 if (empty($prefs) || !$prefs->hide_profile_link) {
800 $oid = new User_openid();
802 $oid->user_id = $profile->id;
805 while ($oid->fetch()) {
806 $links[] = array('href' => $oid->display,
807 'text' => _('OpenID'),
808 'image' => $this->path("icons/openid-16x16.gif"));