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 $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 * If we're in OpenID-only mode, hide all the main menu except OpenID login.
180 * @param Action $action Action being run
182 * @return boolean hook return
184 function onStartPrimaryNav($action)
186 if (common_config('site', 'openidonly') && !common_logged_in()) {
187 // TRANS: Tooltip for main menu option "Login"
188 $tooltip = _m('TOOLTIP', 'Login to the site.');
189 $action->menuItem(common_local_url('openidlogin'),
190 // TRANS: Main menu option when not logged in to log in
195 // TRANS: Tooltip for main menu option "Help"
196 $tooltip = _m('TOOLTIP', 'Help me!');
197 $action->menuItem(common_local_url('doc', array('title' => 'help')),
198 // TRANS: Main menu option for help on the StatusNet site
203 if (!common_config('site', 'private')) {
204 // TRANS: Tooltip for main menu option "Search"
205 $tooltip = _m('TOOLTIP', 'Search for people or text.');
206 $action->menuItem(common_local_url('peoplesearch'),
207 // TRANS: Main menu option when logged in or when the StatusNet instance is not private
208 _m('MENU', 'Search'), $tooltip, false, 'nav_search');
210 Event::handle('EndPrimaryNav', array($action));
219 * If we're in openidOnly mode, we disable the menu for all other login.
221 * @param Action $action Action being executed
223 * @return boolean hook return
225 function onStartLoginGroupNav($action)
227 if (common_config('site', 'openidonly')) {
228 $this->showOpenIDLoginTab($action);
229 // Even though we replace this code, we
230 // DON'T run the End* hook, to keep others from
231 // adding tabs. Not nice, but.
239 * Menu item for login
241 * @param Action $action Action being executed
243 * @return boolean hook return
245 function onEndLoginGroupNav($action)
247 $this->showOpenIDLoginTab($action);
253 * Show menu item for login
255 * @param Action $action Action being executed
259 function showOpenIDLoginTab($action)
261 $action_name = $action->trimmed('action');
263 $action->menuItem(common_local_url('openidlogin'),
264 // TRANS: OpenID plugin menu item on site logon page.
265 _m('MENU', 'OpenID'),
266 // TRANS: OpenID plugin tooltip for logon menu item.
267 _m('Login or register with OpenID.'),
268 $action_name === 'openidlogin');
272 * Show menu item for password
274 * We hide it in openID-only mode
276 * @param Action $menu Widget for menu
277 * @param void &$unused Unused value
281 function onStartAccountSettingsPasswordMenuItem($menu, &$unused) {
282 if (common_config('site', 'openidonly')) {
289 * Menu item for OpenID settings
291 * @param Action $action Action being executed
293 * @return boolean hook return
295 function onEndAccountSettingsNav($action)
297 $action_name = $action->trimmed('action');
299 $action->menuItem(common_local_url('openidsettings'),
300 // TRANS: OpenID plugin menu item on user settings page.
301 _m('MENU', 'OpenID'),
302 // TRANS: OpenID plugin tooltip for user settings menu item.
303 _m('Add or remove OpenIDs.'),
304 $action_name === 'openidsettings');
312 * Loads our classes if they're requested.
314 * @param string $cls Class requested
316 * @return boolean hook return
318 function onAutoload($cls)
322 case 'Auth_OpenID_TeamsExtension':
323 case 'Auth_OpenID_TeamsRequest':
324 case 'Auth_OpenID_TeamsResponse':
325 require_once dirname(__FILE__) . '/extlib/teams-extension.php';
329 return parent::onAutoload($cls);
335 * These actions should be visible even when the site is marked private
337 * @param Action $action Action to show
338 * @param boolean &$login Whether it's a login action
340 * @return boolean hook return
342 function onLoginAction($action, &$login)
347 case 'finishopenidlogin':
357 * We include a <meta> element linking to the webfinger resource page,
358 * for OpenID client-side authentication.
360 * @param Action $action Action being shown
364 function onEndShowHeadElements(Action $action)
366 if ($action instanceof ShowstreamAction) {
367 $action->element('link', array('rel' => 'openid2.provider',
368 'href' => common_local_url('openidserver')));
369 $action->element('link', array('rel' => 'openid2.local_id',
370 'href' => $action->getTarget()->getUrl()));
371 $action->element('link', array('rel' => 'openid.server',
372 'href' => common_local_url('openidserver')));
373 $action->element('link', array('rel' => 'openid.delegate',
374 'href' => $action->getTarget()->getUrl()));
377 if ($action instanceof SitestreamAction) {
378 $action->element('meta', array('http-equiv' => 'X-XRDS-Location',
379 'content' => common_local_url('publicxrds')));
385 * Redirect to OpenID login if they have an OpenID
387 * @param Action $action Action being executed
388 * @param User $user User doing the action
390 * @return boolean whether to continue
392 function onRedirectToLogin($action, $user)
394 if (common_config('site', 'openidonly') || (!empty($user) && User_openid::hasOpenID($user->id))) {
395 common_redirect(common_local_url('openidlogin'), 303);
401 * Show some extra instructions for using OpenID
403 * @param Action $action Action being executed
405 * @return boolean hook value
407 function onEndShowPageNotice($action)
409 $name = $action->trimmed('action');
414 if (common_logged_in()) {
415 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
416 // TRANS: This message contains Markdown links in the form (description)[link].
417 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
418 '[Add an OpenID to your account](%%action.openidsettings%%)!');
420 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
421 // TRANS: This message contains Markdown links in the form (description)[link].
422 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
423 'Try our [OpenID registration]'.
424 '(%%action.openidlogin%%)!)');
428 // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
429 // TRANS: This message contains Markdown links in the form (description)[link].
430 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
431 'Try our [OpenID login]'.
432 '(%%action.openidlogin%%)!)');
438 $output = common_markup_to_html($instr);
439 $action->raw($output);
444 * Load our document if requested
446 * @param string &$title Title to fetch
447 * @param string &$output HTML to output
449 * @return boolean hook value
451 function onStartLoadDoc(&$title, &$output)
453 if ($title == 'openid') {
454 $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
456 $c = file_get_contents($filename);
457 $output = common_markup_to_html($c);
458 return false; // success!
465 * Add our document to the global menu
467 * @param string $title Title being fetched
468 * @param string &$output HTML being output
470 * @return boolean hook value
472 function onEndDocsMenu(&$items) {
473 $items[] = array('doc',
474 array('title' => 'openid'),
475 _m('MENU', 'OpenID'),
476 _('Logging in with OpenID'),
484 * Assure that our data objects are available in the DB
486 * @return boolean hook value
488 function onCheckSchema()
490 $schema = Schema::get();
491 $schema->ensureTable('user_openid', User_openid::schemaDef());
492 $schema->ensureTable('user_openid_trustroot', User_openid_trustroot::schemaDef());
493 $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());
495 /* These are used by JanRain OpenID library */
497 $schema->ensureTable('oid_associations',
500 'server_url' => array('type' => 'blob', 'not null' => true),
501 'handle' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'default' => ''), // character set latin1,
502 'secret' => array('type' => 'blob'),
503 'issued' => array('type' => 'int'),
504 'lifetime' => array('type' => 'int'),
505 'assoc_type' => array('type' => 'varchar', 'length' => 64),
507 'primary key' => array(array('server_url', 191), 'handle'),
509 $schema->ensureTable('oid_nonces',
512 'server_url' => array('type' => 'varchar', 'length' => 2047),
513 'timestamp' => array('type' => 'int'),
514 'salt' => array('type' => 'char', 'length' => 40),
516 'unique keys' => array(
517 'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 191), 'timestamp', 'salt'),
525 * Add our tables to be deleted when a user is deleted
527 * @param User $user User being deleted
528 * @param array &$tables Array of table names
530 * @return boolean hook value
532 function onUserDeleteRelated($user, &$tables)
534 $tables[] = 'User_openid';
535 $tables[] = 'User_openid_trustroot';
540 * Add an OpenID tab to the admin panel
542 * @param Widget $nav Admin panel nav
544 * @return boolean hook value
546 function onEndAdminPanelNav($nav)
548 if (AdminPanelAction::canAdmin('openid')) {
550 $action_name = $nav->action->trimmed('action');
553 common_local_url('openidadminpanel'),
554 // TRANS: OpenID configuration menu item.
556 // TRANS: Tooltip for OpenID configuration menu item.
557 _m('OpenID configuration.'),
558 $action_name == 'openidadminpanel',
559 'nav_openid_admin_panel'
567 * Add OpenID information to the Account Management Control Document
568 * Event supplied by the Account Manager plugin
570 * @param array &$amcd Array that expresses the AMCD
572 * @return boolean hook value
575 function onEndAccountManagementControlDocument(&$amcd)
577 $amcd['auth-methods']['openid'] = array(
580 'path' => common_local_url('openidlogin'),
582 'identity' => 'openid_url'
589 * Add our version information to output
591 * @param array &$versions Array of version-data arrays
593 * @return boolean hook value
595 function onPluginVersion(array &$versions)
597 $versions[] = array('name' => 'OpenID',
598 'version' => GNUSOCIAL_VERSION,
599 'author' => 'Evan Prodromou, Craig Andrews',
600 'homepage' => 'http://status.net/wiki/Plugin:OpenID',
602 // TRANS: Plugin description.
603 _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
607 function onStartOAuthLoginForm($action, &$button)
609 if (common_config('site', 'openidonly')) {
610 // Cancel the regular password login form, we won't need it.
611 $this->showOAuthLoginForm($action);
612 // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
613 $button = _m('BUTTON', 'Continue');
616 // Leave the regular password login form in place.
617 // We'll add an OpenID link at bottom...?
623 * @fixme merge with common code for main OpenID login form
624 * @param HTMLOutputter $action
626 protected function showOAuthLoginForm($action)
628 $action->elementStart('fieldset');
629 // TRANS: OpenID plugin logon form legend.
630 $action->element('legend', null, _m('LEGEND','OpenID login'));
632 $action->elementStart('ul', 'form_data');
633 $action->elementStart('li');
634 $provider = common_config('openid', 'trusted_provider');
635 $appendUsername = common_config('openid', 'append_username');
637 // TRANS: Field label.
638 $action->element('label', array(), _m('OpenID provider'));
639 $action->element('span', array(), $provider);
640 if ($appendUsername) {
641 $action->element('input', array('id' => 'openid_username',
642 'name' => 'openid_username',
643 'style' => 'float: none'));
645 $action->element('p', 'form_guide',
646 // TRANS: Form guide.
647 ($appendUsername ? _m('Enter your username.') . ' ' : '') .
648 // TRANS: Form guide.
649 _m('You will be sent to the provider\'s site for authentication.'));
650 $action->hidden('openid_url', $provider);
652 // TRANS: OpenID plugin logon form field label.
653 $action->input('openid_url', _m('OpenID URL'),
655 // TRANS: OpenID plugin logon form field instructions.
656 _m('Your OpenID URL.'));
658 $action->elementEnd('li');
659 $action->elementEnd('ul');
661 $action->elementEnd('fieldset');
665 * Handle a POST user credential check in apioauthauthorization.
666 * If given an OpenID URL, we'll pass us over to the regular things
667 * and then redirect back here on completion.
669 * @fixme merge with common code for main OpenID login form
670 * @param HTMLOutputter $action
672 function onStartOAuthLoginCheck($action, &$user)
674 $provider = common_config('openid', 'trusted_provider');
676 $openid_url = $provider;
677 if (common_config('openid', 'append_username')) {
678 $openid_url .= $action->trimmed('openid_username');
681 $openid_url = $action->trimmed('openid_url');
685 require_once dirname(__FILE__) . '/openid.php';
686 oid_assert_allowed($openid_url);
688 $returnto = common_local_url(
692 'oauth_token' => $action->arg('oauth_token'),
693 'mode' => $action->arg('mode')
696 common_set_returnto($returnto);
698 // This will redirect if functional...
699 $result = oid_authenticate($openid_url,
700 'finishopenidlogin');
701 if (is_string($result)) { # error message
702 throw new ServerException($result);
712 * Add link in user's XRD file to allow OpenID login.
714 * This link in the XRD should let users log in with their
715 * Webfinger identity to services that support it. See
716 * http://webfinger.org/login for an example.
718 * @param XML_XRD $xrd Currently-displaying resource descriptor
719 * @param Profile $target The profile that it's for
721 * @return boolean hook value (always true)
724 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
726 $xrd->links[] = new XML_XRD_Element_Link(
727 'http://specs.openid.net/auth/2.0/provider',
728 $target->profileurl);
734 * Add links in the user's profile block to their OpenID URLs.
736 * @param Profile $profile The profile being shown
737 * @param Array &$links Writeable array of arrays (href, text, image).
739 * @return boolean hook value (true)
742 function onOtherAccountProfiles($profile, &$links)
744 $prefs = User_openid_prefs::getKV('user_id', $profile->id);
746 if (empty($prefs) || !$prefs->hide_profile_link) {
748 $oid = new User_openid();
750 $oid->user_id = $profile->id;
753 while ($oid->fetch()) {
754 $links[] = array('href' => $oid->display,
755 'text' => _('OpenID'),
756 'image' => $this->path("icons/openid-16x16.gif"));