예제 #1
0
/**
 * this function schedules the user synchronisation updates
 *
 * Implementation specific : Generic
 */
function local_ent_installer_cron()
{
    global $CFG;
    if (!get_config('local_ent_installer', 'cron_enable')) {
        return;
    }
    $now = time();
    $needscron = false;
    $chour = 0 + get_config('local_ent_installer', 'cron_hour');
    $cmin = 0 + get_config('local_ent_installer', 'cron_min');
    $cfreq = get_config('local_ent_installer', 'cron_enable');
    $now = time();
    $nowdt = getdate($now);
    $expectedtime = get_config('local_ent_installer', 'last_sync_date') + $cfreq - HOURSEC;
    $crondebug = optional_param('crondebug', false, PARAM_BOOL);
    if ($now < $expectedtime && !$crondebug) {
        return;
    }
    if (!empty($CFG->ent_installer_running)) {
        return;
    }
    if ($nowdt['hours'] * 60 + $nowdt['minutes'] >= $chour * 60 + $cmin || $crondebug) {
        set_config('ent_installer_running', 1);
        set_config('last_sync_date', $now, 'local_ent_installer');
        // Get ldap params from real ldap plugin.
        $ldapauth = get_auth_plugin('ldap');
        $options = array('host' => $CFG->wwwroot);
        // Run the customised synchro.
        local_ent_installer_sync_users($ldapauth, $options);
        set_config('ent_installer_running', null);
    } else {
        mtrace('waiting for valid time ');
    }
}
예제 #2
0
 function get_content()
 {
     global $USER, $CFG, $SESSION;
     $wwwroot = '';
     $signup = '';
     if ($this->content !== NULL) {
         return $this->content;
     }
     if (empty($CFG->loginhttps)) {
         $wwwroot = $CFG->wwwroot;
     } else {
         // This actually is not so secure ;-), 'cause we're
         // in unencrypted connection...
         $wwwroot = str_replace("http://", "https://", $CFG->wwwroot);
     }
     if (!empty($CFG->registerauth)) {
         $authplugin = get_auth_plugin($CFG->registerauth);
         if ($authplugin->can_signup()) {
             $signup = $wwwroot . '/login/signup.php';
         }
     }
     // TODO: now that we have multiauth it is hard to find out if there is a way to change password
     $forgot = $wwwroot . '/login/forgot_password.php';
     if (!empty($CFG->loginpasswordautocomplete)) {
         $autocomplete = 'autocomplete="off"';
     } else {
         $autocomplete = '';
     }
     $username = get_moodle_cookie();
     $this->content = new stdClass();
     $this->content->footer = '';
     $this->content->text = '';
     if (!isloggedin() or isguestuser()) {
         // Show the block
         if (empty($CFG->authloginviaemail)) {
             $strusername = get_string('username');
         } else {
             $strusername = get_string('usernameemail');
         }
         $this->content->text .= "\n" . '<form class="loginform" id="login" method="post" action="' . get_login_url() . '" ' . $autocomplete . '>';
         $this->content->text .= '<div class="c1 fld username"><label for="login_username">' . $strusername . '</label>';
         $this->content->text .= '<input type="text" name="username" id="login_username" value="' . s($username) . '" /></div>';
         $this->content->text .= '<div class="c1 fld password"><label for="login_password">' . get_string('password') . '</label>';
         $this->content->text .= '<input type="password" name="password" id="login_password" value="" ' . $autocomplete . ' /></div>';
         if (isset($CFG->rememberusername) and $CFG->rememberusername == 2) {
             $checked = $username ? 'checked="checked"' : '';
             $this->content->text .= '<div class="c1 rememberusername"><input type="checkbox" name="rememberusername" id="rememberusername" value="1" ' . $checked . '/>';
             $this->content->text .= ' <label for="rememberusername">' . get_string('rememberusername', 'admin') . '</label></div>';
         }
         $this->content->text .= '<div class="c1 btn"><input type="submit" value="' . get_string('login') . '" /></div>';
         $this->content->text .= "</form>\n";
         if (!empty($signup)) {
             $this->content->footer .= '<div><a href="' . $signup . '">' . get_string('startsignup') . '</a></div>';
         }
         if (!empty($forgot)) {
             $this->content->footer .= '<div><a href="' . $forgot . '">' . get_string('forgotaccount') . '</a></div>';
         }
     }
     return $this->content;
 }
예제 #3
0
 function definition_after_data()
 {
     global $CFG, $DB;
     $mform =& $this->_form;
     $userid = $mform->getElementValue('id');
     // if language does not exist, use site default lang
     if ($langsel = $mform->getElementValue('lang')) {
         $lang = reset($langsel);
         // missing _utf8 in language, add it before further processing. MDL-11829 MDL-16845
         if (strpos($lang, '_utf8') === false) {
             $lang = $lang . '_utf8';
             $lang_el =& $mform->getElement('lang');
             $lang_el->setValue($lang);
         }
         // check lang exists
         if (!file_exists($CFG->dataroot . '/lang/' . $lang) and !file_exists($CFG->dirroot . '/lang/' . $lang)) {
             $lang_el =& $mform->getElement('lang');
             $lang_el->setValue($CFG->lang);
         }
     }
     if ($user = $DB->get_record('user', array('id' => $userid))) {
         // remove description
         if (empty($user->description) && !empty($CFG->profilesforenrolledusersonly) && !$DB->record_exists('role_assignments', array('userid' => $userid))) {
             $mform->removeElement('description');
         }
         // print picture
         if (!empty($CFG->gdversion)) {
             $image_el =& $mform->getElement('currentpicture');
             if ($user and $user->picture) {
                 $image_el->setValue(print_user_picture($user, SITEID, $user->picture, 64, true, false, '', true));
             } else {
                 $image_el->setValue(get_string('none'));
             }
         }
         /// disable fields that are locked by auth plugins
         $fields = get_user_fieldnames();
         $authplugin = get_auth_plugin($user->auth);
         foreach ($fields as $field) {
             if (!$mform->elementExists($field)) {
                 continue;
             }
             $configvariable = 'field_lock_' . $field;
             if (isset($authplugin->config->{$configvariable})) {
                 if ($authplugin->config->{$configvariable} === 'locked') {
                     $mform->hardFreeze($field);
                     $mform->setConstant($field, $user->{$field});
                 } else {
                     if ($authplugin->config->{$configvariable} === 'unlockedifempty' and $user->{$field} != '') {
                         $mform->hardFreeze($field);
                         $mform->setConstant($field, $user->{$field});
                     }
                 }
             }
         }
         /// Next the customisable profile fields
         profile_definition_after_data($mform, $user->id);
     } else {
         profile_definition_after_data($mform, 0);
     }
 }
예제 #4
0
 function definition_after_data()
 {
     global $CFG, $DB, $OUTPUT;
     $mform =& $this->_form;
     $userid = $mform->getElementValue('id');
     // if language does not exist, use site default lang
     if ($langsel = $mform->getElementValue('lang')) {
         $lang = reset($langsel);
         // check lang exists
         if (!get_string_manager()->translation_exists($lang, false)) {
             $lang_el =& $mform->getElement('lang');
             $lang_el->setValue($CFG->lang);
         }
     }
     if ($user = $DB->get_record('user', array('id' => $userid))) {
         // remove description
         if (empty($user->description) && !empty($CFG->profilesforenrolledusersonly) && !$DB->record_exists('role_assignments', array('userid' => $userid))) {
             $mform->removeElement('description_editor');
         }
         // print picture
         $context = context_user::instance($user->id, MUST_EXIST);
         $fs = get_file_storage();
         $hasuploadedpicture = $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.jpg');
         if (!empty($user->picture) && $hasuploadedpicture) {
             $imagevalue = $OUTPUT->user_picture($user, array('courseid' => SITEID, 'size' => 64));
         } else {
             $imagevalue = get_string('none');
         }
         $imageelement = $mform->getElement('currentpicture');
         $imageelement->setValue($imagevalue);
         if ($mform->elementExists('deletepicture') && !$hasuploadedpicture) {
             $mform->removeElement('deletepicture');
         }
         /// disable fields that are locked by auth plugins
         $fields = get_user_fieldnames();
         $authplugin = get_auth_plugin($user->auth);
         foreach ($fields as $field) {
             if (!$mform->elementExists($field)) {
                 continue;
             }
             $configvariable = 'field_lock_' . $field;
             if (isset($authplugin->config->{$configvariable})) {
                 if ($authplugin->config->{$configvariable} === 'locked') {
                     $mform->hardFreeze($field);
                     $mform->setConstant($field, $user->{$field});
                 } else {
                     if ($authplugin->config->{$configvariable} === 'unlockedifempty' and $user->{$field} != '') {
                         $mform->hardFreeze($field);
                         $mform->setConstant($field, $user->{$field});
                     }
                 }
             }
         }
         /// Next the customisable profile fields
         profile_definition_after_data($mform, $user->id);
     } else {
         profile_definition_after_data($mform, 0);
     }
 }
예제 #5
0
 /**
  * Run users sync.
  */
 public function execute()
 {
     global $CFG;
     if (is_enabled_auth('cas')) {
         $auth = get_auth_plugin('cas');
         $auth->sync_users(true);
     }
 }
예제 #6
0
 function validation($data, $files)
 {
     global $CFG;
     $errors = parent::validation($data, $files);
     $authplugin = get_auth_plugin($CFG->registerauth);
     if (record_exists('user', 'username', $data['username'], 'mnethostid', $CFG->mnet_localhost_id)) {
         $errors['username'] = get_string('usernameexists');
     } else {
         if (empty($CFG->extendedusernamechars)) {
             $string = eregi_replace("[^(-\\.[:alnum:])]", '', $data['username']);
             if (strcmp($data['username'], $string)) {
                 $errors['username'] = get_string('alphanumerical');
             }
         }
     }
     //check if user exists in external db
     //TODO: maybe we should check all enabled plugins instead
     if ($authplugin->user_exists($data['username'])) {
         $errors['username'] = get_string('usernameexists');
     }
     if (!validate_email($data['email'])) {
         $errors['email'] = get_string('invalidemail');
     } else {
         if (record_exists('user', 'email', $data['email'])) {
             $errors['email'] = get_string('emailexists') . ' <a href="forgot_password.php">' . get_string('newpassword') . '?</a>';
         }
     }
     if (empty($data['email2'])) {
         $errors['email2'] = get_string('missingemail');
     } else {
         if ($data['email2'] != $data['email']) {
             $errors['email2'] = get_string('invalidemail');
         }
     }
     if (!isset($errors['email'])) {
         if ($err = email_is_not_allowed($data['email'])) {
             $errors['email'] = $err;
         }
     }
     $errmsg = '';
     if (!check_password_policy($data['password'], $errmsg)) {
         $errors['password'] = $errmsg;
     }
     if (signup_captcha_enabled()) {
         $recaptcha_element = $this->_form->getElement('recaptcha_element');
         if (!empty($this->_form->_submitValues['recaptcha_challenge_field'])) {
             $challenge_field = $this->_form->_submitValues['recaptcha_challenge_field'];
             $response_field = $this->_form->_submitValues['recaptcha_response_field'];
             if (true !== ($result = $recaptcha_element->verify($challenge_field, $response_field))) {
                 $errors['recaptcha'] = $result;
             }
         } else {
             $errors['recaptcha'] = get_string('missingrecaptchachallengefield');
         }
     }
     return $errors;
 }
예제 #7
0
 function __logout()
 {
     $authsequence = get_enabled_auth_plugins();
     // auths, in sequence
     foreach ($authsequence as $authname) {
         $authplugin = get_auth_plugin($authname);
         $authplugin->logoutpage_hook();
     }
     require_logout();
 }
예제 #8
0
 /**
  * Tests that the locations in the auth_db API that update a user trigger the user_updated event.
  */
 public function test_user_updated()
 {
     global $CFG, $DB;
     $this->preventResetByRollback();
     // Initialise the database.
     $authdbtestcase = new auth_db_testcase();
     $authdbtestcase->init_auth_database();
     $auth = get_auth_plugin('db');
     $auth->db_init();
     // Add a suspended user.
     $user = array();
     $user['username'] = '******';
     $user['suspended'] = '1';
     $user['mnethostid'] = $CFG->mnet_localhost_id;
     $user['auth'] = 'db';
     $this->getDataGenerator()->create_user($user);
     // Add a user to the auth_db_users table - we will then call sync_users to
     // deal with the record here. In this case it will un-suspend the user.
     $user = new stdClass();
     $user->name = 'mark';
     $user->pass = '******';
     $user->email = '*****@*****.**';
     $user->id = $DB->insert_record('auth_db_users', $user);
     // Set the config to remove the suspension on the user.
     set_config('removeuser', AUTH_REMOVEUSER_SUSPEND, 'auth/db');
     $auth->config->removeuser = AUTH_REMOVEUSER_SUSPEND;
     // Run sync_users and capture the user_updated event.
     $sink = $this->redirectEvents();
     $trace = new null_progress_trace();
     $auth->sync_users($trace, false);
     $events = $sink->get_events();
     $sink->close();
     // Check that there is only one event.
     $this->assertEquals(1, count($events));
     // Get the event.
     $event = array_pop($events);
     // Test that the user updated event was triggered - no need to test the other
     // details of the event as that is done extensively in other unit tests.
     $this->assertInstanceOf('\\core\\event\\user_updated', $event);
     // Run sync_users and capture the user_updated event.
     $sink = $this->redirectEvents();
     $auth->update_user_record('mark');
     $events = $sink->get_events();
     $sink->close();
     // Check that there is only one event.
     $this->assertEquals(1, count($events));
     // Get the event.
     $event = array_pop($events);
     // Test that the user updated event was triggered - no need to test the other
     // details of the event as that is done extensively in other unit tests.
     $this->assertInstanceOf('\\core\\event\\user_updated', $event);
 }
예제 #9
0
 function validation($data)
 {
     global $CFG;
     $errors = array();
     $authplugin = get_auth_plugin($CFG->registerauth);
     if (record_exists('user', 'username', $data['username'], 'mnethostid', $CFG->mnet_localhost_id)) {
         $errors['username'] = get_string('usernameexists');
     } else {
         if (empty($CFG->extendedusernamechars)) {
             $string = eregi_replace("[^(-\\.[:alnum:])]", '', $data['username']);
             if (strcmp($data['username'], $string)) {
                 $errors['username'] = get_string('alphanumerical');
             }
         }
     }
     //check if user exists in external db
     //TODO: maybe we should check all enabled plugins instead
     if ($authplugin->user_exists($data['username'])) {
         $errors['username'] = get_string('usernameexists');
     }
     if (!validate_email($data['email'])) {
         $errors['email'] = get_string('invalidemail');
     } else {
         if (record_exists('user', 'email', $data['email'])) {
             $errors['email'] = get_string('emailexists') . ' <a href="forgot_password.php">' . get_string('newpassword') . '?</a>';
         }
     }
     if (empty($data['email2'])) {
         $errors['email2'] = get_string('missingemail');
     } else {
         if ($data['email2'] != $data['email']) {
             $errors['email2'] = get_string('invalidemail');
         }
     }
     if (!isset($errors['email'])) {
         if ($err = email_is_not_allowed($data['email'])) {
             $errors['email'] = $err;
         }
     }
     if (!check_password_policy($data['password'], $errmsg)) {
         $errors['password'] = $errmsg;
     }
     if (0 == count($errors)) {
         return true;
     } else {
         return $errors;
     }
 }
예제 #10
0
 function definition_after_data()
 {
     global $CFG;
     $mform =& $this->_form;
     $userid = $mform->getElementValue('id');
     // if language does not exist, use site default lang
     if ($langsel = $mform->getElementValue('lang')) {
         $lang = reset($langsel);
         if (!file_exists($CFG->dataroot . '/lang/' . $lang) and !file_exists($CFG->dirroot . '/lang/' . $lang)) {
             $lang_el =& $mform->getElement('lang');
             $lang_el->setValue($CFG->lang);
         }
     }
     if ($user = get_record('user', 'id', $userid)) {
         // print picture
         if (!empty($CFG->gdversion)) {
             $image_el =& $mform->getElement('currentpicture');
             if ($user and $user->picture) {
                 $image_el->setValue(print_user_picture($user->id, SITEID, $user->picture, 64, true, false, '', true));
             } else {
                 $image_el->setValue(get_string('none'));
             }
         }
         /// disable fields that are locked by auth plugins
         $fields = get_user_fieldnames();
         $freezefields = array();
         $authplugin = get_auth_plugin($user->auth);
         foreach ($fields as $field) {
             if (!$mform->elementExists($field)) {
                 continue;
             }
             $configvariable = 'field_lock_' . $field;
             if (isset($authplugin->config->{$configvariable})) {
                 if ($authplugin->config->{$configvariable} === 'locked') {
                     $freezefields[] = $field;
                 } else {
                     if ($authplugin->config->{$configvariable} === 'unlockedifempty' and $user->{$field} != '') {
                         $freezefields[] = $field;
                     }
                 }
             }
         }
         $mform->hardFreeze($freezefields);
     }
     /// Next the customisable profile fields
     profile_definition_after_data($mform);
 }
예제 #11
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());
 }
예제 #12
0
 function get_content()
 {
     global $USER, $CFG;
     $wwwroot = '';
     $signup = '';
     if ($this->content !== NULL) {
         return $this->content;
     }
     if (empty($CFG->loginhttps)) {
         $wwwroot = $CFG->wwwroot;
     } else {
         // This actually is not so secure ;-), 'cause we're
         // in unencrypted connection...
         $wwwroot = str_replace("http://", "https://", $CFG->wwwroot);
     }
     if (!empty($CFG->registerauth)) {
         $authplugin = get_auth_plugin($CFG->registerauth);
         if ($authplugin->can_signup()) {
             $signup = $wwwroot . '/login/signup.php';
         }
     }
     // TODO: now that we have multiauth it is hard to find out if there is a way to change password
     $forgot = $wwwroot . '/login/forgot_password.php';
     $username = get_moodle_cookie() === 'nobody' ? '' : get_moodle_cookie();
     $this->content->footer = '';
     $this->content->text = '';
     if (!isloggedin() or isguestuser()) {
         // Show the block
         $this->content->text .= "\n" . '<form class="loginform" id="login" method="post" action="' . $wwwroot . '/login/index.php">';
         $this->content->text .= '<div class="c1 fld username"><label for="login_username">' . get_string('username') . '</label>';
         $this->content->text .= '<input type="text" name="username" id="login_username" value="' . s($username) . '" /></div>';
         $this->content->text .= '<div class="c1 fld password"><label for="login_password">' . get_string('password') . '</label>';
         $this->content->text .= '<input type="password" name="password" id="login_password" value="" /></div>';
         $this->content->text .= '<div class="c1 btn"><input type="submit" value="' . get_string('login') . '" /></div>';
         $this->content->text .= "</form>\n";
         if (!empty($signup)) {
             $this->content->footer .= '<div><a href="' . $signup . '">' . get_string('startsignup') . '</a></div>';
         }
         if (!empty($forgot)) {
             $this->content->footer .= '<div><a href="' . $forgot . '">' . get_string('forgotaccount') . '</a></div>';
         }
     }
     return $this->content;
 }
예제 #13
0
 /**
  * Display the file listing - no login required
  * @global <type> $SESSION
  * @param <type> $ajax
  * @return <type>
  */
 public function print_login($ajax = true)
 {
     global $SESSION, $CFG, $DB;
     //jump to the peer to create a session
     require_once $CFG->dirroot . '/mnet/lib.php';
     $this->ensure_environment();
     $mnetauth = get_auth_plugin('mnet');
     $host = $DB->get_record('mnet_host', array('id' => $this->options['peer']));
     //need to retrieve the host url
     $url = $mnetauth->start_jump_session($host->id, '/repository/ws.php?callback=yes&repo_id=' . $this->id, true);
     //set session
     $SESSION->loginmahara = true;
     $ret = array();
     $popup_btn = new stdclass();
     $popup_btn->type = 'popup';
     $popup_btn->url = $url;
     $ret['login'] = array($popup_btn);
     return $ret;
 }
    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);
    }
예제 #15
0
 function validation($data, $files)
 {
     global $CFG;
     $invite = false;
     $sitecontext = get_context_instance(CONTEXT_SYSTEM);
     if (isloggedin() && has_capability('moodle/local:invitenewuser', $sitecontext)) {
         $invite = true;
     }
     $errors = parent::validation($data, $files);
     $authplugin = get_auth_plugin($CFG->registerauth);
     if ($data['password1'] != $data['password2']) {
         $errors['password1'] = get_string('passwordsdiffer');
         $errors['password2'] = get_string('passwordsdiffer');
         return $errors;
     }
     if (record_exists('user', 'username', $data['username'], 'mnethostid', $CFG->mnet_localhost_id)) {
         $errors['username'] = get_string('usernameexists');
     } else {
         if (empty($CFG->extendedusernamechars)) {
             $string = eregi_replace("[^(-\\.[:alnum:])]", '', $data['username']);
             if (strcmp($data['username'], $string)) {
                 $errors['username'] = get_string('alphanumerical');
             }
         }
     }
     //check if user exists in external db
     //TODO: maybe we should check all enabled plugins instead
     if ($authplugin->user_exists($data['username'])) {
         $errors['username'] = get_string('usernameexists');
     }
     $errmsg = '';
     if (!check_password_policy($data['password1'], $errmsg)) {
         $errors['password1'] = $errmsg;
     }
     if (function_exists('local_user_signup_validation')) {
         if ($localvalidation = local_user_signup_validation()) {
             $errors = array_merge($errors, $localvalidation);
         }
     }
     return $errors;
 }
 public function __getPassword($username, $email, $old_password, $new_password)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $response = new CliniqueServiceResponce();
     if (!empty($username) && !empty($old_password) && !empty($new_password)) {
         $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0));
         if (!empty($user)) {
             if (is_mnet_remote_user($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - mnet user trying to access.', 0, $user->id);
                 $response->response(true, 'cp_mnet_user');
                 die;
             }
             if (isguestuser($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - guest user credential supplied.', 0, $user->id);
                 $response->response(true, 'cp_guest');
                 die;
             }
             // make sure user is allowed to change password
             require_capability('moodle/user:changeownpassword', $systemcontext, $user->id);
             // $generatePasswordResult = generatePassword::app_validate_internal_user_password($user, $old_password);
             if (!ChangePassword::__app_validate_internal_user_password($user, $old_password)) {
                 $response->response(true, 'cp_wrong_oldpwd');
             } else {
                 $userauth = get_auth_plugin($user->auth);
                 if ($userauth->user_update_password($user, $new_password)) {
                     unset_user_preference('auth_forcepasswordchange', $user);
                     unset_user_preference('create_password', $user);
                     $response->response(false, 'cp_success');
                 } else {
                     add_to_log(-1, 'custom_webservice', 'trigger_mail', null, 'Change password - password change updation failure.', 0, $user->id);
                     $response->response(true, 'cp_failure');
                 }
             }
         } else {
             $response->response(false, 'cp_no_mail_record');
         }
     } else {
         add_to_log(-1, 'custom_webservice', 'input_parameters', null, 'Change password - input parameters missing.', 0, $user->id);
     }
 }
예제 #17
0
파일: UserLogin.php 프로젝트: tmuras/moosh
 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());
 }
 public function __construct()
 {
     global $CFG, $SESSION, $OUTPUT;
     // Get all alternative login methods and add to potentialipds array.
     $authsequence = get_enabled_auth_plugins(true);
     $potentialidps = [];
     foreach ($authsequence as $authname) {
         if (isset($SESSION->snapwantsurl)) {
             $urltogo = $SESSION->snapwantsurl;
         } else {
             $urltogo = $CFG->wwwroot . '/';
         }
         unset($SESSION->snapwantsurl);
         $authplugin = get_auth_plugin($authname);
         $potentialidps = array_merge($potentialidps, $authplugin->loginpage_idp_list($urltogo));
     }
     if (!empty($potentialidps)) {
         foreach ($potentialidps as $idp) {
             $this->potentialidps[] = (object) ['url' => $idp['url']->out(), 'name' => $idp['name'], 'icon' => $OUTPUT->pix_url($idp['icon']->pix)];
         }
     }
 }
예제 #19
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;
}
예제 #20
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     $prefurl = new moodle_url('/user/preferences.php');
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
         $prefurl->param('userid', $userid);
     }
     // Add a user setting branch.
     if ($gstitle == 'usercurrentsettings') {
         $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
         // This should be set to false as we don't want to show this to the user. It's only for generating the correct
         // breadcrumb.
         $dashboard->display = false;
         if (get_home_page() == HOMEPAGE_MY) {
             $dashboard->mainnavonly = true;
         }
         $iscurrentuser = $user->id == $USER->id;
         $baseargs = array('id' => $user->id);
         if ($course->id != $SITE->id && !$iscurrentuser) {
             $baseargs['course'] = $course->id;
             $issitecourse = false;
         } else {
             // Load all categories and get the context for the system.
             $issitecourse = true;
         }
         // Add the user profile to the dashboard.
         $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
         if (!empty($CFG->navadduserpostslinks)) {
             // Add nodes for forum posts and discussions if the user can view either or both
             // There are no capability checks here as the content of the page is based
             // purely on the forums the current user has access too.
             $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
         }
         // Add blog nodes.
         if (!empty($CFG->enableblogs)) {
             if (!$this->cache->cached('userblogoptions' . $user->id)) {
                 require_once $CFG->dirroot . '/blog/lib.php';
                 // Get all options for the user.
                 $options = blog_get_options_for_user($user);
                 $this->cache->set('userblogoptions' . $user->id, $options);
             } else {
                 $options = $this->cache->{'userblogoptions' . $user->id};
             }
             if (count($options) > 0) {
                 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                 foreach ($options as $type => $option) {
                     if ($type == "rss") {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                     } else {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
                     }
                 }
             }
         }
         // Add the messages link.
         // It is context based so can appear in the user's profile and in course participants information.
         if (!empty($CFG->messaging)) {
             $messageargs = array('user1' => $USER->id);
             if ($USER->id != $user->id) {
                 $messageargs['user2'] = $user->id;
             }
             if ($course->id != $SITE->id) {
                 $messageargs['viewing'] = MESSAGE_VIEW_COURSE . $course->id;
             }
             $url = new moodle_url('/message/index.php', $messageargs);
             $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
         }
         // Add the "My private files" link.
         // This link doesn't have a unique display for course context so only display it under the user's profile.
         if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
             $url = new moodle_url('/user/files.php');
             $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
         }
         // Add a node to view the users notes if permitted.
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php', array('user' => $user->id));
             if ($coursecontext->instanceid != SITEID) {
                 $url->param('course', $coursecontext->instanceid);
             }
             $profilenode->add(get_string('notes', 'notes'), $url);
         }
         // Show the grades node.
         if ($issitecourse && $iscurrentuser || has_capability('moodle/user:viewdetails', $usercontext)) {
             require_once $CFG->dirroot . '/user/lib.php';
             // Set the grades node to link to the "Grades" page.
             if ($course->id == SITEID) {
                 $url = user_mygrades_url($user->id, $course->id);
             } else {
                 // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
                 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
             }
             $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
         }
         // Let plugins hook into user navigation.
         $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
         foreach ($pluginsfunction as $plugintype => $plugins) {
             if ($plugintype != 'report') {
                 foreach ($plugins as $pluginfunction) {
                     $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
                 }
             }
         }
         $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $dashboard->add_node($usersetting);
     } else {
         $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $usersetting->display = false;
     }
     $usersetting->id = 'usersettings';
     // Check if the user has been deleted.
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message.
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile.
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
     // Add the profile edit link.
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link.
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
         }
     }
     $pluginmanager = core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('mod');
     if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
         }
     }
     $editors = editors_get_enabled();
     if (count($editors) > 1) {
         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
             if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
                 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
                 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
             }
         }
     }
     // Add "Course preferences" link.
     if (isloggedin() && !isguestuser($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
         }
     }
     // View the roles settings.
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Repositories.
     if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
         require_once $CFG->dirroot . '/repository/lib.php';
         $editabletypes = repository::get_editable_types($usercontext);
         $haseditabletypes = !empty($editabletypes);
         unset($editabletypes);
         $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
     } else {
         $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
     }
     if ($haseditabletypes) {
         $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
         $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
     }
     // Portfolio.
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys.
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging.
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs.
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         if (has_capability('moodle/blog:view', $systemcontext)) {
             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         }
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
         // Remove the blog node if empty.
         $blog->trim_if_empty();
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
             $url = new moodle_url('/badges/mybadges.php');
             $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
         }
         $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Let plugins hook into user settings navigation.
     $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
     foreach ($pluginsfunction as $plugintype => $plugins) {
         foreach ($plugins as $pluginfunction) {
             $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
         }
     }
     return $usersetting;
 }
예제 #21
0
 /**
  * Return XHTML to display control
  *
  * @param mixed $data Unused
  * @param string $query
  * @return string highlight
  */
 public function output_html($data, $query = '')
 {
     global $CFG, $OUTPUT;
     // display strings
     $txt = get_strings(array('authenticationplugins', 'users', 'administration', 'settings', 'edit', 'name', 'enable', 'disable', 'up', 'down', 'none'));
     $txt->updown = "{$txt->up}/{$txt->down}";
     $authsavailable = get_plugin_list('auth');
     get_enabled_auth_plugins(true);
     // fix the list of enabled auths
     if (empty($CFG->auth)) {
         $authsenabled = array();
     } else {
         $authsenabled = explode(',', $CFG->auth);
     }
     // construct the display array, with enabled auth plugins at the top, in order
     $displayauths = array();
     $registrationauths = array();
     $registrationauths[''] = $txt->disable;
     foreach ($authsenabled as $auth) {
         $authplugin = get_auth_plugin($auth);
         /// Get the auth title (from core or own auth lang files)
         $authtitle = $authplugin->get_title();
         /// Apply titles
         $displayauths[$auth] = $authtitle;
         if ($authplugin->can_signup()) {
             $registrationauths[$auth] = $authtitle;
         }
     }
     foreach ($authsavailable as $auth => $dir) {
         if (array_key_exists($auth, $displayauths)) {
             continue;
             //already in the list
         }
         $authplugin = get_auth_plugin($auth);
         /// Get the auth title (from core or own auth lang files)
         $authtitle = $authplugin->get_title();
         /// Apply titles
         $displayauths[$auth] = $authtitle;
         if ($authplugin->can_signup()) {
             $registrationauths[$auth] = $authtitle;
         }
     }
     $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
     $return .= $OUTPUT->box_start('generalbox authsui');
     $table = new html_table();
     $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
     $table->align = array('left', 'center', 'center', 'center');
     $table->data = array();
     $table->attributes['class'] = 'manageauthtable generaltable';
     //add always enabled plugins first
     $displayname = "<span>" . $displayauths['manual'] . "</span>";
     $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
     //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
     $table->data[] = array($displayname, '', '', $settings);
     $displayname = "<span>" . $displayauths['nologin'] . "</span>";
     $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
     $table->data[] = array($displayname, '', '', $settings);
     // iterate through auth plugins and add to the display table
     $updowncount = 1;
     $authcount = count($authsenabled);
     $url = "auth.php?sesskey=" . sesskey();
     foreach ($displayauths as $auth => $name) {
         if ($auth == 'manual' or $auth == 'nologin') {
             continue;
         }
         // hide/show link
         if (in_array($auth, $authsenabled)) {
             $hideshow = "<a href=\"{$url}&amp;action=disable&amp;auth={$auth}\">";
             $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
             // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
             $enabled = true;
             $displayname = "<span>{$name}</span>";
         } else {
             $hideshow = "<a href=\"{$url}&amp;action=enable&amp;auth={$auth}\">";
             $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
             // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
             $enabled = false;
             $displayname = "<span class=\"dimmed_text\">{$name}</span>";
         }
         // up/down link (only if auth is enabled)
         $updown = '';
         if ($enabled) {
             if ($updowncount > 1) {
                 $updown .= "<a href=\"{$url}&amp;action=up&amp;auth={$auth}\">";
                 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
             } else {
                 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
             }
             if ($updowncount < $authcount) {
                 $updown .= "<a href=\"{$url}&amp;action=down&amp;auth={$auth}\">";
                 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
             } else {
                 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
             }
             ++$updowncount;
         }
         // settings link
         if (file_exists($CFG->dirroot . '/auth/' . $auth . '/settings.php')) {
             $settings = "<a href=\"settings.php?section=authsetting{$auth}\">{$txt->settings}</a>";
         } else {
             $settings = "<a href=\"auth_config.php?auth={$auth}\">{$txt->settings}</a>";
         }
         // add a row to the table
         $table->data[] = array($displayname, $hideshow, $updown, $settings);
     }
     $return .= html_writer::table($table);
     $return .= get_string('configauthenticationplugins', 'admin') . '<br />' . get_string('tablenosave', 'filters');
     $return .= $OUTPUT->box_end();
     return highlight($query, $return);
 }
예제 #22
0
    }
    $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) {
        // No need to redirect here.
        unset($SESSION->loginerrormsg);
    } else {
        if ($errormsg or !empty($frm->password)) {
            // We must redirect after every password submission.
            if ($errormsg) {
                $SESSION->loginerrormsg = $errormsg;
예제 #23
0
/**
 * Update a user with a user object (will compare against the ID)
 *
 * @param stdClass $user the user to update
 * @param bool $updatepassword if true, authentication plugin will update password.
 * @param bool $triggerevent set false if user_updated event should not be triggred.
 */
function user_update_user($user, $updatepassword = true, $triggerevent = true)
{
    global $DB;
    // set the timecreate field to the current time
    if (!is_object($user)) {
        $user = (object) $user;
    }
    //check username
    if (isset($user->username)) {
        if ($user->username !== core_text::strtolower($user->username)) {
            throw new moodle_exception('usernamelowercase');
        } else {
            if ($user->username !== clean_param($user->username, PARAM_USERNAME)) {
                throw new moodle_exception('invalidusername');
            }
        }
    }
    // Unset password here, for updating later, if password update is required.
    if ($updatepassword && isset($user->password)) {
        //check password toward the password policy
        if (!check_password_policy($user->password, $errmsg)) {
            throw new moodle_exception($errmsg);
        }
        $passwd = $user->password;
        unset($user->password);
    }
    // Make sure calendartype, if set, is valid.
    if (!empty($user->calendartype)) {
        $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
        // If it doesn't exist, then unset this value, we do not want to update the user's value.
        if (empty($availablecalendartypes[$user->calendartype])) {
            unset($user->calendartype);
        }
    } else {
        // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
        unset($user->calendartype);
    }
    $user->timemodified = time();
    $DB->update_record('user', $user);
    if ($updatepassword) {
        // Get full user record.
        $updateduser = $DB->get_record('user', array('id' => $user->id));
        // if password was set, then update its hash
        if (isset($passwd)) {
            $authplugin = get_auth_plugin($updateduser->auth);
            if ($authplugin->can_change_password()) {
                $authplugin->user_update_password($updateduser, $passwd);
            }
        }
    }
    // Trigger event if required.
    if ($triggerevent) {
        \core\event\user_updated::create_from_userid($user->id)->trigger();
    }
}
예제 #24
0
<?php

// $Id$
require_once "../config.php";
$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
if (empty($CFG->registerauth)) {
    print_error('cannotusepage2');
}
$authplugin = get_auth_plugin($CFG->registerauth);
if (!$authplugin->can_confirm()) {
    print_error('cannotusepage2');
}
if (!empty($data) || !empty($p) && !empty($s)) {
    if (!empty($data)) {
        $dataelements = explode('/', $data);
        $usersecret = $dataelements[0];
        $username = $dataelements[1];
    } else {
        $usersecret = $p;
        $username = $s;
    }
    $confirmed = $authplugin->user_confirm($username, $usersecret);
    if ($confirmed == AUTH_CONFIRM_ALREADY) {
        $user = get_complete_user_data('username', $username);
        print_header(get_string("alreadyconfirmed"), get_string("alreadyconfirmed"), array(), "");
        echo $OUTPUT->box_start('generalbox centerpara boxwidthnormal boxaligncenter');
예제 #25
0
 $emailchangedhtml = '';
 if ($CFG->emailchangeconfirmation) {
     // Users with 'moodle/user:update' can change their email address immediately.
     // Other users require a confirmation email.
     if (isset($usernew->email) and $user->email != $usernew->email && !has_capability('moodle/user:update', $systemcontext)) {
         $a = new stdClass();
         $a->newemail = $usernew->preference_newemail = $usernew->email;
         $usernew->preference_newemailkey = random_string(20);
         $usernew->preference_newemailattemptsleft = 3;
         $a->oldemail = $usernew->email = $user->email;
         $emailchangedhtml = $OUTPUT->box(get_string('auth_changingemailaddress', 'auth', $a), 'generalbox', 'notice');
         $emailchangedhtml .= $OUTPUT->continue_button($returnurl);
         $emailchanged = true;
     }
 }
 $authplugin = get_auth_plugin($user->auth);
 $usernew->timemodified = time();
 // Description editor element may not exist!
 if (isset($usernew->description_editor) && isset($usernew->description_editor['format'])) {
     $usernew = file_postupdate_standard_editor($usernew, 'description', $editoroptions, $personalcontext, 'user', 'profile', 0);
 }
 // Pass a true old $user here.
 if (!$authplugin->user_update($user, $usernew)) {
     // Auth update failed.
     print_error('cannotupdateprofile');
 }
 // Update user with new profile data.
 user_update_user($usernew, false, false);
 // Update preferences.
 useredit_update_user_preference($usernew);
 // Update interests.
예제 #26
0
/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: context_helper::build_all_paths(true);
        mtrace(' Built context paths');
        // Remove expired cache flags
        gc_cache_flags();
        mtrace(' Cleaned cache flags');
        // Cleanup messaging
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace(' Cleaned up read notifications');
        }
        mtrace(' Deleting temporary files...');
        cron_delete_from_temp();
        // Cleanup user password reset records
        // Delete any reset request records which are expired by more than a day.
        // (We keep recently expired requests around so we can give a different error msg to users who
        // are trying to user a recently expired reset attempt).
        $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
        $earliestvalid = time() - $pwresettime - DAYSECS;
        $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
        mtrace(' Cleaned up old password reset records');
        mtrace("...finished clean-up tasks");
    }
    // End of occasional clean-up tasks
    // Send login failures notification - brute force protection in moodle is weak,
    // we should at least send notices early in each cron execution
    if (notify_login_failures()) {
        mtrace(' Notified login failures');
    }
    // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
    context_helper::create_instances();
    mtrace(' Created missing context instances');
    // Session gc.
    mtrace("Running session gc tasks...");
    \core\session\manager::gc();
    mtrace("...finished stale session cleanup");
    // Run the auth cron, if any before enrolments
    // because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    cron_trace_time_and_memory();
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    // Generate new password emails for users - ppl expect these generated asap
    if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
        mtrace('Creating passwords for new users...');
        $usernamefields = get_all_user_name_fields(true, 'u');
        $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n                                                 {$usernamefields}, u.username, u.lang,\n                                                 p.id as prefid\n                                            FROM {user} u\n                                            JOIN {user_preferences} p ON u.id=p.userid\n                                           WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
        // note: we can not send emails to suspended accounts
        foreach ($newusers as $newuser) {
            // Use a low cost factor when generating bcrypt hash otherwise
            // hashing would be slow when emailing lots of users. Hashes
            // will be automatically updated to a higher cost factor the first
            // time the user logs in.
            if (setnew_password_and_mail($newuser, true)) {
                unset_user_preference('create_password', $newuser);
                set_user_preference('auth_forcepasswordchange', 1, $newuser);
            } else {
                trigger_error("Could not create and mail new user password!");
            }
        }
        $newusers->close();
    }
    // It is very important to run enrol early
    // because other plugins depend on correct enrolment info.
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        cron_trace_time_and_memory();
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    // Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    cron_trace_time_and_memory();
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    // Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // We will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    cron_trace_time_and_memory();
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    // Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    mtrace('Starting admin reports');
    cron_execute_plugin_type('report');
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job...');
    cron_trace_time_and_memory();
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    cron_trace_time_and_memory();
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        cron_trace_time_and_memory();
        require_once $CFG->dirroot . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        cron_trace_time_and_memory();
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace('Starting course reports');
    cron_execute_plugin_type('coursereport');
    mtrace('Finished course reports');
    // run gradebook import/export/report cron
    mtrace('Starting gradebook plugins');
    cron_execute_plugin_type('gradeimport');
    cron_execute_plugin_type('gradeexport');
    cron_execute_plugin_type('gradereport');
    mtrace('Finished gradebook plugins');
    // run calendar cron
    require_once "{$CFG->dirroot}/calendar/lib.php";
    calendar_cron();
    // Run external blog cron if needed
    if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        cron_trace_time_and_memory();
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
        mtrace('done.');
    }
    // Run blog associations cleanup
    if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        cron_trace_time_and_memory();
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
        mtrace('done.');
    }
    // Run question bank clean-up.
    mtrace("Starting the question bank cron...", '');
    cron_trace_time_and_memory();
    require_once $CFG->libdir . '/questionlib.php';
    question_bank::cron();
    mtrace('done.');
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    cron_trace_time_and_memory();
    require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // If enabled, fetch information about available updates and eventually notify site admins
    if (empty($CFG->disableupdatenotifications)) {
        $updateschecker = \core\update\checker::instance();
        $updateschecker->cron();
    }
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    cron_trace_time_and_memory();
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // all other plugins
    cron_execute_plugin_type('message', 'message plugins');
    cron_execute_plugin_type('filter', 'filters');
    cron_execute_plugin_type('editor', 'editors');
    cron_execute_plugin_type('format', 'course formats');
    cron_execute_plugin_type('profilefield', 'profile fields');
    cron_execute_plugin_type('webservice', 'webservices');
    cron_execute_plugin_type('repository', 'repository plugins');
    cron_execute_plugin_type('qbehaviour', 'question behaviours');
    cron_execute_plugin_type('qformat', 'question import/export formats');
    cron_execute_plugin_type('qtype', 'question types');
    cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
    cron_execute_plugin_type('theme', 'themes');
    cron_execute_plugin_type('tool', 'admin tools');
    // and finally run any local cronjobs, if any
    if ($locals = core_component::get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        // new cron functions in lib.php first
        cron_execute_plugin_type('local');
        // legacy cron files are executed directly
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace('Running cache cron routines');
    cache_helper::cron();
    mtrace('done.');
    // Run automated backups if required - these may take a long time to execute
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    // Run stats as at the end because they are known to take very long time on large sites
    if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
        require_once $CFG->dirroot . '/lib/statslib.php';
        // check we're not before our runtime
        $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
        if (time() > $timetocheck) {
            // process configured number of days as max (defaulting to 31)
            $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
            if (stats_cron_daily($maxdays)) {
                if (stats_cron_weekly()) {
                    if (stats_cron_monthly()) {
                        stats_clean_old();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // Run badges review cron.
    mtrace("Starting badges cron...");
    require_once $CFG->dirroot . '/badges/cron.php';
    badge_cron();
    mtrace('done.');
    // cleanup file trash - not very important
    $fs = get_file_storage();
    $fs->cron();
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
예제 #27
0
require_once $CFG->dirroot . '/enrol/enrol.class.php';
foreach ($plugins as $p) {
    $enrol = enrolment_factory::factory($p);
    if (method_exists($enrol, 'cron')) {
        $enrol->cron();
    }
    if (!empty($enrol->log)) {
        mtrace($enrol->log);
    }
    unset($enrol);
}
/// Run the auth cron, if any
$auths = get_enabled_auth_plugins();
mtrace("Running auth crons if required...");
foreach ($auths as $auth) {
    $authplugin = get_auth_plugin($auth);
    if (method_exists($authplugin, 'cron')) {
        mtrace("Running cron for auth/{$auth}...");
        $authplugin->cron();
        if (!empty($authplugin->log)) {
            mtrace($authplugin->log);
        }
    }
    unset($authplugin);
}
if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
    // check we're not before our runtime
    $timetocheck = strtotime("today {$CFG->statsruntimestarthour}:{$CFG->statsruntimestartminute}");
    if (time() > $timetocheck) {
        $time = 60 * 60 * 20;
        // set it to 20 here for first run... (overridden by $CFG)
예제 #28
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);
}
예제 #29
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
     // Course context
     $systemcontext = get_system_context();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canviewusercourse && !$canviewuser || !can_access_course($course, $user->id)) {
                 return false;
             }
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
                 // If groups are in use, make sure we can see that group
                 return false;
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
     }
     // Add a user setting branch
     $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
     $usersetting->id = 'usersettings';
     if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
         // Automatically start by making it active
         $usersetting->make_active();
     }
     // Check if the user has been deleted
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     // Add the profile edit link
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link
     if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
     }
     // View the roles settings
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Portfolio
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_instances(true, false)) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', get_system_context())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Repository
     if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
         if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
             require_once $CFG->dirroot . '/repository/lib.php';
             $editabletypes = repository::get_editable_types($usercontext);
             $haseditabletypes = !empty($editabletypes);
             unset($editabletypes);
             $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
         } else {
             $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
         }
         if ($haseditabletypes) {
             $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id));
             $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
         }
     }
     // Messaging
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs
     if ($currentuser && !empty($CFG->bloglevel)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Login as ...
     if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
         $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey()));
         $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
     }
     return $usersetting;
 }
예제 #30
0
        }
    } catch (Exception $e) {
        print_error("An invalid SAML response was received from the Identity Provider. Contact the admin.");
        if ($pluginconfig->saml_debug_mode) {
            print_error($e->getMessage());
        }
        exit;
    }
} else {
    // You shouldn't be able to reach here.
    print_error("Module Setup Error: Review the OneLogin setup instructions for the SAML authentication module, and be sure to change the following one line of code in Moodle's core in 'login/index.php'.<br /><br /><div style=\"text-align:center;\">CHANGE THE FOLLOWING LINE OF CODE (in 'login/index.php')...</div><br /><font style=\"font-size:18px;\"><strong>if (!empty(\$CFG->alternateloginurl)) {</strong></font><br /><br /><div style=\"text-align:center;\">...to...</div><br /><strong><font style=\"font-size:18px;\">if (!empty(\$CFG->alternateloginurl) && !isset(\$_GET['normal'])) { </font></strong> \r\n");
}
// Valid session. Register or update user in Moodle, log him on, and redirect to Moodle front
// we require the plugin to know that we are now doing a saml login in hook puser_login
$SESSION->onelogin_saml_login = TRUE;
$samlplugin = get_auth_plugin('onelogin_saml');
$saml_user = $samlplugin->get_userinfo(null);
// check user name attribute actually passed
if ($saml_user == false) {
    error_log('auth_onelogin_saml: auth failed due to missing username/email saml attribute: ' . $pluginconfig->saml_username_map);
    session_write_close();
    $USER = new object();
    $USER->id = 0;
    require_once '../../config.php';
    print_error('auth_onelogin_saml: auth failed due to missing username/email saml attribute: ' . $pluginconfig->saml_username_map . "<br />" . get_string("auth_onelogin_saml_username_email_error", "auth_onelogin_saml") . "\r\n");
}
if ($_POST['SAMLResponse']) {
    $saml_account_matcher = $pluginconfig->saml_account_matcher;
    if (empty($saml_account_matcher)) {
        $saml_account_matcher = 'username';
    }