]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/OpenIDPlugin.php
Merge branch 'master' of gitorious.org:statusnet/mainline
[quix0rs-gnu-social.git] / plugins / OpenID / OpenIDPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * PHP version 5
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * @category  Plugin
21  * @package   StatusNet
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/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Plugin for OpenID authentication and identity
36  *
37  * This class enables consumer support for OpenID, the distributed authentication
38  * and identity system.
39  *
40  * @category Plugin
41  * @package  StatusNet
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/
48  */
49 class OpenIDPlugin extends Plugin
50 {
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;
54
55     function initialize()
56     {
57         parent::initialize();
58         if ($this->openidOnly !== null) {
59             global $config;
60             $config['site']['openidonly'] = (bool)$this->openidOnly;
61         }
62     }
63
64     /**
65      * Add OpenID-related paths to the router table
66      *
67      * Hook for RouterInitialized event.
68      *
69      * @param Net_URL_Mapper $m URL mapper
70      *
71      * @return boolean hook return
72      */
73     function onStartInitializeRouter($m)
74     {
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'));
84
85         return true;
86     }
87
88     /**
89      * In OpenID-only mode, disable paths for password stuff
90      *
91      * @param string $path     path to connect
92      * @param array  $defaults path defaults
93      * @param array  $rules    path rules
94      * @param array  $result   unused
95      *
96      * @return boolean hook return
97      */
98     function onStartConnectPath(&$path, &$defaults, &$rules, &$result)
99     {
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.
105             //
106             // We take those two over with redirects to ourselves
107             // over in onArgsInitialize().
108             static $block = array('main/recoverpassword',
109                                   'settings/password');
110
111             if (in_array($path, $block)) {
112                 return false;
113             }
114         }
115
116         return true;
117     }
118
119     /**
120      * If we've been hit with password-login args, redirect
121      *
122      * @param array $args args (URL, Get, post)
123      *
124      * @return boolean hook return
125      */
126     function onArgsInitialize($args)
127     {
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'));
133                     exit(0);
134                 } else if ($action == 'passwordsettings') {
135                     common_redirect(common_local_url('openidsettings'));
136                     exit(0);
137                 } else if ($action == 'recoverpassword') {
138                     // TRANS: Client exception thrown when an action is not available.
139                     throw new ClientException(_m('Unavailable action.'));
140                 }
141             }
142         }
143         return true;
144     }
145
146     /**
147      * Public XRDS output hook
148      *
149      * Puts the bits of code needed by some OpenID providers to show
150      * we're good citizens.
151      *
152      * @param Action       $action         Action being executed
153      * @param XMLOutputter &$xrdsOutputter Output channel
154      *
155      * @return boolean hook return
156      */
157     function onEndPublicXRDS($action, &$xrdsOutputter)
158     {
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');
163         //consumer
164         foreach (array('finishopenidlogin', 'finishaddopenid') as $finish) {
165             $xrdsOutputter->showXrdsService(Auth_OpenID_RP_RETURN_TO_URL_TYPE,
166                                             common_local_url($finish));
167         }
168         //provider
169         $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/server',
170                                         common_local_url('openidserver'),
171                                         null,
172                                         null,
173                                         'http://specs.openid.net/auth/2.0/identifier_select');
174         $xrdsOutputter->elementEnd('XRD');
175     }
176
177     /**
178      * User XRDS output hook
179      *
180      * Puts the bits of code needed to discover OpenID endpoints.
181      *
182      * @param Action       $action         Action being executed
183      * @param XMLOutputter &$xrdsOutputter Output channel
184      *
185      * @return boolean hook return
186      */
187     function onEndUserXRDS($action, &$xrdsOutputter)
188     {
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');
194
195         //consumer
196         $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/return_to',
197                                         common_local_url('finishopenidlogin'));
198
199         //provider
200         $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/signon',
201                                         common_local_url('openidserver'),
202                                         null,
203                                         null,
204                                         common_profile_url($action->user->nickname));
205         $xrdsOutputter->elementEnd('XRD');
206     }
207
208     /**
209      * If we're in OpenID-only mode, hide all the main menu except OpenID login.
210      *
211      * @param Action $action Action being run
212      *
213      * @return boolean hook return
214      */
215     function onStartPrimaryNav($action)
216     {
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
222                               _m('MENU', 'Login'),
223                               $tooltip,
224                               false,
225                               'nav_login');
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
230                               _m('MENU', 'Help'),
231                               $tooltip,
232                               false,
233                               'nav_help');
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');
240             }
241             Event::handle('EndPrimaryNav', array($action));
242             return false;
243         }
244         return true;
245     }
246
247     /**
248      * Menu for login
249      *
250      * If we're in openidOnly mode, we disable the menu for all other login.
251      *
252      * @param Action $action Action being executed
253      *
254      * @return boolean hook return
255      */
256     function onStartLoginGroupNav($action)
257     {
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.
263             return false;
264         }
265
266         return true;
267     }
268
269     /**
270      * Menu item for login
271      *
272      * @param Action $action Action being executed
273      *
274      * @return boolean hook return
275      */
276     function onEndLoginGroupNav($action)
277     {
278         $this->showOpenIDLoginTab($action);
279
280         return true;
281     }
282
283     /**
284      * Show menu item for login
285      *
286      * @param Action $action Action being executed
287      *
288      * @return void
289      */
290     function showOpenIDLoginTab($action)
291     {
292         $action_name = $action->trimmed('action');
293
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');
300     }
301
302     /**
303      * Show menu item for password
304      *
305      * We hide it in openID-only mode
306      *
307      * @param Action $menu    Widget for menu
308      * @param void   &$unused Unused value
309      *
310      * @return void
311      */
312     function onStartAccountSettingsPasswordMenuItem($menu, &$unused) {
313         if (common_config('site', 'openidonly')) {
314             return false;
315         }
316         return true;
317     }
318
319     /**
320      * Menu item for OpenID settings
321      *
322      * @param Action $action Action being executed
323      *
324      * @return boolean hook return
325      */
326     function onEndAccountSettingsNav($action)
327     {
328         $action_name = $action->trimmed('action');
329
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');
336
337         return true;
338     }
339
340     /**
341      * Autoloader
342      *
343      * Loads our classes if they're requested.
344      *
345      * @param string $cls Class requested
346      *
347      * @return boolean hook return
348      */
349     function onAutoload($cls)
350     {
351         switch ($cls)
352         {
353         case 'OpenidloginAction':
354         case 'FinishopenidloginAction':
355         case 'FinishaddopenidAction':
356         case 'XrdsAction':
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';
363             return false;
364         case 'User_openid':
365         case 'User_openid_prefs':
366         case 'User_openid_trustroot':
367             require_once dirname(__FILE__) . '/' . $cls . '.php';
368             return false;
369         case 'Auth_OpenID_TeamsExtension':
370         case 'Auth_OpenID_TeamsRequest':
371         case 'Auth_OpenID_TeamsResponse':
372             require_once dirname(__FILE__) . '/extlib/teams-extension.php';
373             return false;
374         default:
375             return true;
376         }
377     }
378
379     /**
380      * Sensitive actions
381      *
382      * These actions should use https when SSL support is 'sometimes'
383      *
384      * @param Action  $action Action to form an URL for
385      * @param boolean &$ssl   Whether to mark it for SSL
386      *
387      * @return boolean hook return
388      */
389     function onSensitiveAction($action, &$ssl)
390     {
391         switch ($action)
392         {
393         case 'finishopenidlogin':
394         case 'finishaddopenid':
395             $ssl = true;
396             return false;
397         default:
398             return true;
399         }
400     }
401
402     /**
403      * Login actions
404      *
405      * These actions should be visible even when the site is marked private
406      *
407      * @param Action  $action Action to show
408      * @param boolean &$login Whether it's a login action
409      *
410      * @return boolean hook return
411      */
412     function onLoginAction($action, &$login)
413     {
414         switch ($action)
415         {
416         case 'openidlogin':
417         case 'finishopenidlogin':
418         case 'openidserver':
419             $login = true;
420             return false;
421         default:
422             return true;
423         }
424     }
425
426     /**
427      * We include a <meta> element linking to the userxrds page, for OpenID
428      * client-side authentication.
429      *
430      * @param Action $action Action being shown
431      *
432      * @return void
433      */
434     function onEndShowHeadElements($action)
435     {
436         if ($action instanceof ShowstreamAction) {
437             $action->element('link', array('rel' => 'openid2.provider',
438                                            'href' => common_local_url('openidserver')));
439             $action->element('link', array('rel' => 'openid2.local_id',
440                                            'href' => $action->profile->profileurl));
441             $action->element('link', array('rel' => 'openid.server',
442                                            'href' => common_local_url('openidserver')));
443             $action->element('link', array('rel' => 'openid.delegate',
444                                            'href' => $action->profile->profileurl));
445         }
446         return true;
447     }
448
449     /**
450      * Redirect to OpenID login if they have an OpenID
451      *
452      * @param Action $action Action being executed
453      * @param User   $user   User doing the action
454      *
455      * @return boolean whether to continue
456      */
457     function onRedirectToLogin($action, $user)
458     {
459         if (common_config('site', 'openid_only') || (!empty($user) && User_openid::hasOpenID($user->id))) {
460             common_redirect(common_local_url('openidlogin'), 303);
461             return false;
462         }
463         return true;
464     }
465
466     /**
467      * Show some extra instructions for using OpenID
468      *
469      * @param Action $action Action being executed
470      *
471      * @return boolean hook value
472      */
473     function onEndShowPageNotice($action)
474     {
475         $name = $action->trimmed('action');
476
477         switch ($name)
478         {
479         case 'register':
480             if (common_logged_in()) {
481                 // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
482                 // TRANS: This message contains Markdown links in the form (description)[link].
483                 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
484                   '[Add an OpenID to your account](%%action.openidsettings%%)!');
485             } else {
486                 // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
487                 // TRANS: This message contains Markdown links in the form (description)[link].
488                 $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
489                   'Try our [OpenID registration]'.
490                   '(%%action.openidlogin%%)!)');
491             }
492             break;
493         case 'login':
494             // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
495             // TRANS: This message contains Markdown links in the form (description)[link].
496             $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
497               'Try our [OpenID login]'.
498               '(%%action.openidlogin%%)!)');
499             break;
500         default:
501             return true;
502         }
503
504         $output = common_markup_to_html($instr);
505         $action->raw($output);
506         return true;
507     }
508
509     /**
510      * Load our document if requested
511      *
512      * @param string &$title  Title to fetch
513      * @param string &$output HTML to output
514      *
515      * @return boolean hook value
516      */
517     function onStartLoadDoc(&$title, &$output)
518     {
519         if ($title == 'openid') {
520             $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';
521
522             $c      = file_get_contents($filename);
523             $output = common_markup_to_html($c);
524             return false; // success!
525         }
526
527         return true;
528     }
529
530     /**
531      * Add our document to the global menu
532      *
533      * @param string $title   Title being fetched
534      * @param string &$output HTML being output
535      *
536      * @return boolean hook value
537      */
538     function onEndDocsMenu(&$items) {
539         $items[] = array('doc', 
540                          array('title' => 'openid'),
541                          _m('MENU', 'OpenID'),
542                          _('Logging in with OpenID'),
543                          'nav_doc_openid');
544         return true;
545     }
546
547     /**
548      * Data definitions
549      *
550      * Assure that our data objects are available in the DB
551      *
552      * @return boolean hook value
553      */
554     function onCheckSchema()
555     {
556         $schema = Schema::get();
557         $schema->ensureTable('user_openid',
558                              array(new ColumnDef('canonical', 'varchar',
559                                                  '255', false, 'PRI'),
560                                    new ColumnDef('display', 'varchar',
561                                                  '255', false, 'UNI'),
562                                    new ColumnDef('user_id', 'integer',
563                                                  null, false, 'MUL'),
564                                    new ColumnDef('created', 'datetime',
565                                                  null, false),
566                                    new ColumnDef('modified', 'timestamp')));
567         $schema->ensureTable('user_openid_trustroot',
568                              array(new ColumnDef('trustroot', 'varchar',
569                                                  '255', false, 'PRI'),
570                                    new ColumnDef('user_id', 'integer',
571                                                  null, false, 'PRI'),
572                                    new ColumnDef('created', 'datetime',
573                                                  null, false),
574                                    new ColumnDef('modified', 'timestamp')));
575
576         $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());
577
578         /* These are used by JanRain OpenID library */
579
580         $schema->ensureTable('oid_associations',
581                              array(
582                                  'fields' => array(
583                                      'server_url' => array('type' => 'blob', 'not null' => true),
584                                      'handle' => array('type' => 'varchar', 'length' => 255, 'not null' => true, 'default' => ''), // character set latin1,
585                                      'secret' => array('type' => 'blob'),
586                                      'issued' => array('type' => 'int'),
587                                      'lifetime' => array('type' => 'int'),
588                                      'assoc_type' => array('type' => 'varchar', 'length' => 64),
589                                  ),
590                                  'primary key' => array(array('server_url', 255), 'handle'),
591                              ));
592         $schema->ensureTable('oid_nonces',
593                              array(
594                                  'fields' => array(
595                                      'server_url' => array('type' => 'varchar', 'length' => 2047),
596                                      'timestamp' => array('type' => 'int'),
597                                      'salt' => array('type' => 'char', 'length' => 40),
598                                  ),
599                                  'unique keys' => array(
600                                      'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 255), 'timestamp', 'salt'),
601                                  ),
602                              ));
603
604         return true;
605     }
606
607     /**
608      * Add our tables to be deleted when a user is deleted
609      *
610      * @param User  $user    User being deleted
611      * @param array &$tables Array of table names
612      *
613      * @return boolean hook value
614      */
615     function onUserDeleteRelated($user, &$tables)
616     {
617         $tables[] = 'User_openid';
618         $tables[] = 'User_openid_trustroot';
619         return true;
620     }
621
622     /**
623      * Add an OpenID tab to the admin panel
624      *
625      * @param Widget $nav Admin panel nav
626      *
627      * @return boolean hook value
628      */
629     function onEndAdminPanelNav($nav)
630     {
631         if (AdminPanelAction::canAdmin('openid')) {
632
633             $action_name = $nav->action->trimmed('action');
634
635             $nav->out->menuItem(
636                 common_local_url('openidadminpanel'),
637                 // TRANS: OpenID configuration menu item.
638                 _m('MENU','OpenID'),
639                 // TRANS: Tooltip for OpenID configuration menu item.
640                 _m('OpenID configuration.'),
641                 $action_name == 'openidadminpanel',
642                 'nav_openid_admin_panel'
643             );
644         }
645
646         return true;
647     }
648
649     /**
650      * Add OpenID information to the Account Management Control Document
651      * Event supplied by the Account Manager plugin
652      *
653      * @param array &$amcd Array that expresses the AMCD
654      *
655      * @return boolean hook value
656      */
657
658     function onEndAccountManagementControlDocument(&$amcd)
659     {
660         $amcd['auth-methods']['openid'] = array(
661             'connect' => array(
662                 'method' => 'POST',
663                 'path' => common_local_url('openidlogin'),
664                 'params' => array(
665                     'identity' => 'openid_url'
666                 )
667             )
668         );
669     }
670
671     /**
672      * Add our version information to output
673      *
674      * @param array &$versions Array of version-data arrays
675      *
676      * @return boolean hook value
677      */
678     function onPluginVersion(&$versions)
679     {
680         $versions[] = array('name' => 'OpenID',
681                             'version' => STATUSNET_VERSION,
682                             'author' => 'Evan Prodromou, Craig Andrews',
683                             'homepage' => 'http://status.net/wiki/Plugin:OpenID',
684                             'rawdescription' =>
685                             // TRANS: Plugin description.
686                             _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
687         return true;
688     }
689
690     function onStartOAuthLoginForm($action, &$button)
691     {
692         if (common_config('site', 'openidonly')) {
693             // Cancel the regular password login form, we won't need it.
694             $this->showOAuthLoginForm($action);
695             // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
696             $button = _m('BUTTON', 'Continue');
697             return false;
698         } else {
699             // Leave the regular password login form in place.
700             // We'll add an OpenID link at bottom...?
701             return true;
702         }
703     }
704
705     /**
706      * @fixme merge with common code for main OpenID login form
707      * @param HTMLOutputter $action
708      */
709     protected function showOAuthLoginForm($action)
710     {
711         $action->elementStart('fieldset');
712         // TRANS: OpenID plugin logon form legend.
713         $action->element('legend', null, _m('LEGEND','OpenID login'));
714
715         $action->elementStart('ul', 'form_data');
716         $action->elementStart('li');
717         $provider = common_config('openid', 'trusted_provider');
718         $appendUsername = common_config('openid', 'append_username');
719         if ($provider) {
720             // TRANS: Field label.
721             $action->element('label', array(), _m('OpenID provider'));
722             $action->element('span', array(), $provider);
723             if ($appendUsername) {
724                 $action->element('input', array('id' => 'openid_username',
725                                               'name' => 'openid_username',
726                                               'style' => 'float: none'));
727             }
728             $action->element('p', 'form_guide',
729                            // TRANS: Form guide.
730                            ($appendUsername ? _m('Enter your username.') . ' ' : '') .
731                            // TRANS: Form guide.
732                            _m('You will be sent to the provider\'s site for authentication.'));
733             $action->hidden('openid_url', $provider);
734         } else {
735             // TRANS: OpenID plugin logon form field label.
736             $action->input('openid_url', _m('OpenID URL'),
737                          '',
738                         // TRANS: OpenID plugin logon form field instructions.
739                          _m('Your OpenID URL.'));
740         }
741         $action->elementEnd('li');
742         $action->elementEnd('ul');
743
744         $action->elementEnd('fieldset');
745     }
746
747     /**
748      * Handle a POST user credential check in apioauthauthorization.
749      * If given an OpenID URL, we'll pass us over to the regular things
750      * and then redirect back here on completion.
751      *
752      * @fixme merge with common code for main OpenID login form
753      * @param HTMLOutputter $action
754      */
755     function onStartOAuthLoginCheck($action, &$user)
756     {
757         $provider = common_config('openid', 'trusted_provider');
758         if ($provider) {
759             $openid_url = $provider;
760             if (common_config('openid', 'append_username')) {
761                 $openid_url .= $action->trimmed('openid_username');
762             }
763         } else {
764             $openid_url = $action->trimmed('openid_url');
765         }
766
767         if ($openid_url) {
768             require_once dirname(__FILE__) . '/openid.php';
769             oid_assert_allowed($openid_url);
770
771             $returnto = common_local_url(
772                 'ApiOauthAuthorize',
773                 array(),
774                 array(
775                     'oauth_token' => $action->arg('oauth_token'),
776                     'mode'        => $action->arg('mode')
777                 )
778             );
779             common_set_returnto($returnto);
780
781             // This will redirect if functional...
782             $result = oid_authenticate($openid_url,
783                                        'finishopenidlogin');
784             if (is_string($result)) { # error message
785                 throw new ServerException($result);
786             } else {
787                 exit(0);
788             }
789         }
790
791         return true;
792     }
793
794     /**
795      * Add link in user's XRD file to allow OpenID login.
796      *
797      * This link in the XRD should let users log in with their
798      * Webfinger identity to services that support it. See
799      * http://webfinger.org/login for an example.
800      *
801      * @param XRD  &$xrd Currently-displaying XRD object
802      * @param User $user The user that it's for
803      *
804      * @return boolean hook value (always true)
805      */
806
807     function onEndXrdActionLinks(&$xrd, $user)
808     {
809         $profile = $user->getProfile();
810
811         if (!empty($profile)) {
812             $xrd->links[] = array('rel' => 'http://specs.openid.net/auth/2.0/provider',
813                                   'href' => $profile->profileurl);
814         }
815
816         return true;
817     }
818
819     /**
820      * Add links in the user's profile block to their OpenID URLs.
821      *
822      * @param Profile $profile The profile being shown
823      * @param Array   &$links  Writeable array of arrays (href, text, image).
824      *
825      * @return boolean hook value (true)
826      */
827     
828     function onOtherAccountProfiles($profile, &$links)
829     {
830         $prefs = User_openid_prefs::staticGet('user_id', $profile->id);
831
832         if (empty($prefs) || !$prefs->hide_profile_link) {
833
834             $oid = new User_openid();
835
836             $oid->user_id = $profile->id;
837
838             if ($oid->find()) {
839                 while ($oid->fetch()) {
840                     $links[] = array('href' => $oid->display,
841                                      'text' => _('OpenID'),
842                                      'image' => $this->path("icons/openid-16x16.gif"));
843                 }
844             }
845         }
846
847         return true;
848     }
849 }