function find_remote_user($username, $wwwroot)
{
    $authinstances = auth_get_auth_instances_for_wwwroot($wwwroot);
    $candidates = array();
    foreach ($authinstances as $authinstance) {
        if ($authinstance->authname != 'xmlrpc') {
            continue;
        }
        try {
            $user = new User();
            $user->find_by_instanceid_username($authinstance->id, $username, true);
            $candidates[$authinstance->id] = $user;
        } catch (Exception $e) {
            // we don't care
            continue;
        }
    }
    if (count($candidates) != 1) {
        return false;
    }
    safe_require('auth', 'xmlrpc');
    return array(end($candidates), new AuthXmlrpc(key($candidates)));
}
// If networking is turned off, it's safer to die immediately
if (!get_config('enablenetworking')) {
    throw new AccessTotallyDeniedException(get_string('networkingdisabledonthissite', 'auth.xmlrpc'));
}
require_once get_config('docroot') . 'api/xmlrpc/client.php';
require_once get_config('docroot') . 'auth/xmlrpc/lib.php';
require_once get_config('libroot') . 'institution.php';
$token = param_variable('token');
$remotewwwroot = param_variable('idp');
$wantsurl = param_variable('wantsurl', '/');
$remoteurl = param_boolean('remoteurl');
$len = strlen($remotewwwroot);
if ($len < 1 || $len > 255) {
    throw new ParameterException(get_string('errnoxmlrpcwwwroot', 'auth', $remotewwwroot));
}
$instances = auth_get_auth_instances_for_wwwroot($remotewwwroot);
if (empty($instances)) {
    throw new ParameterException(get_string('errnoauthinstances', 'auth', $remotewwwroot));
}
// If the user is already logged in as someone, log them out. That way, if
// XMLRPC authentication fails, the system isn't left looking stupid as it
// reports that the user couldn't log in while they actually are.
if ($USER->is_logged_in()) {
    $USER->logout();
}
$SESSION->set('messages', array());
$rpcconfigured = false;
$res = false;
foreach ($instances as $instance) {
    if ($instance->authname == 'xmlrpc') {
        if (!$instance->suspended) {