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(array &$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 use https when SSL support is 'sometimes'
337 * @param Action $action Action to form an URL for
338 * @param boolean &$ssl Whether to mark it for SSL
340 * @return boolean hook return
342 function onSensitiveAction($action, &$ssl)
346 case 'finishopenidlogin':
347 case 'finishaddopenid':
358 * These actions should be visible even when the site is marked private
360 * @param Action $action Action to show
361 * @param boolean &$login Whether it's a login action
363 * @return boolean hook return
365 function onLoginAction($action, &$login)
370 case 'finishopenidlogin':
380 * We include a <meta> element linking to the webfinger resource page,
381 * for OpenID client-side authentication.
383 * @param Action $action Action being shown
387 function onEndShowHeadElements(Action $action)
389 if ($action instanceof ShowstreamAction) {
390 $action->element('link', array('rel' => 'openid2.provider',
391 'href' => common_local_url('openidserver')));
392 $action->element('link', array('rel' => 'openid2.local_id',
393 'href' => $action->getTarget()->getUrl()));
394 $action->element('link', array('rel' => 'openid.server',
395 'href' => common_local_url('openidserver')));
396 $action->element('link', array('rel' => 'openid.delegate',
397 'href' => $action->getTarget()->getUrl()));
400 if ($action instanceof SitestreamAction) {
401 $action->element('meta', array('http-equiv' => 'X-XRDS-Location',
402 'content' => common_local_url('publicxrds')));
408 * Redirect to OpenID login if they have an OpenID
410 * @param Action $action Action being executed
411 * @param User $user User doing the action
413 * @return boolean whether to continue
415 function onRedirectToLogin($action, $user)
417 if (common_config('site', 'openid_only') || (!empty($user) && User_openid::hasOpenID($user->id))) {
418 common_redirect(common_local_url('openidlogin'), 303);
424 * Show some extra instructions for using OpenID
426 * @param Action $action Action being executed
428 * @return boolean hook value
430 function onEndShowPageNotice($action)
432 $name = $action->trimmed('action');
437 if (common_logged_in()) {
438 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
439 // TRANS: This message contains Markdown links in the form (description)[link].
440 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
441 '[Add an OpenID to your account](%%action.openidsettings%%)!');
443 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
444 // TRANS: This message contains Markdown links in the form (description)[link].
445 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
446 'Try our [OpenID registration]'.
447 '(%%action.openidlogin%%)!)');
451 // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
452 // TRANS: This message contains Markdown links in the form (description)[link].
453 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
454 'Try our [OpenID login]'.
455 '(%%action.openidlogin%%)!)');
461 $output = common_markup_to_html($instr);
462 $action->raw($output);
467 * Load our document if requested
469 * @param string &$title Title to fetch
470 * @param string &$output HTML to output
472 * @return boolean hook value
474 function onStartLoadDoc(&$title, &$output)
476 if ($title == 'openid') {
477 $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
479 $c = file_get_contents($filename);
480 $output = common_markup_to_html($c);
481 return false; // success!
488 * Add our document to the global menu
490 * @param string $title Title being fetched
491 * @param string &$output HTML being output
493 * @return boolean hook value
495 function onEndDocsMenu(&$items) {
496 $items[] = array('doc',
497 array('title' => 'openid'),
498 _m('MENU', 'OpenID'),
499 _('Logging in with OpenID'),
507 * Assure that our data objects are available in the DB
509 * @return boolean hook value
511 function onCheckSchema()
513 $schema = Schema::get();
514 $schema->ensureTable('user_openid', User_openid::schemaDef());
515 $schema->ensureTable('user_openid_trustroot', User_openid_trustroot::schemaDef());
516 $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());
518 /* These are used by JanRain OpenID library */
520 $schema->ensureTable('oid_associations',
523 'server_url' => array('type' => 'blob', 'not null' => true),
524 'handle' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'default' => ''), // character set latin1,
525 'secret' => array('type' => 'blob'),
526 'issued' => array('type' => 'int'),
527 'lifetime' => array('type' => 'int'),
528 'assoc_type' => array('type' => 'varchar', 'length' => 64),
530 'primary key' => array(array('server_url', 191), 'handle'),
532 $schema->ensureTable('oid_nonces',
535 'server_url' => array('type' => 'varchar', 'length' => 2047),
536 'timestamp' => array('type' => 'int'),
537 'salt' => array('type' => 'char', 'length' => 40),
539 'unique keys' => array(
540 'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 191), 'timestamp', 'salt'),
548 * Add our tables to be deleted when a user is deleted
550 * @param User $user User being deleted
551 * @param array &$tables Array of table names
553 * @return boolean hook value
555 function onUserDeleteRelated($user, &$tables)
557 $tables[] = 'User_openid';
558 $tables[] = 'User_openid_trustroot';
563 * Add an OpenID tab to the admin panel
565 * @param Widget $nav Admin panel nav
567 * @return boolean hook value
569 function onEndAdminPanelNav(Menu $nav)
571 if (AdminPanelAction::canAdmin('openid')) {
573 $action_name = $nav->action->trimmed('action');
576 common_local_url('openidadminpanel'),
577 // TRANS: OpenID configuration menu item.
579 // TRANS: Tooltip for OpenID configuration menu item.
580 _m('OpenID configuration.'),
581 $action_name == 'openidadminpanel',
582 'nav_openid_admin_panel'
590 * Add OpenID information to the Account Management Control Document
591 * Event supplied by the Account Manager plugin
593 * @param array &$amcd Array that expresses the AMCD
595 * @return boolean hook value
598 function onEndAccountManagementControlDocument(&$amcd)
600 $amcd['auth-methods']['openid'] = array(
603 'path' => common_local_url('openidlogin'),
605 'identity' => 'openid_url'
612 * Add our version information to output
614 * @param array &$versions Array of version-data arrays
616 * @return boolean hook value
618 function onPluginVersion(array &$versions)
620 $versions[] = array('name' => 'OpenID',
621 'version' => GNUSOCIAL_VERSION,
622 'author' => 'Evan Prodromou, Craig Andrews',
623 'homepage' => 'http://status.net/wiki/Plugin:OpenID',
625 // TRANS: Plugin description.
626 _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
630 function onStartOAuthLoginForm($action, &$button)
632 if (common_config('site', 'openidonly')) {
633 // Cancel the regular password login form, we won't need it.
634 $this->showOAuthLoginForm($action);
635 // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
636 $button = _m('BUTTON', 'Continue');
639 // Leave the regular password login form in place.
640 // We'll add an OpenID link at bottom...?
646 * @fixme merge with common code for main OpenID login form
647 * @param HTMLOutputter $action
649 protected function showOAuthLoginForm($action)
651 $action->elementStart('fieldset');
652 // TRANS: OpenID plugin logon form legend.
653 $action->element('legend', null, _m('LEGEND','OpenID login'));
655 $action->elementStart('ul', 'form_data');
656 $action->elementStart('li');
657 $provider = common_config('openid', 'trusted_provider');
658 $appendUsername = common_config('openid', 'append_username');
660 // TRANS: Field label.
661 $action->element('label', array(), _m('OpenID provider'));
662 $action->element('span', array(), $provider);
663 if ($appendUsername) {
664 $action->element('input', array('id' => 'openid_username',
665 'name' => 'openid_username',
666 'style' => 'float: none'));
668 $action->element('p', 'form_guide',
669 // TRANS: Form guide.
670 ($appendUsername ? _m('Enter your username.') . ' ' : '') .
671 // TRANS: Form guide.
672 _m('You will be sent to the provider\'s site for authentication.'));
673 $action->hidden('openid_url', $provider);
675 // TRANS: OpenID plugin logon form field label.
676 $action->input('openid_url', _m('OpenID URL'),
678 // TRANS: OpenID plugin logon form field instructions.
679 _m('Your OpenID URL.'));
681 $action->elementEnd('li');
682 $action->elementEnd('ul');
684 $action->elementEnd('fieldset');
688 * Handle a POST user credential check in apioauthauthorization.
689 * If given an OpenID URL, we'll pass us over to the regular things
690 * and then redirect back here on completion.
692 * @fixme merge with common code for main OpenID login form
693 * @param HTMLOutputter $action
695 function onStartOAuthLoginCheck($action, &$user)
697 $provider = common_config('openid', 'trusted_provider');
699 $openid_url = $provider;
700 if (common_config('openid', 'append_username')) {
701 $openid_url .= $action->trimmed('openid_username');
704 $openid_url = $action->trimmed('openid_url');
708 require_once dirname(__FILE__) . '/openid.php';
709 oid_assert_allowed($openid_url);
711 $returnto = common_local_url(
715 'oauth_token' => $action->arg('oauth_token'),
716 'mode' => $action->arg('mode')
719 common_set_returnto($returnto);
721 // This will redirect if functional...
722 $result = oid_authenticate($openid_url,
723 'finishopenidlogin');
724 if (is_string($result)) { # error message
725 throw new ServerException($result);
735 * Add link in user's XRD file to allow OpenID login.
737 * This link in the XRD should let users log in with their
738 * Webfinger identity to services that support it. See
739 * http://webfinger.org/login for an example.
741 * @param XML_XRD $xrd Currently-displaying resource descriptor
742 * @param Profile $target The profile that it's for
744 * @return boolean hook value (always true)
747 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
749 $xrd->links[] = new XML_XRD_Element_Link(
750 'http://specs.openid.net/auth/2.0/provider',
751 $target->profileurl);
757 * Add links in the user's profile block to their OpenID URLs.
759 * @param Profile $profile The profile being shown
760 * @param Array &$links Writeable array of arrays (href, text, image).
762 * @return boolean hook value (true)
765 function onOtherAccountProfiles($profile, &$links)
767 $prefs = User_openid_prefs::getKV('user_id', $profile->id);
769 if (empty($prefs) || !$prefs->hide_profile_link) {
771 $oid = new User_openid();
773 $oid->user_id = $profile->id;
776 while ($oid->fetch()) {
777 $links[] = array('href' => $oid->display,
778 'text' => _('OpenID'),
779 'image' => $this->path("icons/openid-16x16.gif"));