code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2010 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:42+0000\n"
"Last-Translator: digitaldreamer <digitaldreamer@email.cz>\n"
"Language-Team: Tagalog (http://www.transifex.com/gnu-social/gnu-social/language/tl/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: tl\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr "Nagbubukas ng panlabas na mga kawing (iyon ay may rel=panlabas) sa ibabaw ng isang bagong dungawan o laylayan."


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:32+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Turkish (http://www.transifex.com/gnu-social/gnu-social/language/tr/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: tr\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr ""

repo_name: andremichelle/gnu

license: mit


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2010 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:42+0000\n"
"Last-Translator: digitaldreamer <digitaldreamer@email.cz>\n"
"Language-Team: Ukrainian (http://www.transifex.com/gnu-social/gnu-social/language/uk/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: uk\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr "Відкривати зовнішні посилання (тобто з rel=external) у новому вікні або вкладці."


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:32+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Urdu (Pakistan) (http://www.transifex.com/gnu-social/gnu-social/language/ur_PK/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: ur_PK\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr ""


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:32+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Vietnamese (http://www.transifex.com/gnu-social/gnu-social/language/vi/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: vi\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr ""


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:32+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Chinese (http://www.transifex.com/gnu-social/gnu-social/language/zh/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr ""


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2010 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:42+0000\n"
"Last-Translator: digitaldreamer <digitaldreamer@email.cz>\n"
"Language-Team: Chinese (China) (http://www.transifex.com/gnu-social/gnu-social/language/zh_CN/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh_CN\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr "打开外部链接 （即与 rel = 外部） 在一个新窗口或选项卡。"


code:
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-07 09:32+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Chinese (Taiwan) (http://www.transifex.com/gnu-social/gnu-social/language/zh_TW/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh_TW\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Plugin description.
#: OpenExternalLinkTargetPlugin.php:60
msgid "Opens external links (i.e. with rel=external) on a new window or tab."
msgstr ""


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Craig Andrews <candrews@integralblue.com>
 * @copyright 2009-2010 StatusNet, Inc.
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Plugin for OpenID authentication and identity
 *
 * This class enables consumer support for OpenID, the distributed authentication
 * and identity system.
 *
 * Depends on: WebFinger plugin for HostMeta-lookup (user@host format)
 *
 * @category Plugin
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Craig Andrews <candrews@integralblue.com>
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 * @link     http://openid.net/
 */
class OpenIDPlugin extends Plugin
{
    const PLUGIN_VERSION = '2.1.1';

    // Plugin parameter: set true to disallow non-OpenID logins
    // If set, overrides the setting in database or $config['site']['openidonly']
    public $openidOnly = null;

    function initialize()
    {
        parent::initialize();
        if ($this->openidOnly !== null) {
            global $config;
            $config['site']['openidonly'] = (bool)$this->openidOnly;
        }
    }

    /**
     * Add OpenID-related paths to the router table
     *
     * Hook for RouterInitialized event.
     *
     * @param URLMapper $m URL mapper
     *
     * @return boolean hook return
     */
    public function onStartInitializeRouter(URLMapper $m)
    {
        $m->connect('main/openid', array('action' => 'openidlogin'));
        $m->connect('main/openidtrust', array('action' => 'openidtrust'));
        $m->connect('settings/openid', array('action' => 'openidsettings'));
        $m->connect('index.php?action=finishopenidlogin',
                    array('action' => 'finishopenidlogin'));
        $m->connect('index.php?action=finishaddopenid',
                    array('action' => 'finishaddopenid'));
        $m->connect('index.php?action=finishsynchopenid',
                    array('action' => 'finishsynchopenid'));
        $m->connect('main/openidserver', array('action' => 'openidserver'));
        $m->connect('panel/openid', array('action' => 'openidadminpanel'));

        return true;
    }

    /**
     * In OpenID-only mode, disable paths for password stuff
     *
     * @param string $path     path to connect
     * @param array  $defaults path defaults
     * @param array  $rules    path rules
     * @param array  $result   unused
     *
     * @return boolean hook return
     */
    function onStartConnectPath(&$path, &$defaults, &$rules, &$result)
    {
        if (common_config('site', 'openidonly')) {
            // Note that we should not remove the login and register
            // actions. Lots of auth-related things link to them,
            // such as when visiting a private site without a session
            // or revalidating a remembered login for admin work.
            //
            // We take those two over with redirects to ourselves
            // over in onArgsInitialize().
            static $block = array('main/recoverpassword',
                                  'settings/password');

            if (in_array($path, $block)) {
                return false;
            }
        }

        return true;
    }

    /**
     * If we've been hit with password-login args, redirect
     *
     * @param array $args args (URL, Get, post)
     *
     * @return boolean hook return
     */
    function onArgsInitialize($args)
    {
        if (common_config('site', 'openidonly')) {
            if (array_key_exists('action', $args)) {
                $action = trim($args['action']);
                if (in_array($action, array('login', 'register'))) {
                    common_redirect(common_local_url('openidlogin'));
                } else if ($action == 'passwordsettings') {
                    common_redirect(common_local_url('openidsettings'));
                } else if ($action == 'recoverpassword') {
                    // TRANS: Client exception thrown when an action is not available.
                    throw new ClientException(_m('Unavailable action.'));
                }
            }
        }
        return true;
    }

    /**
     * Public XRDS output hook
     *
     * Puts the bits of code needed by some OpenID providers to show
     * we're good citizens.
     *
     * @param Action       $action         Action being executed
     * @param XMLOutputter &$xrdsOutputter Output channel
     *
     * @return boolean hook return
     */
    function onEndPublicXRDS(Action $action, &$xrdsOutputter)
    {
        $xrdsOutputter->elementStart('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
                                                  'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
                                                  'version' => '2.0'));
        $xrdsOutputter->element('Type', null, 'xri://$xrds*simple');
        //consumer
        foreach (array('finishopenidlogin', 'finishaddopenid') as $finish) {
            $xrdsOutputter->showXrdsService(Auth_OpenID_RP_RETURN_TO_URL_TYPE,
                                            common_local_url($finish));
        }
        //provider
        $xrdsOutputter->showXrdsService('http://specs.openid.net/auth/2.0/server',
                                        common_local_url('openidserver'),
                                        null,
                                        null,
                                        'http://specs.openid.net/auth/2.0/identifier_select');
        $xrdsOutputter->elementEnd('XRD');
    }

    /**
     * If we're in OpenID-only mode, hide all the main menu except OpenID login.
     *
     * @param Action $action Action being run
     *
     * @return boolean hook return
     */
    function onStartPrimaryNav($action)
    {
        if (common_config('site', 'openidonly') && !common_logged_in()) {
            // TRANS: Tooltip for main menu option "Login"
            $tooltip = _m('TOOLTIP', 'Login to the site.');
            $action->menuItem(common_local_url('openidlogin'),
                              // TRANS: Main menu option when not logged in to log in
                              _m('MENU', 'Login'),
                              $tooltip,
                              false,
                              'nav_login');
            // TRANS: Tooltip for main menu option "Help"
            $tooltip = _m('TOOLTIP', 'Help me!');
            $action->menuItem(common_local_url('doc', array('title' => 'help')),
                              // TRANS: Main menu option for help on the StatusNet site
                              _m('MENU', 'Help'),
                              $tooltip,
                              false,
                              'nav_help');
            if (!common_config('site', 'private')) {
                // TRANS: Tooltip for main menu option "Search"
                $tooltip = _m('TOOLTIP', 'Search for people or text.');
                $action->menuItem(common_local_url('peoplesearch'),
                                  // TRANS: Main menu option when logged in or when the StatusNet instance is not private
                                  _m('MENU', 'Search'), $tooltip, false, 'nav_search');
            }
            Event::handle('EndPrimaryNav', array($action));
            return false;
        }
        return true;
    }

    /**
     * Menu for login
     *
     * If we're in openidOnly mode, we disable the menu for all other login.
     *
     * @param Action $action Action being executed
     *
     * @return boolean hook return
     */
    function onStartLoginGroupNav($action)
    {
        if (common_config('site', 'openidonly')) {
            $this->showOpenIDLoginTab($action);
            // Even though we replace this code, we
            // DON'T run the End* hook, to keep others from
            // adding tabs. Not nice, but.
            return false;
        }

        return true;
    }

    /**
     * Menu item for login
     *
     * @param Action $action Action being executed
     *
     * @return boolean hook return
     */
    function onEndLoginGroupNav($action)
    {
        $this->showOpenIDLoginTab($action);

        return true;
    }

    /**
     * Show menu item for login
     *
     * @param Action $action Action being executed
     *
     * @return void
     */
    function showOpenIDLoginTab($action)
    {
        $action_name = $action->trimmed('action');

        $action->menuItem(common_local_url('openidlogin'),
                          // TRANS: OpenID plugin menu item on site logon page.
                          _m('MENU', 'OpenID'),
                          // TRANS: OpenID plugin tooltip for logon menu item.
                          _m('Login or register with OpenID.'),
                          $action_name === 'openidlogin');
    }

    /**
     * Show menu item for password
     *
     * We hide it in openID-only mode
     *
     * @param Action $menu    Widget for menu
     * @param void   &$unused Unused value
     *
     * @return void
     */
    function onStartAccountSettingsPasswordMenuItem($menu, &$unused) {
        if (common_config('site', 'openidonly')) {
            return false;
        }
        return true;
    }

    /**
     * Menu item for OpenID settings
     *
     * @param Action $action Action being executed
     *
     * @return boolean hook return
     */
    function onEndAccountSettingsNav($action)
    {
        $action_name = $action->trimmed('action');

        $action->menuItem(common_local_url('openidsettings'),
                          // TRANS: OpenID plugin menu item on user settings page.
                          _m('MENU', 'OpenID'),
                          // TRANS: OpenID plugin tooltip for user settings menu item.
                          _m('Add or remove OpenIDs.'),
                          $action_name === 'openidsettings');

        return true;
    }

    /**
     * Autoloader
     *
     * Loads our classes if they're requested.
     *
     * @param string $cls Class requested
     *
     * @return boolean hook return
     */
    function onAutoload($cls)
    {
        switch ($cls)
        {
        case 'Auth_OpenID_TeamsExtension':
        case 'Auth_OpenID_TeamsRequest':
        case 'Auth_OpenID_TeamsResponse':
            require_once dirname(__FILE__) . '/extlib/teams-extension.php';
            return false;
        }

        return parent::onAutoload($cls);
    }

    /**
     * Login actions
     *
     * These actions should be visible even when the site is marked private
     *
     * @param Action  $action Action to show
     * @param boolean &$login Whether it's a login action
     *
     * @return boolean hook return
     */
    function onLoginAction($action, &$login)
    {
        switch ($action)
        {
        case 'openidlogin':
        case 'finishopenidlogin':
        case 'openidserver':
            $login = true;
            return false;
        default:
            return true;
        }
    }

    /**
     * We include a <meta> element linking to the webfinger resource page,
     * for OpenID client-side authentication.
     *
     * @param Action $action Action being shown
     *
     * @return void
     */
    function onEndShowHeadElements(Action $action)
    {
        if ($action instanceof ShowstreamAction) {
            $action->element('link', array('rel' => 'openid2.provider',
                                           'href' => common_local_url('openidserver')));
            $action->element('link', array('rel' => 'openid2.local_id',
                                           'href' => $action->getTarget()->getUrl()));
            $action->element('link', array('rel' => 'openid.server',
                                           'href' => common_local_url('openidserver')));
            $action->element('link', array('rel' => 'openid.delegate',
                                           'href' => $action->getTarget()->getUrl()));
        }

        if ($action instanceof SitestreamAction) {
            $action->element('meta', array('http-equiv' => 'X-XRDS-Location',
                                         'content' => common_local_url('publicxrds')));
        }
        return true;
    }

    /**
     * Redirect to OpenID login if they have an OpenID
     *
     * @param Action $action Action being executed
     * @param User   $user   User doing the action
     *
     * @return boolean whether to continue
     */
    function onRedirectToLogin($action, $user)
    {
        if (common_config('site', 'openidonly') || (!empty($user) && User_openid::hasOpenID($user->id))) {
            common_redirect(common_local_url('openidlogin'), 303);
        }
        return true;
    }

    /**
     * Show some extra instructions for using OpenID
     *
     * @param Action $action Action being executed
     *
     * @return boolean hook value
     */
    function onEndShowPageNotice($action)
    {
        $name = $action->trimmed('action');

        switch ($name)
        {
        case 'register':
            if (common_logged_in()) {
                // TRANS: Page notice for logged in users to try and get them to add an OpenID account to their StatusNet account.
                // TRANS: This message contains Markdown links in the form (description)[link].
                $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
                  '[Add an OpenID to your account](%%action.openidsettings%%)!');
            } else {
                // TRANS: Page notice for anonymous users to try and get them to register with an OpenID account.
                // TRANS: This message contains Markdown links in the form (description)[link].
                $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
                  'Try our [OpenID registration]'.
                  '(%%action.openidlogin%%)!)');
            }
            break;
        case 'login':
            // TRANS: Page notice on the login page to try and get them to log on with an OpenID account.
            // TRANS: This message contains Markdown links in the form (description)[link].
            $instr = _m('(Have an [OpenID](http://openid.net/)? ' .
              'Try our [OpenID login]'.
              '(%%action.openidlogin%%)!)');
            break;
        default:
            return true;
        }

        $output = common_markup_to_html($instr);
        $action->raw($output);
        return true;
    }

    /**
     * Load our document if requested
     *
     * @param string &$title  Title to fetch
     * @param string &$output HTML to output
     *
     * @return boolean hook value
     */
    function onStartLoadDoc(&$title, &$output)
    {
        if ($title == 'openid') {
            $filename = INSTALLDIR.'/plugins/OpenID/doc-src/openid';

            $c      = file_get_contents($filename);
            $output = common_markup_to_html($c);
            return false; // success!
        }

        return true;
    }

    /**
     * Add our document to the global menu
     *
     * @param string $title   Title being fetched
     * @param string &$output HTML being output
     *
     * @return boolean hook value
     */
    function onEndDocsMenu(&$items) {
        $items[] = array('doc',
                         array('title' => 'openid'),
                         _m('MENU', 'OpenID'),
                         _('Logging in with OpenID'),
                         'nav_doc_openid');
        return true;
    }

    /**
     * Data definitions
     *
     * Assure that our data objects are available in the DB
     *
     * @return boolean hook value
     */
    function onCheckSchema()
    {
        $schema = Schema::get();
        $schema->ensureTable('user_openid', User_openid::schemaDef());
        $schema->ensureTable('user_openid_trustroot', User_openid_trustroot::schemaDef());
        $schema->ensureTable('user_openid_prefs', User_openid_prefs::schemaDef());

        /* These are used by JanRain OpenID library */

        $schema->ensureTable('oid_associations',
                             array(
                                 'fields' => array(
                                     'server_url' => array('type' => 'blob', 'not null' => true),
                                     'handle' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'default' => ''), // character set latin1,
                                     'secret' => array('type' => 'blob'),
                                     'issued' => array('type' => 'int'),
                                     'lifetime' => array('type' => 'int'),
                                     'assoc_type' => array('type' => 'varchar', 'length' => 64),
                                 ),
                                 'primary key' => array(array('server_url', 191), 'handle'),
                             ));
        $schema->ensureTable('oid_nonces',
                             array(
                                 'fields' => array(
                                     'server_url' => array('type' => 'varchar', 'length' => 2047),
                                     'timestamp' => array('type' => 'int'),
                                     'salt' => array('type' => 'char', 'length' => 40),
                                 ),
                                 'unique keys' => array(
                                     'oid_nonces_server_url_timestamp_salt_key' => array(array('server_url', 191), 'timestamp', 'salt'),
                                 ),
                             ));

        return true;
    }

    /**
     * Add our tables to be deleted when a user is deleted
     *
     * @param User  $user    User being deleted
     * @param array &$tables Array of table names
     *
     * @return boolean hook value
     */
    function onUserDeleteRelated($user, &$tables)
    {
        $tables[] = 'User_openid';
        $tables[] = 'User_openid_trustroot';
        return true;
    }

    /**
     * Add an OpenID tab to the admin panel
     *
     * @param Widget $nav Admin panel nav
     *
     * @return boolean hook value
     */
    function onEndAdminPanelNav($nav)
    {
        if (AdminPanelAction::canAdmin('openid')) {

            $action_name = $nav->action->trimmed('action');

            $nav->out->menuItem(
                common_local_url('openidadminpanel'),
                // TRANS: OpenID configuration menu item.
                _m('MENU','OpenID'),
                // TRANS: Tooltip for OpenID configuration menu item.
                _m('OpenID configuration.'),
                $action_name == 'openidadminpanel',
                'nav_openid_admin_panel'
            );
        }

        return true;
    }

    /**
     * Add OpenID information to the Account Management Control Document
     * Event supplied by the Account Manager plugin
     *
     * @param array &$amcd Array that expresses the AMCD
     *
     * @return boolean hook value
     */

    function onEndAccountManagementControlDocument(&$amcd)
    {
        $amcd['auth-methods']['openid'] = array(
            'connect' => array(
                'method' => 'POST',
                'path' => common_local_url('openidlogin'),
                'params' => array(
                    'identity' => 'openid_url'
                )
            )
        );
    }

    /**
     * Add our version information to output
     *
     * @param array &$versions Array of version-data arrays
     *
     * @return boolean hook value
     */
    function onPluginVersion(array &$versions)
    {
        $versions[] = array('name' => 'OpenID',
                            'version' => self::PLUGIN_VERSION,
                            'author' => 'Evan Prodromou, Craig Andrews',
                            'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OpenID',
                            'rawdescription' =>
                            // TRANS: Plugin description.
                            _m('Use <a href="http://openid.net/">OpenID</a> to login to the site.'));
        return true;
    }

    function onStartOAuthLoginForm($action, &$button)
    {
        if (common_config('site', 'openidonly')) {
            // Cancel the regular password login form, we won't need it.
            $this->showOAuthLoginForm($action);
            // TRANS: button label for OAuth authorization page when needing OpenID authentication first.
            $button = _m('BUTTON', 'Continue');
            return false;
        } else {
            // Leave the regular password login form in place.
            // We'll add an OpenID link at bottom...?
            return true;
        }
    }

    /**
     * @fixme merge with common code for main OpenID login form
     * @param HTMLOutputter $action
     */
    protected function showOAuthLoginForm($action)
    {
        $action->elementStart('fieldset');
        // TRANS: OpenID plugin logon form legend.
        $action->element('legend', null, _m('LEGEND','OpenID login'));

        $action->elementStart('ul', 'form_data');
        $action->elementStart('li');
        $provider = common_config('openid', 'trusted_provider');
        $appendUsername = common_config('openid', 'append_username');
        if ($provider) {
            // TRANS: Field label.
            $action->element('label', array(), _m('OpenID provider'));
            $action->element('span', array(), $provider);
            if ($appendUsername) {
                $action->element('input', array('id' => 'openid_username',
                                              'name' => 'openid_username',
                                              'style' => 'float: none'));
            }
            $action->element('p', 'form_guide',
                           // TRANS: Form guide.
                           ($appendUsername ? _m('Enter your username.') . ' ' : '') .
                           // TRANS: Form guide.
                           _m('You will be sent to the provider\'s site for authentication.'));
            $action->hidden('openid_url', $provider);
        } else {
            // TRANS: OpenID plugin logon form field label.
            $action->input('openid_url', _m('OpenID URL'),
                         '',
                        // TRANS: OpenID plugin logon form field instructions.
                         _m('Your OpenID URL.'));
        }
        $action->elementEnd('li');
        $action->elementEnd('ul');

        $action->elementEnd('fieldset');
    }

    /**
     * Handle a POST user credential check in apioauthauthorization.
     * If given an OpenID URL, we'll pass us over to the regular things
     * and then redirect back here on completion.
     *
     * @fixme merge with common code for main OpenID login form
     * @param HTMLOutputter $action
     */
    function onStartOAuthLoginCheck($action, &$user)
    {
        $provider = common_config('openid', 'trusted_provider');
        if ($provider) {
            $openid_url = $provider;
            if (common_config('openid', 'append_username')) {
                $openid_url .= $action->trimmed('openid_username');
            }
        } else {
            $openid_url = $action->trimmed('openid_url');
        }

        if ($openid_url) {
            require_once dirname(__FILE__) . '/openid.php';
            oid_assert_allowed($openid_url);

            $returnto = common_local_url(
                'ApiOAuthAuthorize',
                array(),
                array(
                    'oauth_token' => $action->arg('oauth_token'),
	            'mode'        => $action->arg('mode')
                )
            );
            common_set_returnto($returnto);

            // This will redirect if functional...
            $result = oid_authenticate($openid_url,
                                       'finishopenidlogin');
            if (is_string($result)) { # error message
                throw new ServerException($result);
            } else {
                exit(0);
            }
        }

        return true;
    }

    /**
     * Add link in user's XRD file to allow OpenID login.
     *
     * This link in the XRD should let users log in with their
     * Webfinger identity to services that support it. See
     * http://webfinger.org/login for an example.
     *
     * @param XML_XRD   $xrd    Currently-displaying resource descriptor
     * @param Profile   $target The profile that it's for
     *
     * @return boolean hook value (always true)
     */

    function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
    {
        $xrd->links[] = new XML_XRD_Element_Link(
                            'http://specs.openid.net/auth/2.0/provider',
                            $target->profileurl);

        return true;
    }

    /**
     * Add links in the user's profile block to their OpenID URLs.
     *
     * @param Profile $profile The profile being shown
     * @param Array   &$links  Writeable array of arrays (href, text, image).
     *
     * @return boolean hook value (true)
     */

    function onOtherAccountProfiles($profile, &$links)
    {
        $prefs = User_openid_prefs::getKV('user_id', $profile->id);

        if (empty($prefs) || !$prefs->hide_profile_link) {

            $oid = new User_openid();

            $oid->user_id = $profile->id;

            if ($oid->find()) {
                while ($oid->fetch()) {
                    $links[] = array('href' => $oid->display,
                                     'text' => _('OpenID'),
                                     'image' => $this->path("icons/openid-16x16.gif"));
                }
            }
        }

        return true;
    }
}


code:
The OpenID plugin allows users to use OpenID to login.

See: http://openid.net/

Installation
============
This plugin is enabled by default

Settings
========
openidonly: Whether we only allow logins through OpenID.
trusted_provider: URL to the OpenID provider.
append_username: Whether to append the username at the end of the OpenID URL

Example
=======
$config['site']['openidonly'] = true;
$config['openid']['trusted_provider'] = "http://example.org";
$config['openid']['append_username'] = true;
addPlugin('OpenID');

path: plugins/OpenID/README


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Complete adding an OpenID
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Settings
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

require_once INSTALLDIR.'/plugins/OpenID/openid.php';

/**
 * Complete adding an OpenID
 *
 * Handle the return from an OpenID verification
 *
 * @category Settings
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class FinishaddopenidAction extends Action
{
    public $msg = null;

    /**
     * Handle the redirect back from OpenID confirmation
     *
     * Check to see if the user's logged in, and then try
     * to use the OpenID login system.
     *
     * @param array $args $_REQUEST arguments
     *
     * @return void
     */
    public function handle()
    {
        parent::handle();
        if (!common_logged_in()) {
            // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
            $this->clientError(_m('Not logged in.'));
        } else {
            $this->tryLogin();
        }
    }

    /**
     * Try to log in using OpenID
     *
     * Check the OpenID for validity; potentially store it.
     *
     * @return void
     */
    public function tryLogin()
    {
        $consumer = oid_consumer();

        $response = $consumer->complete(common_local_url('finishaddopenid'));

        if ($response->status == Auth_OpenID_CANCEL) {
            // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
            $this->message(_m('OpenID authentication cancelled.'));
            return;
        } elseif ($response->status == Auth_OpenID_FAILURE) {
            // TRANS: OpenID authentication failed; display the error message.
            // TRANS: %s is the error message.
            $this->message(sprintf(
                _m('OpenID authentication failed: %s.'),
                $response->message
            ));
        } elseif ($response->status == Auth_OpenID_SUCCESS) {
            $display   = $response->getDisplayIdentifier();
            $canonical = ($response->endpoint && $response->endpoint->canonicalID) ?
              $response->endpoint->canonicalID : $display;

            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);

            if ($sreg_resp) {
                $sreg = $sreg_resp->contents();
            }

            // Launchpad teams extension
            if (!oid_check_teams($response)) {
                // TRANS: OpenID authentication error.
                $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
                return;
            }

            $cur = common_current_user();

            $other = oid_get_user($canonical);

            if ($other) {
                if ($other->id == $cur->id) {
                    // TRANS: Message in case a user tries to add an OpenID that is already connected to them.
                    $this->message(_m('You already have this OpenID!'));
                } else {
                    // TRANS: Message in case a user tries to add an OpenID that is already used by another user.
                    $this->message(_m('Someone else already has this OpenID.'));
                }
                return;
            }

            // start a transaction

            $cur->query('BEGIN');

            $result = oid_link_user($cur->id, $canonical, $display);

            if (!$result) {
                // TRANS: Message in case the OpenID object cannot be connected to the user.
                $this->message(_m('Error connecting user.'));
                return;
            }

            if (isset($_SESSION['openid_synch']) && $_SESSION['openid_synch']) {
                if (Event::handle('StartOpenIDUpdateUser', [$cur, $canonical, &$sreg])) {
                    if (!oid_update_user($cur, $sreg)) {
                        // TRANS: Message in case the user or the user profile cannot be saved in StatusNet.
                        $this->message(_m('Error updating profile.'));
                        return;
                    }
                }
                Event::handle('EndOpenIDUpdateUser', [$cur, $canonical, $sreg]);
            }

            unset($_SESSION['openid_synch']);

            // success!

            $cur->query('COMMIT');

            oid_set_last($display);

            common_redirect(common_local_url('openidsettings'), 303);
        }
    }

    /**
     * Show a failure message
     *
     * Something went wrong. Save the message, and show the page.
     *
     * @param string $msg Error message to show
     *
     * @return void
     */
    public function message($msg)
    {
        $this->message = $msg;
        $this->showPage();
    }

    /**
     * Title of the page
     *
     * @return string title
     */
    public function title()
    {
        // TRANS: Title after getting the status of the OpenID authorisation request.
        return _m('OpenID Login');
    }

    /**
     * Show error message
     *
     * @return void
     */
    public function showPageNotice()
    {
        if ($this->message) {
            $this->element('p', 'error', $this->message);
        }
    }
}


code:
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET')) {
    exit(1);
}

require_once INSTALLDIR.'/plugins/OpenID/openid.php';

class FinishopenidloginAction extends Action
{
    public $error = null;
    public $username = null;
    public $message = null;

    public function handle()
    {
        parent::handle();
        if (common_is_real_login()) {
            // TRANS: Client error message trying to log on with OpenID while already logged on.
            $this->clientError(_m('Already logged in.'));
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $token = $this->trimmed('token');
            if (!$token || $token != common_session_token()) {
                // TRANS: Message given when there is a problem with the user's session token.
                $this->showForm(_m('There was a problem with your session token. Try again, please.'));
                return;
            }
            if ($this->arg('create')) {
                if (!$this->boolean('license')) {
                    // TRANS: Message given if user does not agree with the site's license.
                    $this->showForm(
                        _m('You cannot register if you do not agree to the license.'),
                        $this->trimmed('newname')
                    );
                    return;
                }
                $this->createNewUser();
            } elseif ($this->arg('connect')) {
                $this->connectUser();
            } else {
                // TRANS: Messag given on an unknown error.
                $this->showForm(
                    _m('An unknown error has occured.'),
                    $this->trimmed('newname')
                );
            }
        } else {
            $this->tryLogin();
        }
    }

    public function showPageNotice()
    {
        if ($this->error) {
            $this->element('div', ['class' => 'error'], $this->error);
        } else {
            $this->element('div', 'instructions',
                           // TRANS: Instructions given after a first successful logon using OpenID.
                           // TRANS: %s is the site name.
                           sprintf(_m('This is the first time you have logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
        }
    }

    public function title()
    {
        // TRANS: Title
        return _m('TITLE', 'OpenID Account Setup');
    }

    public function showForm($error=null, $username=null)
    {
        $this->error = $error;
        $this->username = $username;

        $this->showPage();
    }

    /**
     * @fixme much of this duplicates core code, which is very fragile.
     * Should probably be replaced with an extensible mini version of
     * the core registration form.
     */
    public function showContent()
    {
        if (!empty($this->message_text)) {
            $this->element('div', ['class' => 'error'], $this->message_text);
            return;
        }

        // We don't recognize this OpenID, so we're going to give the user
        // two options, each in its own mini-form.
        //
        // First, they can create a new account using their OpenID auth
        // info. The profile will be pre-populated with whatever name,
        // email, and location we can get from the OpenID provider, so
        // all we ask for is the license confirmation.
        $this->elementStart('form', ['method' => 'post',
                                     'id' => 'account_create',
                                     'class' => 'form_settings',
                                     'action' => common_local_url('finishopenidlogin')]);
        $this->hidden('token', common_session_token());
        $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
        $this->element('legend', null,
                       // TRANS: Fieldset legend.
                       _m('Create new account'));
        $this->element('p', null,
                       // TRANS: Form guide.
                       _m('Create a new user with this nickname.'));
        $this->elementStart('ul', 'form_data');

        // Hook point for captcha etc
        Event::handle('StartRegistrationFormData', [$this]);

        $this->elementStart('li');
        // TRANS: Field label.
        $this->input('newname',
                     _m('New nickname'),
                     ($this->username) ? $this->username : '',
                     // TRANS: Field title.
                     _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
        $this->elementEnd('li');
        $this->elementStart('li');
        // TRANS: Field label.
        $this->input('email', _m('Email'),
                     $this->getEmail(),
                     // TRANS: Field title.
                     _m('Used only for updates, announcements, '.
                        'and password recovery.'));
        $this->elementEnd('li');

        // Hook point for captcha etc
        Event::handle('EndRegistrationFormData', [$this]);

        $this->elementStart('li');
        $this->element('input', ['type' => 'checkbox',
                                 'id' => 'license',
                                 'class' => 'checkbox',
                                 'name' => 'license',
                                 'value' => 'true']);
        $this->elementStart('label', ['for' => 'license',
                                      'class' => 'checkbox']);
        // TRANS: OpenID plugin link text.
        // TRANS: %s is a link to a license with the license name as link text.
        $message = _m('My text and files are available under %s ' .
                      'except this private data: password, ' .
                      'email address, IM address, and phone number.');
        $link = '' .
                htmlspecialchars(common_config('license', 'title')) .
                '';
        $this->raw(sprintf(htmlspecialchars($message), $link));
        $this->elementEnd('label');
        $this->elementEnd('li');
        $this->elementEnd('ul');
        // TRANS: Button label in form in which to create a new user on the site for an OpenID.
        $this->submit('create', _m('BUTTON', 'Create'));
        $this->elementEnd('fieldset');
        $this->elementEnd('form');

        // The second option is to attach this OpenID to an existing account
        // on the local system, which they need to provide a password for.
        $this->elementStart('form', ['method' => 'post',
                                     'id' => 'account_connect',
                                     'class' => 'form_settings',
                                     'action' => common_local_url('finishopenidlogin')]);
        $this->hidden('token', common_session_token());
        $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
        $this->element('legend', null,
                       // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
                       _m('Connect existing account'));
        $this->element('p', null,
                       // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
                       _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
        $this->elementStart('ul', 'form_data');
        $this->elementStart('li');
        // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
        $this->input('nickname', _m('Existing nickname'));
        $this->elementEnd('li');
        $this->elementStart('li');
        // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
        $this->password('password', _m('Password'));
        $this->elementEnd('li');
        $this->elementStart('li');
        // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
        $this->checkbox('openid-synch', _m('Synchronize Account'), false,
                        _m('Synchronize GNU social profile with this OpenID identity.'));
        $this->elementEnd('li');
        $this->elementEnd('ul');
        // TRANS: Button text in form in which to connect an OpenID to an existing user on the site.
        $this->submit('connect', _m('BUTTON', 'Connect'));
        $this->elementEnd('fieldset');
        $this->elementEnd('form');
    }

    /**
     * Get specified e-mail from the form, or the OpenID sreg info, or the
     * invite code.
     *
     * @return string
     */
    public function getEmail()
    {
        $email = $this->trimmed('email');
        if (!empty($email)) {
            return $email;
        }

        // Pull from openid thingy
        list($display, $canonical, $sreg) = $this->getSavedValues();
        if (!empty($sreg['email'])) {
            return $sreg['email'];
        }

        // Terrible hack for invites...
        if (common_config('site', 'inviteonly')) {
            $code = $_SESSION['invitecode'];
            if ($code) {
                $invite = Invitation::getKV($code);

                if ($invite && $invite->address_type == 'email') {
                    return $invite->address;
                }
            }
        }
        return '';
    }

    public function tryLogin()
    {
        $consumer = oid_consumer();

        $response = $consumer->complete(common_local_url('finishopenidlogin'));

        if ($response->status == Auth_OpenID_CANCEL) {
            // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
            $this->message(_m('OpenID authentication cancelled.'));
            return;
        } elseif ($response->status == Auth_OpenID_FAILURE) {
            // TRANS: OpenID authentication failed; display the error message. %s is the error message.
            $this->message(sprintf(_m('OpenID authentication failed: %s.'), $response->message));
        } elseif ($response->status == Auth_OpenID_SUCCESS) {
            // This means the authentication succeeded; extract the
            // identity URL and Simple Registration data (if it was
            // returned).
            $display = $response->getDisplayIdentifier();
            $canonical = ($response->endpoint->canonicalID) ?
              $response->endpoint->canonicalID : $response->getDisplayIdentifier();

            oid_assert_allowed($display);
            oid_assert_allowed($canonical);

            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);

            if ($sreg_resp) {
                $sreg = $sreg_resp->contents();
            }

            // Launchpad teams extension
            if (!oid_check_teams($response)) {
                // TRANS: Message displayed when OpenID authentication is aborted.
                $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
                return;
            }

            $user = oid_get_user($canonical);

            if ($user) {
                oid_set_last($display);
                // XXX: commented out at @edd's request until better
                // control over how data flows from OpenID provider.
                // oid_update_user($user, $sreg);
                common_set_user($user);
                common_real_login(true);
                if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
                    common_rememberme($user);
                }
                unset($_SESSION['openid_rememberme']);
                $this->goHome($user->nickname);
            } else {
                $this->saveValues($display, $canonical, $sreg);
                $this->showForm(null, $this->bestNewNickname($display, $sreg));
            }
        }
    }

    public function message($msg)
    {
        $this->message_text = $msg;
        $this->showPage();
    }

    public function saveValues($display, $canonical, $sreg)
    {
        common_ensure_session();
        $_SESSION['openid_display'] = $display;
        $_SESSION['openid_canonical'] = $canonical;
        $_SESSION['openid_sreg'] = $sreg;
    }

    public function getSavedValues()
    {
        return [$_SESSION['openid_display'],
                $_SESSION['openid_canonical'],
                $_SESSION['openid_sreg']];
    }

    public function createNewUser()
    {
        // FIXME: save invite code before redirect, and check here

        if (!Event::handle('StartRegistrationTry', [$this])) {
            return;
        }

        if (common_config('site', 'closed')) {
            // TRANS: OpenID plugin message. No new user registration is allowed on the site.
            $this->clientError(_m('Registration not allowed.'));
        }

        $invite = null;

        if (common_config('site', 'inviteonly')) {
            $code = $_SESSION['invitecode'];
            if (empty($code)) {
                // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
                $this->clientError(_m('Registration not allowed.'));
            }

            $invite = Invitation::getKV($code);

            if (empty($invite)) {
                // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
                $this->clientError(_m('Not a valid invitation code.'));
            }
        }

        try {
            $nickname = Nickname::normalize($this->trimmed('newname'), true);
        } catch (NicknameException $e) {
            $this->showForm($e->getMessage());
            return;
        }

        list($display, $canonical, $sreg) = $this->getSavedValues();

        if (!$display || !$canonical) {
            // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
            $this->serverError(_m('Stored OpenID not found.'));
        }

        // Possible race condition... let's be paranoid

        $other = oid_get_user($canonical);

        if ($other) {
            // TRANS: OpenID plugin server error.
            $this->serverError(_m('Creating new account for OpenID that already has a user.'));
        }

        Event::handle('StartOpenIDCreateNewUser', [$canonical, &$sreg]);

        $location = '';
        if (!empty($sreg['country'])) {
            if ($sreg['postcode']) {
                // XXX: use postcode to get city and region
                // XXX: also, store postcode somewhere -- it's valuable!
                $location = $sreg['postcode'] . ', ' . $sreg['country'];
            } else {
                $location = $sreg['country'];
            }
        }

        if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
            $fullname = $sreg['fullname'];
        } else {
            $fullname = '';
        }

        $email = $this->getEmail();

        // XXX: add language
        // XXX: add timezone

        $args = ['nickname' => $nickname,
                 'email' => $email,
                 'fullname' => $fullname,
                 'location' => $location];

        if (!empty($invite)) {
            $args['code'] = $invite->code;
        }

        $user = User::register($args);

        $result = oid_link_user($user->id, $canonical, $display);

        Event::handle('EndOpenIDCreateNewUser', [$user, $canonical, $sreg]);

        oid_set_last($display);
        common_set_user($user);
        common_real_login(true);
        if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
            common_rememberme($user);
        }
        unset($_SESSION['openid_rememberme']);

        Event::handle('EndRegistrationTry', [$this]);

        common_redirect(common_local_url('showstream', ['nickname' => $user->nickname]), 303);
    }

    public function connectUser()
    {
        $nickname = $this->trimmed('nickname');
        $password = $this->trimmed('password');
        $synch     = $this->boolean('openid-synch');

        if (!common_check_user($nickname, $password)) {
            // TRANS: OpenID plugin message.
            $this->showForm(_m('Invalid username or password.'));
            return;
        }

        // They're legit!

        $user = User::getKV('nickname', $nickname);

        list($display, $canonical, $sreg) = $this->getSavedValues();

        if (!$display || !$canonical) {
            // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
            $this->serverError(_m('Stored OpenID not found.'));
        }

        $result = oid_link_user($user->id, $canonical, $display);

        if (!$result) {
            // TRANS: OpenID plugin server error. The user or user profile could not be saved.
            $this->serverError(_m('Error connecting user to OpenID.'));
        }

        if ($synch) {
            if (Event::handle('StartOpenIDUpdateUser', [$user, $canonical, &$sreg])) {
                oid_update_user($user, $sreg);
            }
            Event::handle('EndOpenIDUpdateUser', [$user, $canonical, $sreg]);
        }

        oid_set_last($display);
        common_set_user($user);
        common_real_login(true);
        if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
            common_rememberme($user);
        }
        unset($_SESSION['openid_rememberme']);
        $this->goHome($user->nickname);
    }

    public function goHome($nickname)
    {
        $url = common_get_returnto();
        if ($url) {
            // We don't have to return to it again
            common_set_returnto(null);
            $url = common_inject_session($url);
        } else {
            $url = common_local_url('all', ['nickname' => $nickname]);
        }
        common_redirect($url, 303);
    }

    public function bestNewNickname($display, $sreg)
    {
        // Try the passed-in nickname

        if (!empty($sreg['nickname'])) {
            $nickname = common_nicknamize($sreg['nickname']);
            if (Nickname::isValid($nickname, true)) {
                return $nickname;
            }
        }

        // Try the full name

        if (!empty($sreg['fullname'])) {
            $fullname = common_nicknamize($sreg['fullname']);
            if (Nickname::isValid($fullname, true)) {
                return $fullname;
            }
        }

        // Try the URL

        $from_url = $this->openidToNickname($display);

        if ($from_url && Nickname::isValid($from_url, true)) {
            return $from_url;
        }

        // XXX: others?

        return null;
    }

    public function openidToNickname($openid)
    {
        if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
            return $this->xriToNickname($openid);
        } else {
            return $this->urlToNickname($openid);
        }
    }

    // We try to use an OpenID URL as a legal StatusNet user name in this order
    // 1. Plain hostname, like http://evanp.myopenid.com/
    // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
    //    or http://getopenid.com/evanprodromou
    public function urlToNickname($openid)
    {
        return common_url_to_nickname($openid);
    }

    public function xriToNickname($xri)
    {
        $base = $this->xriBase($xri);

        if (!$base) {
            return null;
        } else {
            // =evan.prodromou
            // or @gratis*evan.prodromou
            $parts = explode('*', substr($base, 1));
            return common_nicknamize(array_pop($parts));
        }
    }

    public function xriBase($xri)
    {
        if (substr($xri, 0, 6) == 'xri://') {
            return substr($xri, 6);
        } else {
            return $xri;
        }
    }
}


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * OpenID Synch completion
 *
 * @package   GNUsocial
 * @author    Bruno Casteleiro <brunoccast@fc.up.pt>
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

defined('GNUSOCIAL') || die();

require_once(INSTALLDIR . '/plugins/OpenID/openid.php');

/**
 * Action that handles OpenID Synch completion.
 *
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class FinishsynchopenidAction extends Action
{
    public $msg = null;

    /**
     * Handle the redirect back from OpenID confirmation
     *
     * Check to see if the user's logged in, and then try
     * to use the OpenID login system.
     *
     * @param array $args $_REQUEST arguments
     *
     * @return void
     */
    public function handle()
    {
        parent::handle();
        if (!common_logged_in()) {
            // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
            $this->clientError(_m('Not logged in.'));
        } else {
            $this->tryLogin();
        }
    }

    /**
     * Try to log in using OpenID
     *
     * Check the OpenID for validity; potentially store it.
     *
     * @return void
     */
    public function tryLogin()
    {
        $consumer = oid_consumer();

        $response = $consumer->complete(common_local_url('finishsynchopenid'));

        if ($response->status == Auth_OpenID_CANCEL) {
            // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
            $this->message(_m('OpenID authentication cancelled.'));
            return;
        } elseif ($response->status == Auth_OpenID_FAILURE) {
            // TRANS: OpenID authentication failed; display the error message.
            // TRANS: %s is the error message.
            $this->message(sprintf(
                _m('OpenID authentication failed: %s.'),
                $response->message
            ));
        } elseif ($response->status == Auth_OpenID_SUCCESS) {
            $display   = $response->getDisplayIdentifier();
            $canonical = ($response->endpoint && $response->endpoint->canonicalID) ?
              $response->endpoint->canonicalID : $display;

            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);

            if ($sreg_resp) {
                $sreg = $sreg_resp->contents();
            }

            // Launchpad teams extension
            if (!oid_check_teams($response)) {
                // TRANS: OpenID authentication error.
                $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
                return;
            }

            $cur = common_current_user();

            // start a transaction

            $cur->query('BEGIN');

            if (Event::handle('StartOpenIDUpdateUser', [$cur, $canonical, &$sreg])) {
                if (!oid_update_user($cur, $sreg)) {
                    // TRANS: Message in case the user or the user profile cannot be saved in StatusNet.
                    $this->message(_m('Error updating profile.'));
                    return;
                }
            }
            Event::handle('EndOpenIDUpdateUser', [$cur, $canonical, $sreg]);

            // success!

            $cur->query('COMMIT');

            oid_set_last($display);

            common_redirect(common_local_url('openidsettings'), 303);
        }
    }

    /**
     * Show a failure message
     *
     * Something went wrong. Save the message, and show the page.
     *
     * @param string $msg Error message to show
     *
     * @return void
     */
    public function message($msg)
    {
        $this->message = $msg;
        $this->showPage();
    }

    /**
     * Title of the page
     *
     * @return string title
     */
    public function title()
    {
        // TRANS: Title after getting the status of the OpenID authorisation request.
        // TODO update after understanding the function ^
        return _m('OpenID Synchronization');
    }

    /**
     * Show error message
     *
     * @return void
     */
    public function showPageNotice()
    {
        if ($this->message) {
            $this->element('p', 'error', $this->message);
        }
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * OpenID bridge administration panel
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Settings
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Administer global OpenID settings
 *
 * @category Admin
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class OpenidadminpanelAction extends AdminPanelAction
{
    /**
     * Returns the page title
     *
     * @return string page title
     */
    function title()
    {
        // TRANS: Title for OpenID bridge administration page.
        return _m('TITLE','OpenID Settings');
    }

    /**
     * Instructions for using this form.
     *
     * @return string instructions
     */
    function getInstructions()
    {
        // TRANS: Page instructions.
        return _m('OpenID settings');
    }

    /**
     * Show the OpenID admin panel form
     *
     * @return void
     */
    function showForm()
    {
        $form = new OpenIDAdminPanelForm($this);
        $form->show();
        return;
    }

    /**
     * Save settings from the form
     *
     * @return void
     */
    function saveSettings()
    {
        static $settings = array(
            'openid' => array('trusted_provider', 'required_team')
        );

        static $booleans = array(
            'openid' => array('append_username'),
            'site' => array('openidonly')
        );

        $values = array();

        foreach ($settings as $section => $parts) {
            foreach ($parts as $setting) {
                $values[$section][$setting]
                    = $this->trimmed($setting);
            }
        }

        foreach ($booleans as $section => $parts) {
            foreach ($parts as $setting) {
                $values[$section][$setting]
                    = ($this->boolean($setting)) ? 1 : 0;
            }
        }

        // This throws an exception on validation errors

        $this->validate($values);

        // assert(all values are valid);

        $config = new Config();

        $config->query('BEGIN');

        foreach ($settings as $section => $parts) {
            foreach ($parts as $setting) {
                Config::save($section, $setting, $values[$section][$setting]);
            }
        }

        foreach ($booleans as $section => $parts) {
            foreach ($parts as $setting) {
                Config::save($section, $setting, $values[$section][$setting]);
            }
        }

        $config->query('COMMIT');

        return;
    }

    function validate(&$values)
    {
        // Validate consumer key and secret (can't be too long)

        if (mb_strlen($values['openid']['trusted_provider']) > 255) {
            $this->clientError(
                // TRANS: Client error displayed when OpenID provider URL is too long.
                _m('Invalid provider URL. Maximum length is 255 characters.')
            );
        }

        if (mb_strlen($values['openid']['required_team']) > 255) {
            $this->clientError(
                // TRANS: Client error displayed when Launchpad team name is too long.
                _m('Invalid team name. Maximum length is 255 characters.')
            );
        }
    }
}

class OpenIDAdminPanelForm extends AdminForm
{
    /**
     * ID of the form
     *
     * @return int ID of the form
     */
    function id()
    {
        return 'openidadminpanel';
    }

    /**
     * class of the form
     *
     * @return string class of the form
     */
    function formClass()
    {
        return 'form_settings';
    }

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('openidadminpanel');
    }

    /**
     * Data elements of the form
     *
     * @return void
     *
     * @todo Some of the options could prevent users from logging in again.
     *       Make sure that the acting administrator has a valid OpenID matching,
     *       or more carefully warn folks.
     */
    function formData()
    {
        $this->out->elementStart(
            'fieldset',
            array('id' => 'settings_openid')
        );
        // TRANS: Fieldset legend.
        $this->out->element('legend', null, _m('LEGEND','Trusted provider'));
        $this->out->element('p', 'form_guide',
            // TRANS: Form guide.
            _m('By default, users are allowed to authenticate with any OpenID provider. ' .
               'If you are using your own OpenID service for shared sign-in, ' .
               'you can restrict access to only your own users here.'));
        $this->out->elementStart('ul', 'form_data');

        $this->li();
        $this->input(
            'trusted_provider',
            // TRANS: Field label.
            _m('Provider URL'),
            // TRANS: Field title.
            _m('All OpenID logins will be sent to this URL; other providers may not be used.'),
            'openid'
        );
        $this->unli();

        $this->li();
        $this->out->checkbox(
            // TRANS: Checkbox label.
            'append_username', _m('Append a username to base URL'),
            (bool) $this->value('append_username', 'openid'),
            // TRANS: Checkbox title.
            _m('Login form will show the base URL and prompt for a username to add at the end. Use when OpenID provider URL should be the profile page for individual users.'),
            'true'
        );
        $this->unli();

        $this->li();
        $this->input(
            'required_team',
            // TRANS: Field label.
            _m('Required team'),
            // TRANS: Field title.
            _m('Only allow logins from users in the given team (Launchpad extension).'),
            'openid'
        );
        $this->unli();

        $this->out->elementEnd('ul');
        $this->out->elementEnd('fieldset');

        $this->out->elementStart(
            'fieldset',
            array('id' => 'settings_openid-options')
        );
        // TRANS: Fieldset legend.
        $this->out->element('legend', null, _m('LEGEND','Options'));

        $this->out->elementStart('ul', 'form_data');

        $this->li();

        $this->out->checkbox(
            // TRANS: Checkbox label.
            'openidonly', _m('Enable OpenID-only mode'),
            (bool) $this->value('openidonly', 'site'),
            // TRANS: Checkbox title.
            _m('Require all users to login via OpenID. Warning: disables password authentication for all users!'),
            'true'
        );
        $this->unli();

        $this->out->elementEnd('ul');

        $this->out->elementEnd('fieldset');
    }

    /**
     * Action elements
     *
     * @return void
     */
    function formActions()
    {
        // TRANS: Button text to save OpenID settings.
        $this->out->submit('submit', _m('BUTTON','Save'), 'submit', null,
                           // TRANS: Button title to save OpenID settings.
                           _m('Save OpenID settings.'));
    }
}


code:
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET')) {
    exit(1);
}

require_once INSTALLDIR.'/plugins/OpenID/openid.php';

class OpenidloginAction extends Action
{
    function handle()
    {
        parent::handle();
        if (common_is_real_login()) {
            // TRANS: Client error message trying to log on with OpenID while already logged on.
            $this->clientError(_m('Already logged in.'));
        } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $provider = common_config('openid', 'trusted_provider');
            if ($provider) {
                $openid_url = $provider;
                if (common_config('openid', 'append_username')) {
                    $openid_url .= $this->trimmed('openid_username');
                }
            } else {
                $openid_url = $this->trimmed('openid_url');
            }

            oid_assert_allowed($openid_url);

            $rememberme = $this->boolean('rememberme');

            common_ensure_session();

            $_SESSION['openid_rememberme'] = $rememberme;

            $result = oid_authenticate($openid_url,
                                       'finishopenidlogin');

            if (is_string($result)) { # error message
                unset($_SESSION['openid_rememberme']);
                $this->showForm($result, $openid_url);
            }
        } else {
            $openid_url = oid_get_last();
            $this->showForm(null, $openid_url);
        }
    }

    function getInstructions()
    {
        if (common_logged_in() && !common_is_real_login() &&
            common_get_returnto()) {
            // rememberme logins have to reauthenticate before
            // changing any profile settings (cookie-stealing protection)
            // TRANS: OpenID plugin message. Rememberme logins have to reauthenticate before changing any profile settings.
            // TRANS: "OpenID" is the display text for a link with URL "(%%doc.openid%%)".
            return _m('For security reasons, please re-login with your ' .
                     '[OpenID](%%doc.openid%%) ' .
                     'before changing your settings.');
        } else {
            // TRANS: OpenID plugin message.
            // TRANS: "OpenID" is the display text for a link with URL "(%%doc.openid%%)".
            return _m('Login with an [OpenID](%%doc.openid%%) account.');
        }
    }

    function showPageNotice()
    {
        if ($this->error) {
            $this->element('div', array('class' => 'error'), $this->error);
        } else {
            $instr = $this->getInstructions();
            $output = common_markup_to_html($instr);
            $this->elementStart('div', 'instructions');
            $this->raw($output);
            $this->elementEnd('div');
        }
    }

    function showScripts()
    {
        parent::showScripts();
        if (common_config('openid', 'trusted_provider')) {
            if (common_config('openid', 'append_username')) {
                $this->autofocus('openid_username');
            } else {
                $this->autofocus('rememberme');
            }
        } else {
            $this->autofocus('openid_url');
        }
    }

    function title()
    {
        // TRANS: OpenID plugin message. Title.
        return _m('TITLE','OpenID Login');
    }

    function showForm($error=null, $openid_url)
    {
        $this->error = $error;
        $this->openid_url = $openid_url;
        $this->showPage();
    }

    function showContent() {
        $formaction = common_local_url('openidlogin');
        $this->elementStart('form', array('method' => 'post',
                                           'id' => 'form_openid_login',
                                           'class' => 'form_settings',
                                           'action' => $formaction));
        $this->elementStart('fieldset');
        // TRANS: OpenID plugin logon form legend.
        $this->element('legend', null, _m('LEGEND','OpenID login'));

        $this->elementStart('ul', 'form_data');
        $this->elementStart('li');
        $provider = common_config('openid', 'trusted_provider');
        $appendUsername = common_config('openid', 'append_username');
        if ($provider) {
            // TRANS: Field label.
            $this->element('label', [], _m('LABEL','OpenID provider'));
            $this->element('span', [], $provider);
            if ($appendUsername) {
                $this->element('input', array('id' => 'openid_username',
                                              'name' => 'openid_username',
                                              'style' => 'float: none'));
            }
            $this->element('p', 'form_guide',
                           // TRANS: Form guide.
                           ($appendUsername ? _m('Enter your username.') . ' ' : '') .
                           // TRANS: Form guide.
                           _m('You will be sent to the provider\'s site for authentication.'));
            $this->hidden('openid_url', $provider);
        } else {
            // TRANS: OpenID plugin logon form field label.
            $this->input('openid_url', _m('OpenID URL'),
                         $this->openid_url,
                        // TRANS: OpenID plugin logon form field title.
                         _m('Your OpenID URL.'));
        }
        $this->elementEnd('li');
        $this->elementStart('li', array('id' => 'settings_rememberme'));
        // TRANS: OpenID plugin logon form checkbox label for setting to put the OpenID information in a cookie.
        $this->checkbox('rememberme', _m('Remember me'), false,
                        // TRANS: OpenID plugin logon form field title.
                        _m('Automatically login in the future; ' .
                           'not for shared computers!'));
        $this->elementEnd('li');
        $this->elementEnd('ul');
        // TRANS: OpenID plugin logon form button label to start logon with the data provided in the logon form.
        $this->submit('submit', _m('BUTTON', 'Login'));
        $this->elementEnd('fieldset');
        $this->elementEnd('form');
    }

    function showLocalNav()
    {
        $nav = new LoginGroupNav($this);
        $nav->show();
    }

    function showNoticeForm()
    {
    }

    function showProfileBlock()
    {
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Settings for OpenID
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Settings
 * @package   StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @copyright 2008-2009 StatusNet, Inc.
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

require_once INSTALLDIR.'/plugins/OpenID/openid.php';

/**
 * Settings for OpenID
 *
 * Lets users add, edit and delete OpenIDs from their account
 *
 * @category Settings
 * @package  StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class OpenidserverAction extends Action
{
    var $oserver;

    function prepare(array $args = array())
    {
        parent::prepare($args);
        $this->oserver = oid_server();
        return true;
    }

    function handle()
    {
        parent::handle();
        $request = $this->oserver->decodeRequest();
        if (in_array($request->mode, array('checkid_immediate',
            'checkid_setup'))) {
            if (!$this->scoped instanceof Profile) {
                if($request->immediate){
                    //cannot prompt the user to login in immediate mode, so answer false
                    $response = $this->generateDenyResponse($request);
                }else{
                    // Go log in, and then come back.
                    //
                    // Note: 303 redirect rather than 307 to avoid
                    // prompting user for form resubmission if we
                    // were POSTed here.
                    common_set_returnto($_SERVER['REQUEST_URI']);
                    common_redirect(common_local_url('login'), 303);
                }
            } elseif (in_array($request->identity, $this->scoped->getAliases()) || $request->idSelect()) {
                $user_openid_trustroot = User_openid_trustroot::pkeyGet(
                                                array('user_id'=>$this->scoped->getID(), 'trustroot'=>$request->trust_root));
                if(empty($user_openid_trustroot)){
                    if($request->immediate){
                        //cannot prompt the user to trust this trust root in immediate mode, so answer false
                        $response = $this->generateDenyResponse($request);
                    }else{
                        common_ensure_session();
                        $_SESSION['openid_trust_root'] = $request->trust_root;
                        $allowResponse = $this->generateAllowResponse($request, $this->scoped);
                        $this->oserver->encodeResponse($allowResponse); //sign the response
                        $denyResponse = $this->generateDenyResponse($request);
                        $this->oserver->encodeResponse($denyResponse); //sign the response
                        $_SESSION['openid_allow_url'] = $allowResponse->encodeToUrl();
                        $_SESSION['openid_deny_url'] = $denyResponse->encodeToUrl();

                        // Ask the user to trust this trust root...
                        //
                        // Note: 303 redirect rather than 307 to avoid
                        // prompting user for form resubmission if we
                        // were POSTed here.
                        common_redirect(common_local_url('openidtrust'), 303);
                    }
                } else {
                    //user has previously authorized this trust root
                    $response = $this->generateAllowResponse($request, $this->scoped);
                }
            } elseif ($request->immediate) {
                $response = $this->generateDenyResponse($request);
            } else {
                //invalid
                // TRANS: OpenID plugin client error given trying to add an unauthorised OpenID to a user (403).
                // TRANS: %s is a request identity.
                $this->clientError(sprintf(_m('You are not authorized to use the identity %s.'),$request->identity),$code=403);
            }
        } else {
            $response = $this->oserver->handleRequest($request);
        }

        if($response){
            $response = $this->oserver->encodeResponse($response);
            if ($response->code != AUTH_OPENID_HTTP_OK) {
                header(sprintf("HTTP/1.1 %d ", $response->code),
                       true, $response->code);
            }

            if($response->headers){
                foreach ($response->headers as $k => $v) {
                    header("$k: $v");
                }
            }
            $this->raw($response->body);
        }else{
            // TRANS: OpenID plugin client error given when not getting a response for a given OpenID provider (500).
            $this->clientError(_m('Just an OpenID provider. Nothing to see here, move along...'),$code=500);
        }
    }

    function generateAllowResponse($request, Profile $profile){
        $response = $request->answer(true, null, $profile->getUrl());
        $user = $profile->getUser();

        $sreg_data = array(
            'fullname' => $profile->getFullname(),
            'nickname' => $profile->getNickname(),
            'email' => $user->email,    // FIXME: Should we make the email optional?
            'language' => $user->language,
            'timezone' => $user->timezone);
        $sreg_request = Auth_OpenID_SRegRequest::fromOpenIDRequest($request);
        $sreg_response = Auth_OpenID_SRegResponse::extractResponse(
                              $sreg_request, $sreg_data);
        $sreg_response->toMessage($response->fields);
        return $response;
    }

    function generateDenyResponse($request){
        $response = $request->answer(false);
        return $response;
    }
}