Ejemplo n.º 1
0
/**
 * @param int $oldversion the version we are upgrading from
 * @return bool result
 */
function xmldb_auth_ldap_upgrade($oldversion)
{
    // Moodle v2.5.0 release upgrade line
    // Put any upgrade step following this
    // MDL-39323 New setting in 2.5, make sure it's defined.
    if ($oldversion < 2013052100) {
        if (get_config('start_tls', 'auth/ldap') === false) {
            set_config('start_tls', 0, 'auth/ldap');
        }
        upgrade_plugin_savepoint(true, 2013052100, 'auth', 'ldap');
    }
    // Moodle v2.6.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v2.7.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2014111001) {
        global $DB;
        // From now on the default LDAP objectClass setting for AD has been changed, from 'user' to '(samaccounttype=805306368)'.
        if (is_enabled_auth('ldap') && $DB->get_field('config_plugins', 'value', array('name' => 'user_type', 'plugin' => 'auth/ldap')) === 'ad' && $DB->get_field('config_plugins', 'value', array('name' => 'objectclass', 'plugin' => 'auth/ldap')) === '') {
            // Save the backwards-compatible default setting.
            set_config('objectclass', 'user', 'auth/ldap');
        }
        upgrade_plugin_savepoint(true, 2014111001, 'auth', 'ldap');
    }
    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.
    return true;
}
 public function test_get_public_config()
 {
     global $CFG, $SITE, $OUTPUT;
     $this->resetAfterTest(true);
     $result = external::get_public_config();
     $result = external_api::clean_returnvalue(external::get_public_config_returns(), $result);
     // Test default values.
     $context = context_system::instance();
     list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
     list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
     $expected = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => $authinstructions, 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => $maintenancemessage, 'typeoflogin' => api::LOGIN_VIA_APP, 'warnings' => array());
     $this->assertEquals($expected, $result);
     // Change some values.
     set_config('registerauth', 'email');
     $authinstructions = 'Something with <b>html tags</b>';
     set_config('auth_instructions', $authinstructions);
     set_config('typeoflogin', api::LOGIN_VIA_BROWSER, 'tool_mobile');
     set_config('logo', 'mock.png', 'core_admin');
     set_config('logocompact', 'mock.png', 'core_admin');
     list($authinstructions, $notusedformat) = external_format_text($authinstructions, FORMAT_MOODLE, $context->id);
     $expected['registerauth'] = 'email';
     $expected['authinstructions'] = $authinstructions;
     $expected['typeoflogin'] = api::LOGIN_VIA_BROWSER;
     $expected['launchurl'] = "{$CFG->wwwroot}/{$CFG->admin}/tool/mobile/launch.php";
     if ($logourl = $OUTPUT->get_logo_url()) {
         $expected['logourl'] = $logourl->out(false);
     }
     if ($compactlogourl = $OUTPUT->get_compact_logo_url()) {
         $expected['compactlogourl'] = $compactlogourl->out(false);
     }
     $result = external::get_public_config();
     $result = external_api::clean_returnvalue(external::get_public_config_returns(), $result);
     $this->assertEquals($expected, $result);
 }
 function get_content()
 {
     global $CFG, $USER, $DB, $OUTPUT;
     // shortcut -  only for logged in users!
     if (!isloggedin() || isguestuser()) {
         return false;
     }
     // according to start_jump_session,
     // remote users can't on-jump
     // so don't show this block to them
     if (is_mnet_remote_user($USER)) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_localusersonly', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if (!is_enabled_auth('mnet')) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_authmnetneeded', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM), NULL, false)) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_roamcapabilityneeded', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if ($this->content !== NULL) {
         return $this->content;
     }
     // TODO: Test this query - it's appropriate? It works?
     // get the hosts and whether we are doing SSO with them
     $sql = "\n             SELECT DISTINCT\n                 h.id,\n                 h.name,\n                 h.wwwroot,\n                 a.name as application,\n                 a.display_name\n             FROM\n                 {mnet_host} h,\n                 {mnet_application} a,\n                 {mnet_host2service} h2s_IDP,\n                 {mnet_service} s_IDP,\n                 {mnet_host2service} h2s_SP,\n                 {mnet_service} s_SP\n             WHERE\n                 h.id <> ? AND\n                 h.id <> ? AND\n                 h.id = h2s_IDP.hostid AND\n                 h.deleted = 0 AND\n                 h.applicationid = a.id AND\n                 h2s_IDP.serviceid = s_IDP.id AND\n                 s_IDP.name = 'sso_idp' AND\n                 h2s_IDP.publish = '1' AND\n                 h.id = h2s_SP.hostid AND\n                 h2s_SP.serviceid = s_SP.id AND\n                 s_SP.name = 'sso_idp' AND\n                 h2s_SP.publish = '1'\n             ORDER BY\n                 a.display_name,\n                 h.name";
     $hosts = $DB->get_records_sql($sql, array($CFG->mnet_localhost_id, $CFG->mnet_all_hosts_id));
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     if ($hosts) {
         foreach ($hosts as $host) {
             $icon = '<img src="' . $OUTPUT->pix_url('i/' . $host->application . '_host') . '"' . ' class="icon" alt="' . get_string('server', 'block_mnet_hosts') . '" />&nbsp;';
             if ($host->id == $USER->mnethostid) {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$host->wwwroot}\">" . $icon . s($host->name) . "</a>";
             } else {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$host->id}\">" . $icon . s($host->name) . "</a>";
             }
         }
     }
     return $this->content;
 }
Ejemplo n.º 4
0
 /**
  * Run users sync.
  */
 public function execute()
 {
     global $CFG;
     if (is_enabled_auth('cas')) {
         $auth = get_auth_plugin('cas');
         $auth->sync_users(true);
     }
 }
Ejemplo n.º 5
0
 /**
  * Returns a list of the site public settings, those not requiring authentication.
  *
  * @return array with the settings and warnings
  */
 public static function get_site_public_settings()
 {
     global $CFG, $SITE, $PAGE;
     $context = context_system::instance();
     // We need this to make work the format text functions.
     $PAGE->set_context($context);
     $settings = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => format_text($CFG->auth_instructions), 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => format_text($CFG->maintenance_message));
     return $settings;
 }
Ejemplo n.º 6
0
 /**
  * Performs the synchronisation of members.
  */
 public function execute()
 {
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return;
     }
     $this->dataconnector = new data_connector();
     // Get all the enabled tools.
     $tools = helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'membersync' => 1));
     foreach ($tools as $tool) {
         mtrace("Starting - Member sync for published tool '{$tool->id}' for course '{$tool->courseid}'.");
         // Variables to keep track of information to display later.
         $usercount = 0;
         $enrolcount = 0;
         $unenrolcount = 0;
         // Fetch consumer records mapped to this tool.
         $consumers = $this->dataconnector->get_consumers_mapped_to_tool($tool->id);
         // Perform processing for each consumer.
         foreach ($consumers as $consumer) {
             mtrace("Requesting membership service for the tool consumer '{$consumer->getRecordId()}'");
             // Get members through this tool consumer.
             $members = $this->fetch_members_from_consumer($consumer);
             // Check if we were able to fetch the members.
             if ($members === false) {
                 mtrace("Skipping - Membership service request failed.\n");
                 continue;
             }
             // Fetched members count.
             $membercount = count($members);
             mtrace("{$membercount} members received.\n");
             // Process member information.
             list($usercount, $enrolcount) = $this->sync_member_information($tool, $consumer, $members);
         }
         // Now we check if we have to unenrol users who were not listed.
         if ($this->should_sync_unenrol($tool->membersyncmode)) {
             $unenrolcount = $this->sync_unenrol($tool);
         }
         mtrace("Completed - Synced members for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; enrolled {$enrolcount} members; unenrolled {$unenrolcount} members.\n");
     }
     // Sync the user profile photos.
     mtrace("Started - Syncing user profile images.");
     $countsyncedimages = $this->sync_profile_images();
     mtrace("Completed - Synced {$countsyncedimages} profile images.");
 }
 function get_content()
 {
     global $THEME, $CFG, $USER;
     // only for logged in users!
     if (!isloggedin() || isguest()) {
         return false;
     }
     if (!is_enabled_auth('mnet')) {
         // no need to query anything remote related
         debugging('mnet authentication plugin is not enabled', DEBUG_ALL);
         return '';
     }
     if (!empty($USER->realuser)) {
         $this->content = new stdClass();
         $this->content->items = array();
         $this->content->icons = array();
         $this->content->footer = get_string('notpermittedtojumpas', 'mnet');
         return $this->content;
     }
     // check for outgoing roaming permission first
     if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM), NULL, false)) {
         return '';
     }
     if ($this->content !== NULL) {
         return $this->content;
     }
     // TODO: Test this query - it's appropriate? It works?
     // get the hosts and whether we are doing SSO with them
     $sql = "\n             SELECT DISTINCT \n                 h.id, \n                 h.name,\n                 h.wwwroot,\n                 a.name as application,\n                 a.display_name\n             FROM \n                 {$CFG->prefix}mnet_host h,\n                 {$CFG->prefix}mnet_application a,\n                 {$CFG->prefix}mnet_host2service h2s_IDP,\n                 {$CFG->prefix}mnet_service s_IDP,\n                 {$CFG->prefix}mnet_host2service h2s_SP,\n                 {$CFG->prefix}mnet_service s_SP\n             WHERE\n                 h.id != '{$CFG->mnet_localhost_id}' AND\n                 h.id = h2s_IDP.hostid AND\n                 h.deleted = 0 AND\n                 h.applicationid = a.id AND\n                 h2s_IDP.serviceid = s_IDP.id AND\n                 s_IDP.name = 'sso_idp' AND\n                 h2s_IDP.publish = '1' AND\n                 h.id = h2s_SP.hostid AND\n                 h2s_SP.serviceid = s_SP.id AND\n                 s_SP.name = 'sso_idp' AND\n                 h2s_SP.publish = '1'\n             ORDER BY\n                 a.display_name,\n                 h.name";
     $hosts = get_records_sql($sql);
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     if ($hosts) {
         foreach ($hosts as $host) {
             $icon = '<img src="' . $CFG->pixpath . '/i/' . $host->application . '_host.gif"' . ' class="icon" alt="' . get_string('server', 'block_mnet_hosts') . '" />';
             $this->content->icons[] = $icon;
             if ($host->id == $USER->mnethostid) {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$host->wwwroot}\">" . s($host->name) . "</a>";
             } else {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$host->id}\">" . s($host->name) . "</a>";
             }
         }
     }
     return $this->content;
 }
Ejemplo n.º 8
0
 public function execute()
 {
     global $CFG;
     require_once "{$CFG->libdir}/datalib.php";
     $user = get_admin();
     if (!$user) {
         cli_error("Unable to find admin user in DB.");
     }
     $auth = empty($user->auth) ? 'manual' : $user->auth;
     if ($auth == 'nologin' or !is_enabled_auth($auth)) {
         cli_error(sprintf("User authentication is either 'nologin' or disabled. Check Moodle authentication method for '%s'", $user->username));
     }
     $authplugin = get_auth_plugin($auth);
     $authplugin->sync_roles($user);
     login_attempt_valid($user);
     complete_user_login($user);
     printf("%s:%s\n", session_name(), session_id());
 }
Ejemplo n.º 9
0
 /**
  * Form definition.
  */
 protected function definition()
 {
     global $USER;
     $authconfig = get_config('auth_oidc');
     $opname = !empty($authconfig->opname) ? $authconfig->opname : get_string('pluginname', 'auth_oidc');
     $mform =& $this->_form;
     $mform->addElement('html', \html_writer::tag('h4', get_string('ucp_disconnect_title', 'auth_oidc', $opname)));
     $mform->addElement('html', \html_writer::div(get_string('ucp_disconnect_details', 'auth_oidc', $opname)));
     $mform->addElement('html', '<br />');
     $mform->addElement('header', 'userdetails', get_string('userdetails'));
     $newmethod = [];
     $attributes = [];
     $manualenabled = is_enabled_auth('manual') === true ? true : false;
     if ($manualenabled === true) {
         $newmethod[] =& $mform->createElement('radio', 'newmethod', '', 'manual', 'manual', $attributes);
     }
     if (!empty($this->_customdata['prevmethod'])) {
         $prevmethod = $this->_customdata['prevmethod'];
         $newmethod[] =& $mform->createElement('radio', 'newmethod', '', $prevmethod, $prevmethod, $attributes);
     }
     $mform->addGroup($newmethod, 'newmethodar', get_string('errorauthdisconnectnewmethod', 'auth_oidc'), [' '], false);
     if (!empty($this->_customdata['prevmethod'])) {
         $mform->setDefault('newmethod', $this->_customdata['prevmethod']);
     } else {
         if ($manualenabled === true) {
             $mform->setDefault('newmethod', 'manual');
         }
     }
     if ($manualenabled === true) {
         $mform->addElement('html', \html_writer::div(get_string('errorauthdisconnectifmanual', 'auth_oidc')));
         $mform->addElement('text', 'username', get_string('username'));
         $mform->addElement('passwordunmask', 'password', get_string('password'));
         $mform->setType('username', PARAM_USERNAME);
         $mform->disabledIf('username', 'newmethod', 'neq', 'manual');
         $mform->disabledIf('password', 'newmethod', 'neq', 'manual');
         // If the user cannot choose a username, set it to their current username and freeze.
         if (isset($this->_customdata['canchooseusername']) && $this->_customdata['canchooseusername'] == false) {
             $mform->setDefault('username', $USER->username);
             $element = $mform->getElement('username');
             $element->freeze();
         }
     }
     $this->add_action_buttons();
 }
Ejemplo n.º 10
0
/**
 * @param int $oldversion the version we are upgrading from
 * @return bool result
 */
function xmldb_auth_cas_upgrade($oldversion)
{
    global $CFG, $DB;
    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2014111001) {
        // From now on the default LDAP objectClass setting for AD has been changed, from 'user' to '(samaccounttype=805306368)'.
        if (is_enabled_auth('cas') && $DB->get_field('config_plugins', 'value', array('name' => 'user_type', 'plugin' => 'auth/cas')) === 'ad' && $DB->get_field('config_plugins', 'value', array('name' => 'objectclass', 'plugin' => 'auth/cas')) === '') {
            // Save the backwards-compatible default setting.
            set_config('objectclass', 'user', 'auth/cas');
        }
        upgrade_plugin_savepoint(true, 2014111001, 'auth', 'cas');
    }
    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v3.0.0 release upgrade line.
    // Put any upgrade step following this.
    return true;
}
Ejemplo n.º 11
0
 public function test_get_site_public_settings()
 {
     global $CFG, $SITE;
     $this->resetAfterTest(true);
     $result = external::get_site_public_settings();
     $result = external_api::clean_returnvalue(external::get_site_public_settings_returns(), $result);
     // Test default values.
     $context = context_system::instance();
     $expected = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => format_text($CFG->auth_instructions), 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => format_text($CFG->maintenance_message), 'warnings' => array());
     $this->assertEquals($expected, $result);
     // Change a value.
     set_config('registerauth', 'email');
     $authinstructions = 'Something with <b>html tags</b>';
     set_config('auth_instructions', $authinstructions);
     $expected['registerauth'] = 'email';
     $expected['authinstructions'] = format_text($authinstructions);
     $result = external::get_site_public_settings();
     $result = external_api::clean_returnvalue(external::get_site_public_settings_returns(), $result);
     $this->assertEquals($expected, $result);
 }
    private function __app_reset_password_and_mail($user)
    {
        global $CFG;
        $site = get_site();
        $supportuser = generate_email_supportuser();
        $userauth = get_auth_plugin($user->auth);
        if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
            trigger_error("Attempt to reset user password for user {$user->username} with Auth {$user->auth}.");
            return false;
        }
        $newpassword = generate_password();
        if (!$userauth->user_update_password($user, $newpassword)) {
            $error->error = true;
            $error->msg = 'fp_passwordgen_failure';
            echo json_encode($error);
            die;
        }
        $a = new stdClass();
        $a->firstname = $user->firstname;
        $a->lastname = $user->lastname;
        $a->sitename = format_string($site->fullname);
        $a->username = $user->username;
        $a->newpassword = $newpassword;
        //$a->signoff = generate_email_signoff();
        $message = 'Hi ' . $a->firstname . ',

Your account password at \'' . $a->sitename . '\' has been reset
and you have been issued with a new temporary password.

Your current login information is now:
   username: '******'
   password: '******'

Cheers from the \'' . $a->sitename . '\' administrator.';
        //$message = get_string('newpasswordtext', '', $a);
        $subject = format_string($site->fullname) . ': ' . get_string('changedpassword');
        unset_user_preference('create_password', $user);
        // prevent cron from generating the password
        //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
        return email_to_user($user, $supportuser, $subject, $message);
    }
Ejemplo n.º 13
0
 public function execute()
 {
     global $CFG, $DB;
     require_once "{$CFG->libdir}/datalib.php";
     $username = $this->arguments[0];
     $options = $this->expandedOptions;
     if ($options['id']) {
         $user = $DB->get_record('user', array('id' => $username), '*', MUST_EXIST);
     } else {
         $user = $DB->get_record('user', array('username' => $username), '*', MUST_EXIST);
     }
     $auth = empty($user->auth) ? 'manual' : $user->auth;
     if ($auth == 'nologin' or !is_enabled_auth($auth)) {
         cli_error(sprintf("User authentication is either 'nologin' or disabled. Check Moodle authentication method for '%s'", $user->username));
     }
     $authplugin = get_auth_plugin($auth);
     $authplugin->sync_roles($user);
     login_attempt_valid($user);
     complete_user_login($user);
     printf("%s:%s\n", session_name(), session_id());
 }
Ejemplo n.º 14
0
/**
 * Verifies unsupported noauth setting
 * @param bool $detailed
 * @return object result
 */
function report_security_check_noauth($detailed = false)
{
    global $CFG;
    $result = new stdClass();
    $result->issue = 'report_security_check_noauth';
    $result->name = get_string('check_noauth_name', 'report_security');
    $result->info = null;
    $result->details = null;
    $result->status = null;
    $result->link = null;
    $result->link = "<a href=\"{$CFG->wwwroot}/{$CFG->admin}/settings.php?section=manageauths\">" . get_string('authsettings', 'admin') . '</a>';
    if (is_enabled_auth('none')) {
        $result->status = REPORT_SECURITY_CRITICAL;
        $result->info = get_string('check_noauth_error', 'report_security');
    } else {
        $result->status = REPORT_SECURITY_OK;
        $result->info = get_string('check_noauth_ok', 'report_security');
    }
    if ($detailed) {
        $result->details = get_string('check_noauth_details', 'report_security');
    }
    return $result;
}
Ejemplo n.º 15
0
/**
 * Create a link that allows for displaying embedded Jasper reports
 * on an HTML page
 *
 * @param   $uri        The resource id of the necessary report
 * @param   $parameters Additional parameters to be passed to the report
 * @param   $print      If true, prints iframe on page
 * @return              The HTML of the iframe containing the report
 *
 */
function embeddedreports_generate_link($uri, $parameters = array(), $print = true)
{
    global $USER;
    $parameters['elisembedded'] = 'true';
    if (!is_enabled_auth('mnet')) {
        error('mnet is disabled');
    }
    // check remote login permissions
    if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM)) or is_mnet_remote_user($USER) or $USER->username == 'guest' or empty($USER->id)) {
        print_error('notpermittedtojump', 'mnet');
    }
    $mnet_auth = get_auth_plugin('mnet');
    // check for SSO publish permission first
    if ($mnet_auth->has_service(jasper_mnet_hostid(), 'sso_sp') == false) {
        print_error('hostnotconfiguredforsso', 'mnet');
    }
    $mnet_link = jasper_mnet_link(jasper_report_link($uri, $parameters));
    $result = '<iframe id="reportframe" name="reportframe" src="' . $mnet_link . '"></iframe>';
    if ($print) {
        echo $result;
    }
    return $result;
}
Ejemplo n.º 16
0
function block_mystats_mycourses()
{
    global $USER;
    $mycourses = array();
    $count = 0;
    $enrolledcourses = enrol_get_users_courses($USER->id);
    foreach ($enrolledcourses as $course) {
        if (isset($USER->lastcourseaccess[$course->id])) {
            $course->lastaccess = $USER->lastcourseaccess[$course->id];
        } else {
            $course->lastaccess = 0;
        }
        $mycourses[$course->id] = $course;
        $count++;
    }
    if (is_enabled_auth('mnet')) {
        $remotecourses = get_my_remotecourses();
        foreach ($remotecourses as $course) {
            $mycourses[$course->id] = $course;
            $count++;
        }
    }
    return $mycourses;
}
Ejemplo n.º 17
0
/**
 * OpenID login fallback
 *
 * This file allows OpenID users to log in even if their provider is offline for
 * some reason.  It sends an email with a one-time link to the email address
 * associated with the requested OpenID url.
 *
 * @author Stuart Metcalfe <*****@*****.**>
 * @copyright Copyright (c) 2007 Canonical
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package openid
 **/
require_once "../../config.php";
require_once $CFG->dirroot . '/auth/openid/lib.php';
// We don't want to allow use of this script if OpenID auth isn't enabled
if (!is_enabled_auth('openid') && !is_enabled_auth('openid_sso')) {
    print_error('auth_openid_not_enabled', 'auth_openid');
}
$action = optional_param('openid_action', '', PARAM_CLEAN);
$url = optional_param('openid_url', null);
$data = optional_param('data', '', PARAM_CLEAN);
// Formatted as:  secret/username
$p = optional_param('p', '', PARAM_ALPHANUM);
// Old parameter:  secret
$s = optional_param('s', '', PARAM_CLEAN);
// Old parameter:  username
// First, we set the action if we're handling a submitted data string
if (!empty($data) || !empty($p) && !empty($s)) {
    $action = 'handle_data';
}
switch ($action) {
Ejemplo n.º 18
0
/**
 * Sends an email containinginformation on how to change your password.
 *
 * @param stdClass $user A {@link $USER} object
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function send_password_change_info($user)
{
    global $CFG;
    $site = get_site();
    $supportuser = core_user::get_support_user();
    $systemcontext = context_system::instance();
    $data = new stdClass();
    $data->firstname = $user->firstname;
    $data->lastname = $user->lastname;
    $data->sitename = format_string($site->fullname);
    $data->admin = generate_email_signoff();
    $userauth = get_auth_plugin($user->auth);
    if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
        $message = get_string('emailpasswordchangeinfodisabled', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
        // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
        return email_to_user($user, $supportuser, $subject, $message);
    }
    if ($userauth->can_change_password() and $userauth->change_password_url()) {
        // We have some external url for password changing.
        $data->link .= $userauth->change_password_url();
    } else {
        // No way to change password, sorry.
        $data->link = '';
    }
    if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
        $message = get_string('emailpasswordchangeinfo', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    } else {
        $message = get_string('emailpasswordchangeinfofail', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    }
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
    return email_to_user($user, $supportuser, $subject, $message);
}
 function get_remote_courses()
 {
     global $CFG, $USER, $OUTPUT;
     if (!is_enabled_auth('mnet')) {
         // no need to query anything remote related
         return;
     }
     $icon = '<img src="' . $OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="" />';
     // shortcut - the rest is only for logged in users!
     if (!isloggedin() || isguestuser()) {
         return false;
     }
     if ($courses = get_my_remotecourses()) {
         $this->content->items[] = get_string('remotecourses', 'mnet');
         $this->content->icons[] = '';
         foreach ($courses as $course) {
             $coursecontext = context_course::instance($course->id);
             $this->content->items[] = "<a title=\"" . format_string($course->shortname, true, array('context' => $coursecontext)) . "\" " . "href=\"{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}\">" . $icon . format_string(get_course_display_name_for_list($course)) . "</a>";
         }
         // if we listed courses, we are done
         return true;
     }
     if ($hosts = get_my_remotehosts()) {
         $this->content->items[] = get_string('remotehosts', 'mnet');
         $this->content->icons[] = '';
         foreach ($USER->mnet_foreign_host_array as $somehost) {
             $this->content->items[] = $somehost['count'] . get_string('courseson', 'mnet') . '<a title="' . $somehost['name'] . '" href="' . $somehost['url'] . '">' . $icon . $somehost['name'] . '</a>';
         }
         // if we listed hosts, done
         return true;
     }
     return false;
 }
Ejemplo n.º 20
0
function restore_create_users($restore, $xml_file)
{
    global $CFG, $db;
    require_once $CFG->dirroot . '/tag/lib.php';
    $authcache = array();
    // Cache to get some bits from authentication plugins
    $status = true;
    // Users have already been checked by restore_precheck_users() so they are loaded
    // in backup_ids table. They don't need to be loaded (parsed) from XML again. Also, note
    // the same function has performed the needed modifications in the $user->mnethostid field
    // so we don't need to do it again here at all. Just some checks.
    // Get users ids from backup_ids table
    $userids = get_fieldset_select('backup_ids', 'old_id', "backup_code = {$restore->backup_unique_code} AND table_name = 'user'");
    // Have users to process, proceed with them
    if (!empty($userids)) {
        /// Get languages for quick search later
        $languages = get_list_of_languages();
        /// Iterate over all users loaded from xml
        $counter = 0;
        /// Init trailing messages
        $messages = array();
        foreach ($userids as $userid) {
            // Defaults
            $user_exists = false;
            // By default user does not exist
            $newid = null;
            // By default, there is not newid
            // Get record from backup_ids
            $useridsdbrec = backup_getid($restore->backup_unique_code, 'user', $userid);
            // Based in restore_precheck_users() calculations, if the user exists
            // new_id must contain the id of the matching user
            if (!empty($useridsdbrec->new_id)) {
                $user_exists = true;
                $newid = $useridsdbrec->new_id;
            }
            $user = $useridsdbrec->info;
            foreach (array_keys(get_object_vars($user)) as $field) {
                if (!is_array($user->{$field})) {
                    $user->{$field} = backup_todb($user->{$field}, false);
                    if (is_null($user->{$field})) {
                        $user->{$field} = '';
                    }
                }
            }
            //Now, recode some languages (Moodle 1.5)
            if ($user->lang == 'ma_nt') {
                $user->lang = 'mi_nt';
            }
            //Country list updates - MDL-13060
            //Any user whose country code has been deleted or modified needs to be assigned a valid one.
            $country_update_map = array('ZR' => 'CD', 'TP' => 'TL', 'FX' => 'FR', 'KO' => 'RS', 'CS' => 'RS', 'WA' => 'GB');
            if (array_key_exists($user->country, $country_update_map)) {
                $user->country = $country_update_map[$user->country];
            }
            //If language does not exist here - use site default
            if (!array_key_exists($user->lang, $languages)) {
                $user->lang = $CFG->lang;
            }
            //Check if it's admin and coursecreator
            $is_admin = !empty($user->roles['admin']);
            $is_coursecreator = !empty($user->roles['coursecreator']);
            //Check if it's teacher and student
            $is_teacher = !empty($user->roles['teacher']);
            $is_student = !empty($user->roles['student']);
            //Check if it's needed
            $is_needed = !empty($user->roles['needed']);
            //Calculate if it is a course user
            //Has role teacher or student or needed
            $is_course_user = ($is_teacher or $is_student or $is_needed);
            // Only try to perform mnethost/auth modifications if restoring to another server
            // or if, while restoring to same server, the user doesn't exists yet (rebuilt site)
            //
            // So existing user data in same server *won't be modified by restore anymore*,
            // under any circumpstance. If somehting is wrong with existing data, it's server fault.
            if (!backup_is_same_site($restore) || backup_is_same_site($restore) && !$user_exists) {
                //Arriving here, any user with mnet auth and using $CFG->mnet_localhost_id is wrong
                //as own server cannot be accesed over mnet. Change auth to manual and inform about the switch
                if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
                    // Respect registerauth
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                    // inform about the automatic switch of authentication/host
                    if (empty($user->mnethosturl)) {
                        $user->mnethosturl = '----';
                    }
                    $messages[] = get_string('mnetrestore_extusers_switchuserauth', 'admin', $user);
                }
            }
            unset($user->mnethosturl);
            //Flags to see what parts are we going to restore
            $create_user = true;
            $create_roles = true;
            $create_custom_profile_fields = true;
            $create_tags = true;
            $create_preferences = true;
            //If we are restoring course users and it isn't a course user
            if ($restore->users == 1 and !$is_course_user) {
                //If only restoring course_users and user isn't a course_user, inform to $backup_ids
                $status = backup_putid($restore->backup_unique_code, "user", $userid, null, 'notincourse');
                $create_user = false;
                $create_roles = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            if ($user_exists and $create_user) {
                //If user exists mark its newid in backup_ids (the same than old)
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, 'exists');
                $create_user = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            //Here, if create_user, do it
            if ($create_user) {
                //Unset the id because it's going to be inserted with a new one
                unset($user->id);
                /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties)
                if (!empty($CFG->disableuserimages) || empty($user->picture)) {
                    $user->picture = 0;
                }
                //We need to analyse the AUTH field to recode it:
                //   - if the field isn't set, we are in a pre 1.4 backup and $CFG->registerauth will decide
                //   - if the auth isn't enabled in target site, $CFG->registerauth will decide
                //   - finally, if the auth resulting isn't enabled, default to 'manual'
                if (empty($user->auth) || !is_enabled_auth($user->auth)) {
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                }
                if (!is_enabled_auth($user->auth)) {
                    // Final auth check verify, default to manual if not enabled
                    $user->auth = 'manual';
                }
                // Now that we know the auth method, for users to be created without pass
                // if password handling is internal and reset password is available
                // we set the password to "restored" (plain text), so the login process
                // will know how to handle that situation in order to allow the user to
                // recover the password. MDL-20846
                if (empty($user->password)) {
                    // Only if restore comes without password
                    if (!array_key_exists($user->auth, $authcache)) {
                        // Not in cache
                        $userauth = new stdClass();
                        $authplugin = get_auth_plugin($user->auth);
                        $userauth->preventpassindb = $authplugin->prevent_local_passwords();
                        $userauth->isinternal = $authplugin->is_internal();
                        $userauth->canresetpwd = $authplugin->can_reset_password();
                        $authcache[$user->auth] = $userauth;
                    } else {
                        $userauth = $authcache[$user->auth];
                        // Get from cache
                    }
                    // Most external plugins do not store passwords locally
                    if (!empty($userauth->preventpassindb)) {
                        $user->password = '******';
                        // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
                    } else {
                        if ($userauth->isinternal and $userauth->canresetpwd) {
                            $user->password = '******';
                        }
                    }
                }
                //We need to process the POLICYAGREED field to recalculate it:
                //    - if the destination site is different (by wwwroot) reset it.
                //    - if the destination site is the same (by wwwroot), leave it unmodified
                if (!backup_is_same_site($restore)) {
                    $user->policyagreed = 0;
                } else {
                    //Nothing to do, we are in the same server
                }
                //Check if the theme exists in destination server
                $themes = get_list_of_themes();
                if (!in_array($user->theme, $themes)) {
                    $user->theme = '';
                }
                //We are going to create the user
                //The structure is exactly as we need
                $newid = insert_record("user", addslashes_recursive($user));
                //Put the new id
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, "new");
            }
            ///TODO: This seccion is to support pre 1.7 course backups, using old roles
            ///      teacher, coursecreator, student.... providing a basic mapping to new ones.
            ///      Someday we'll drop support for them and this section will be safely deleted (2.0?)
            //Here, if create_roles, do it as necessary
            if ($create_roles) {
                //Get the newid and current info from backup_ids
                $data = backup_getid($restore->backup_unique_code, "user", $userid);
                $newid = $data->new_id;
                $currinfo = $data->info . ",";
                //Now, depending of the role, create records in user_studentes and user_teacher
                //and/or mark it in backup_ids
                if ($is_admin) {
                    //If the record (user_admins) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "admin,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_coursecreator) {
                    //If the record (user_coursecreators) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "coursecreator,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_needed) {
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "needed,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_teacher) {
                    //If the record (teacher) doesn't exists
                    //Put status in backup_ids
                    $currinfo = $currinfo . "teacher,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['teacher']->course = $restore->course_id;
                    $user->roles['teacher']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['teacher']->enrol)) {
                        $user->roles['teacher']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['teacher']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    if ($user->roles['teacher']->editall) {
                        role_assign($rolesmapping['defaultteacheredit'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                        // editting teacher
                    } else {
                        // non editting teacher
                        role_assign($rolesmapping['defaultteacher'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                    }
                }
                if ($is_student) {
                    //Put status in backup_ids
                    $currinfo = $currinfo . "student,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['student']->course = $restore->course_id;
                    $user->roles['student']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['student']->enrol)) {
                        $user->roles['student']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['student']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    role_assign($rolesmapping['defaultstudent'], $newid, 0, $context->id, $user->roles['student']->timestart, $user->roles['student']->timeend, 0, $user->roles['student']->enrol);
                }
                if (!$is_course_user) {
                    //If the record (user) doesn't exists
                    if (!record_exists("user", "id", $newid)) {
                        //Put status in backup_ids
                        $currinfo = $currinfo . "user,";
                        $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    }
                }
            }
            /// Here, if create_custom_profile_fields, do it as necessary
            if ($create_custom_profile_fields) {
                if (isset($user->user_custom_profile_fields)) {
                    foreach ($user->user_custom_profile_fields as $udata) {
                        /// If the profile field has data and the profile shortname-datatype is defined in server
                        if ($udata->field_data) {
                            if ($field = get_record('user_info_field', 'shortname', $udata->field_name, 'datatype', $udata->field_type)) {
                                /// Insert the user_custom_profile_field
                                $rec = new object();
                                $rec->userid = $newid;
                                $rec->fieldid = $field->id;
                                $rec->data = $udata->field_data;
                                insert_record('user_info_data', $rec);
                            }
                        }
                    }
                }
            }
            /// Here, if create_tags, do it as necessary
            if ($create_tags) {
                /// if tags are enabled and there are user tags
                if (!empty($CFG->usetags) && isset($user->user_tags)) {
                    $tags = array();
                    foreach ($user->user_tags as $user_tag) {
                        $tags[] = $user_tag->rawname;
                    }
                    tag_set('user', $newid, $tags);
                }
            }
            //Here, if create_preferences, do it as necessary
            if ($create_preferences) {
                if (isset($user->user_preferences)) {
                    foreach ($user->user_preferences as $user_preference) {
                        //We check if that user_preference exists in DB
                        if (!record_exists("user_preferences", "userid", $newid, "name", $user_preference->name)) {
                            //Prepare the record and insert it
                            $user_preference->userid = $newid;
                            $status = insert_record("user_preferences", $user_preference);
                        }
                    }
                }
            }
            //Do some output
            $counter++;
            if ($counter % 10 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if ($counter % 200 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
        /// End of loop over all the users loaded from backup_ids table
        /// Inform about all the messages geerated while restoring users
        if (!defined('RESTORE_SILENTLY')) {
            if ($messages) {
                echo '<ul>';
                foreach ($messages as $message) {
                    echo '<li>' . $message . '</li>';
                }
                echo '</ul>';
            }
        }
    }
    return $status;
}
Ejemplo n.º 21
0
 /**
  * Performs the synchronisation of members.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'membersync' => 1))) {
         $ltiplugin = enrol_get_plugin('lti');
         $consumers = array();
         $currentusers = array();
         $userphotos = array();
         foreach ($tools as $tool) {
             mtrace("Starting - Member sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $enrolcount = 0;
             $unenrolcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount++;
                     // Check if we do not have a membershipsurl - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsurl) {
                         mtrace("Skipping - Empty membershipsurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a membershipsid - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsid) {
                         mtrace("Skipping - Empty membershipsid {$mtracecontent}.");
                         continue;
                     }
                     $consumer = sha1($ltiuser->membershipsurl . ':' . $ltiuser->membershipsid . ':' . $ltiuser->consumerkey . ':' . $ltiuser->consumersecret);
                     if (in_array($consumer, $consumers)) {
                         // We have already synchronised with this consumer.
                         continue;
                     }
                     $consumers[] = $consumer;
                     $params = array('lti_message_type' => self::LTI_MESSAGE_TYPE, 'id' => $ltiuser->membershipsid, 'lti_version' => self::LTI_VERSION);
                     mtrace("Calling memberships url '{$ltiuser->membershipsurl}' with body '" . json_encode($params) . "'");
                     try {
                         $response = sendOAuthParamsPOST('POST', $ltiuser->membershipsurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/x-www-form-urlencoded', $params);
                     } catch (\Exception $e) {
                         mtrace("Skipping - No response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace($e->getMessage());
                         continue;
                     }
                     // Check the response from the consumer.
                     $data = new \SimpleXMLElement($response);
                     // Check if we did not receive a valid response.
                     if (empty($data->statusinfo)) {
                         mtrace("Skipping - Bad response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace('Skipping - Error parsing the XML received \'' . substr($response, 0, 125) . '\' ... (Displaying only 125 chars)');
                         continue;
                     }
                     // Check if we did not receive a valid response.
                     if (strpos(strtolower($data->statusinfo->codemajor), 'success') === false) {
                         mtrace('Skipping - Error received from the remote system: ' . $data->statusinfo->codemajor . ' ' . $data->statusinfo->severity . ' ' . $data->statusinfo->codeminor);
                         continue;
                     }
                     $members = $data->memberships->member;
                     mtrace(count($members) . ' members received.');
                     foreach ($members as $member) {
                         // Set the user data.
                         $user = new \stdClass();
                         $user->username = \enrol_lti\helper::create_username($ltiuser->consumerkey, $member->user_id);
                         $user->firstname = \core_user::clean_field($member->person_name_given, 'firstname');
                         $user->lastname = \core_user::clean_field($member->person_name_family, 'lastname');
                         $user->email = \core_user::clean_field($member->person_contact_email_primary, 'email');
                         // Get the user data from the LTI consumer.
                         $user = \enrol_lti\helper::assign_user_tool_data($tool, $user);
                         if (!($dbuser = $DB->get_record('user', array('username' => $user->username, 'deleted' => 0)))) {
                             if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                                 // If the email was stripped/not set then fill it with a default one. This
                                 // stops the user from being redirected to edit their profile page.
                                 if (empty($user->email)) {
                                     $user->email = $user->username . "@example.com";
                                 }
                                 $user->auth = 'lti';
                                 $user->id = user_create_user($user);
                                 // Add the information to the necessary arrays.
                                 $currentusers[] = $user->id;
                                 $userphotos[$user->id] = $member->user_image;
                             }
                         } else {
                             // If email is empty remove it, so we don't update the user with an empty email.
                             if (empty($user->email)) {
                                 unset($user->email);
                             }
                             $user->id = $dbuser->id;
                             user_update_user($user);
                             // Add the information to the necessary arrays.
                             $currentusers[] = $user->id;
                             $userphotos[$user->id] = $member->user_image;
                         }
                         if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                             // Enrol the user in the course.
                             \enrol_lti\helper::enrol_user($tool, $user->id);
                         }
                     }
                 }
                 // Now we check if we have to unenrol users who were not listed.
                 if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_UNENROL_MISSING) {
                     // Go through the users and check if any were never listed, if so, remove them.
                     foreach ($ltiusers as $ltiuser) {
                         if (!in_array($ltiuser->userid, $currentusers)) {
                             $instance = new \stdClass();
                             $instance->id = $tool->enrolid;
                             $instance->courseid = $tool->courseid;
                             $instance->enrol = 'lti';
                             $ltiplugin->unenrol_user($instance, $ltiuser->id);
                         }
                     }
                 }
             }
             mtrace("Completed - Synced members for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; enrolled {$enrolcount} members; unenrolled {$unenrolcount} members.");
             mtrace("");
         }
         // Sync the user profile photos.
         mtrace("Started - Syncing user profile images.");
         $counter = 0;
         if (!empty($userphotos)) {
             foreach ($userphotos as $userid => $url) {
                 if ($url) {
                     $result = \enrol_lti\helper::update_user_profile_image($userid, $url);
                     if ($result === \enrol_lti\helper::PROFILE_IMAGE_UPDATE_SUCCESSFUL) {
                         $counter++;
                         mtrace("Profile image succesfully downloaded and created for user '{$userid}' from {$url}.");
                     } else {
                         mtrace($result);
                     }
                 }
             }
         }
         mtrace("Completed - Synced {$counter} profile images.");
     }
 }
Ejemplo n.º 22
0
 public static function plugin_sanity_check() {
     global $CFG, $DB;
     $errorcode = 0;
     if (!isset($CFG->mnet_dispatcher_mode) || $CFG->mnet_dispatcher_mode != 'strict') {
         $errorcode =  PORTFOLIO_MAHARA_ERR_NETWORKING_OFF;
     }
     if (!is_enabled_auth('mnet')) {
         $errorcode = PORTFOLIO_MAHARA_ERR_NOMNETAUTH;
     }
     if (!self::get_mnet_hosts()) {
         $errorcode =  PORTFOLIO_MAHARA_ERR_NOHOSTS;
     }
     return $errorcode;
 }
 /**
  * Cleanup any remote mnet_sessions, kill the local mnet_session data
  *
  * This is called by require_logout in moodlelib
  *
  * @return   void
  */
 function prelogout_hook()
 {
     global $CFG, $USER;
     if (!is_enabled_auth('mnet')) {
         return;
     }
     // If the user is local to this Moodle:
     if ($USER->mnethostid == $this->mnet->id) {
         $this->kill_children($USER->username, sha1($_SERVER['HTTP_USER_AGENT']));
         // Else the user has hit 'logout' at a Service Provider Moodle:
     } else {
         $this->kill_parent($USER->username, sha1($_SERVER['HTTP_USER_AGENT']));
     }
 }
Ejemplo n.º 24
0
                        redirect('access_control.php', get_string('ssl_acl_deny', 'mnet', array($username, $mnethosts[$form->mnet_host_id])));
                    }
                }
            }
        }
    }
    exit;
}
// Explain
print_box(get_string('ssoacldescr', 'mnet'));
// Are the needed bits enabled?
$warn = '';
if (empty($CFG->mnet_dispatcher_mode) || $CFG->mnet_dispatcher_mode !== 'strict') {
    $warn = '<p>' . get_string('mnetdisabled', 'mnet') . '</p>';
}
if (!is_enabled_auth('mnet')) {
    $warn .= '<p>' . get_string('authmnetdisabled', 'mnet') . '</p>';
}
if (get_config('auth/mnet', 'auto_add_remote_users') != true) {
    $warn .= '<p>' . get_string('authmnetautoadddisabled', 'mnet') . '</p>';
}
if (!empty($warn)) {
    $warn = '<p>' . get_string('ssoaclneeds', 'mnet') . '</p>' . $warn;
    print_box($warn);
}
// output the ACL table
$columns = array("username", "mnet_host_id", "access", "delete");
$headings = array();
$string = array('username' => get_string('username'), 'mnet_host_id' => get_string('remotehost', 'mnet'), 'access' => get_string('accesslevel', 'mnet'), 'delete' => get_string('delete'));
foreach ($columns as $column) {
    if ($sort != $column) {
Ejemplo n.º 25
0
 /**
  * Performs the synchronisation of grades.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $DB, $CFG;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     require_once $CFG->dirroot . '/lib/completionlib.php';
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/grade/querylib.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'gradesync' => 1))) {
         foreach ($tools as $tool) {
             mtrace("Starting - Grade sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $sendcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 $completion = new \completion_info(get_course($tool->courseid));
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount = $usercount + 1;
                     // Check if we do not have a serviceurl - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->serviceurl)) {
                         mtrace("Skipping - Empty serviceurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a sourceid - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->sourceid)) {
                         mtrace("Skipping - Empty sourceid {$mtracecontent}.");
                         continue;
                     }
                     // Need a valid context to continue.
                     if (!($context = \context::instance_by_id($tool->contextid))) {
                         mtrace("Failed - Invalid contextid '{$tool->contextid}' for the tool '{$tool->id}'.");
                         continue;
                     }
                     // Ok, let's get the grade.
                     $grade = false;
                     if ($context->contextlevel == CONTEXT_COURSE) {
                         // Check if the user did not completed the course when it was required.
                         if ($tool->gradesynccompletion && !$completion->is_course_complete($ltiuser->userid)) {
                             mtrace("Skipping - Course not completed {$mtracecontent}.");
                             continue;
                         }
                         // Get the grade.
                         if ($grade = grade_get_course_grade($ltiuser->userid, $tool->courseid)) {
                             $grademax = floatval($grade->item->grademax);
                             $grade = $grade->grade;
                         }
                     } else {
                         if ($context->contextlevel == CONTEXT_MODULE) {
                             $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
                             if ($tool->gradesynccompletion) {
                                 $data = $completion->get_data($cm, false, $ltiuser->userid);
                                 if ($data->completionstate != COMPLETION_COMPLETE_PASS && $data->completionstate != COMPLETION_COMPLETE) {
                                     mtrace("Skipping - Activity not completed {$mtracecontent}.");
                                     continue;
                                 }
                             }
                             $grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $ltiuser->userid);
                             if (!empty($grades->items[0]->grades)) {
                                 $grade = reset($grades->items[0]->grades);
                                 if (!empty($grade->item)) {
                                     $grademax = floatval($grade->item->grademax);
                                 } else {
                                     $grademax = floatval($grades->items[0]->grademax);
                                 }
                                 $grade = $grade->grade;
                             }
                         }
                     }
                     if ($grade === false || $grade === null || strlen($grade) < 1) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // No need to be dividing by zero.
                     if (empty($grademax)) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // This can happen if the sync process has an unexpected error.
                     if ($grade == $ltiuser->lastgrade) {
                         mtrace("Not sent - The grade {$mtracecontent} was not sent as the grades are the same.");
                         continue;
                     }
                     // Sync with the external system.
                     $floatgrade = $grade / $grademax;
                     $body = \enrol_lti\helper::create_service_body($ltiuser->sourceid, $floatgrade);
                     try {
                         $response = sendOAuthBodyPOST('POST', $ltiuser->serviceurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/xml', $body);
                     } catch (\Exception $e) {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                         mtrace($e->getMessage());
                         continue;
                     }
                     if (strpos(strtolower($response), 'success') !== false) {
                         $DB->set_field('enrol_lti_users', 'lastgrade', intval($grade), array('id' => $ltiuser->id));
                         mtrace("Success - The grade '{$floatgrade}' {$mtracecontent} was sent.");
                         $sendcount = $sendcount + 1;
                     } else {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                     }
                 }
             }
             mtrace("Completed - Synced grades for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; sent {$sendcount} grades.");
             mtrace("");
         }
     }
 }
Ejemplo n.º 26
0
/**
 * send_password_change_info.
 *
 * @uses $CFG
 * @param user $user A {@link $USER} object
 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
 *          was blocked by user and "false" if there was another sort of error.
 */
function send_password_change_info($user)
{
    global $CFG;
    $site = get_site();
    $supportuser = generate_email_supportuser();
    $systemcontext = get_context_instance(CONTEXT_SYSTEM);
    $data = new object();
    $data->firstname = $user->firstname;
    $data->lastname = $user->lastname;
    $data->sitename = format_string($site->fullname);
    $data->admin = generate_email_signoff();
    $userauth = get_auth_plugin($user->auth);
    if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
        $message = get_string('emailpasswordchangeinfodisabled', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
        return email_to_user($user, $supportuser, $subject, $message);
    }
    if ($userauth->can_change_password() and $userauth->change_password_url()) {
        // we have some external url for password changing
        $data->link .= $userauth->change_password_url();
    } else {
        //no way to change password, sorry
        $data->link = '';
    }
    if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
        $message = get_string('emailpasswordchangeinfo', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    } else {
        $message = get_string('emailpasswordchangeinfofail', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    }
    return email_to_user($user, $supportuser, $subject, $message);
}
Ejemplo n.º 27
0
/**
 * This function processes a user's submitted token to validate the request to set a new password.
 * If the user's token is validated, they are prompted to set a new password.
 * @param string $token the one-use identifier which should verify the password reset request as being valid.
 * @return void
 */
function core_login_process_password_set($token)
{
    global $DB, $CFG, $OUTPUT, $PAGE, $SESSION;
    $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
    $sql = "SELECT u.*, upr.token, upr.timerequested, upr.id as tokenid\n              FROM {user} u\n              JOIN {user_password_resets} upr ON upr.userid = u.id\n             WHERE upr.token = ?";
    $user = $DB->get_record_sql($sql, array($token));
    $forgotpasswordurl = "{$CFG->httpswwwroot}/login/forgot_password.php";
    if (empty($user) or $user->timerequested < time() - $pwresettime - DAYSECS) {
        // There is no valid reset request record - not even a recently expired one.
        // (suspicious)
        // Direct the user to the forgot password page to request a password reset.
        echo $OUTPUT->header();
        notice(get_string('noresetrecord'), $forgotpasswordurl);
        die;
        // Never reached.
    }
    if ($user->timerequested < time() - $pwresettime) {
        // There is a reset record, but it's expired.
        // Direct the user to the forgot password page to request a password reset.
        $pwresetmins = floor($pwresettime / MINSECS);
        echo $OUTPUT->header();
        notice(get_string('resetrecordexpired', '', $pwresetmins), $forgotpasswordurl);
        die;
        // Never reached.
    }
    if ($user->auth === 'nologin' or !is_enabled_auth($user->auth)) {
        // Bad luck - user is not able to login, do not let them set password.
        echo $OUTPUT->header();
        print_error('forgotteninvalidurl');
        die;
        // Never reached.
    }
    // Check this isn't guest user.
    if (isguestuser($user)) {
        print_error('cannotresetguestpwd');
    }
    // Token is correct, and unexpired.
    $mform = new login_set_password_form(null, null, 'post', '', 'autocomplete="yes"');
    $data = $mform->get_data();
    if (empty($data)) {
        // User hasn't submitted form, they got here directly from email link.
        // Next, display the form.
        $setdata = new stdClass();
        $setdata->username = $user->username;
        $setdata->username2 = $user->username;
        $setdata->token = $user->token;
        $mform->set_data($setdata);
        $PAGE->verify_https_required();
        echo $OUTPUT->header();
        echo $OUTPUT->box(get_string('setpasswordinstructions'), 'generalbox boxwidthnormal boxaligncenter');
        $mform->display();
        echo $OUTPUT->footer();
        return;
    } else {
        // User has submitted form.
        // Delete this token so it can't be used again.
        $DB->delete_records('user_password_resets', array('id' => $user->tokenid));
        $userauth = get_auth_plugin($user->auth);
        if (!$userauth->user_update_password($user, $data->password)) {
            print_error('errorpasswordupdate', 'auth');
        }
        // Reset login lockout (if present) before a new password is set.
        login_unlock_account($user);
        // Clear any requirement to change passwords.
        unset_user_preference('auth_forcepasswordchange', $user);
        unset_user_preference('create_password', $user);
        if (!empty($user->lang)) {
            // Unset previous session language - use user preference instead.
            unset($SESSION->lang);
        }
        complete_user_login($user);
        // Triggers the login event.
        $urltogo = core_login_get_return_url();
        unset($SESSION->wantsurl);
        redirect($urltogo, get_string('passwordset'), 1);
    }
}
Ejemplo n.º 28
0
if (empty($frm->username) && $authsequence[0] != 'shibboleth') {
    // See bug 5184
    if (!empty($_GET["username"])) {
        $frm->username = clean_param($_GET["username"], PARAM_RAW);
        // we do not want data from _POST here
    } else {
        $frm->username = get_moodle_cookie();
    }
    $frm->password = "";
}
if (!empty($frm->username)) {
    $focus = "password";
} else {
    $focus = "username";
}
if (!empty($CFG->registerauth) or is_enabled_auth('none') or !empty($CFG->auth_instructions)) {
    $show_instructions = true;
} else {
    $show_instructions = false;
}
$potentialidps = array();
foreach ($authsequence as $authname) {
    $authplugin = get_auth_plugin($authname);
    $potentialidps = array_merge($potentialidps, $authplugin->loginpage_idp_list($SESSION->wantsurl));
}
if (!empty($SESSION->loginerrormsg)) {
    // We had some errors before redirect, show them now.
    $errormsg = $SESSION->loginerrormsg;
    unset($SESSION->loginerrormsg);
} else {
    if ($testsession) {
Ejemplo n.º 29
0
$toolid = null;
$token = null;
$filearguments = get_file_argument();
$arguments = explode('/', trim($filearguments, '/'));
if (count($arguments) >= 2) {
    // Can put cartridge.xml at the end, or anything really.
    list($toolid, $token) = $arguments;
}
$toolid = optional_param('id', $toolid, PARAM_INT);
$token = optional_param('token', $token, PARAM_ALPHANUM);
// Only show the cartridge if the token parameter is correct.
// If we do not compare with a shared secret, someone could very easily
// guess an id for the enrolment.
if (!\enrol_lti\helper::verify_tool_token($toolid, $token)) {
    throw new \moodle_exception('incorrecttoken', 'enrol_lti');
}
$tool = \enrol_lti\helper::get_lti_tool($toolid);
if (!is_enabled_auth('lti')) {
    print_error('pluginnotenabled', 'auth', '', get_string('pluginname', 'auth_lti'));
} else {
    if (!enrol_is_enabled('lti')) {
        print_error('enrolisdisabled', 'enrol_lti');
    } else {
        if ($tool->status != ENROL_INSTANCE_ENABLED) {
            print_error('enrolisdisabled', 'enrol_lti');
        } else {
            header('Content-Type: text/xml; charset=utf-8');
            echo \enrol_lti\helper::create_cartridge($toolid);
        }
    }
}
Ejemplo n.º 30
0
 /**
  * Authenticate user using username+password or token.
  * This function sets up $USER global.
  * It is safe to use has_capability() after this.
  * This method also verifies user is allowed to use this
  * server.
  */
 protected function authenticate_user()
 {
     global $CFG, $DB;
     if (!NO_MOODLE_COOKIES) {
         throw new coding_exception('Cookies must be disabled in WS servers!');
     }
     $loginfaileddefaultparams = array('context' => context_system::instance(), 'other' => array('method' => $this->authmethod, 'reason' => null));
     if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
         //we check that authentication plugin is enabled
         //it is only required by simple authentication
         if (!is_enabled_auth('webservice')) {
             throw new webservice_access_exception('The web service authentication plugin is disabled.');
         }
         if (!($auth = get_auth_plugin('webservice'))) {
             throw new webservice_access_exception('The web service authentication plugin is missing.');
         }
         $this->restricted_context = context_system::instance();
         if (!$this->username) {
             throw new moodle_exception('missingusername', 'webservice');
         }
         if (!$this->password) {
             throw new moodle_exception('missingpassword', 'webservice');
         }
         if (!$auth->user_login_webservice($this->username, $this->password)) {
             // Log failed login attempts.
             $params = $loginfaileddefaultparams;
             $params['other']['reason'] = 'password';
             $params['other']['username'] = $this->username;
             $event = \core\event\webservice_login_failed::create($params);
             $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '', get_string('failedtolog', 'webservice') . ": " . $this->username . "/" . $this->password . " - " . getremoteaddr(), 0));
             $event->trigger();
             throw new moodle_exception('wrongusernamepassword', 'webservice');
         }
         $user = $DB->get_record('user', array('username' => $this->username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
     } else {
         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN) {
             $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
         } else {
             $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
         }
     }
     //Non admin can not authenticate if maintenance mode
     $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
     if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
         throw new moodle_exception('sitemaintenance', 'admin');
     }
     //only confirmed user should be able to call web service
     if (!empty($user->deleted)) {
         $params = $loginfaileddefaultparams;
         $params['other']['reason'] = 'user_deleted';
         $params['other']['username'] = $user->username;
         $event = \core\event\webservice_login_failed::create($params);
         $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice', $user->username) . " - " . getremoteaddr(), 0, $user->id));
         $event->trigger();
         throw new webservice_access_exception('Refused web service access for deleted username: '******'other']['reason'] = 'user_unconfirmed';
         $params['other']['username'] = $user->username;
         $event = \core\event\webservice_login_failed::create($params);
         $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice', $user->username) . " - " . getremoteaddr(), 0, $user->id));
         $event->trigger();
         throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
     }
     //check the user is suspended
     if (!empty($user->suspended)) {
         $params = $loginfaileddefaultparams;
         $params['other']['reason'] = 'user_unconfirmed';
         $params['other']['username'] = $user->username;
         $event = \core\event\webservice_login_failed::create($params);
         $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice', $user->username) . " - " . getremoteaddr(), 0, $user->id));
         $event->trigger();
         throw new webservice_access_exception('Refused web service access for suspended username: '******'other']['reason'] = 'password_expired';
             $params['other']['username'] = $user->username;
             $event = \core\event\webservice_login_failed::create($params);
             $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice', $user->username) . " - " . getremoteaddr(), 0, $user->id));
             $event->trigger();
             throw new webservice_access_exception('Refused web service access for password expired username: '******'nologin') {
         $params = $loginfaileddefaultparams;
         $params['other']['reason'] = 'login';
         $params['other']['username'] = $user->username;
         $event = \core\event\webservice_login_failed::create($params);
         $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice', $user->username) . " - " . getremoteaddr(), 0, $user->id));
         $event->trigger();
         throw new webservice_access_exception('Refused web service access for nologin authentication username: '******'You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
     }
     external_api::set_context_restriction($this->restricted_context);
 }