/**
  * Sign up a new user ready for confirmation.
  * Password is passed in plaintext.
  *
  * @param object $user new user object
  * @param boolean $notify print notice with link and terminate
  */
 public function user_signup($user, $notify = true)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     $plainpassword = $user->password;
     $user->password = hash_internal_user_password($user->password);
     if (empty($user->calendartype)) {
         $user->calendartype = $CFG->calendartype;
     }
     $user->id = user_create_user($user, false, false);
     user_add_password_history($user->id, $plainpassword);
     // Save any custom profile field information.
     profile_save_data($user);
     // Trigger event.
     \core\event\user_created::create_from_userid($user->id)->trigger();
     if (!send_confirmation_email($user)) {
         print_error('auth_emailnoemail, auth_email');
     }
     if ($notify) {
         global $CFG, $PAGE, $OUTPUT;
         $emailconfirm = get_string('emailconfirm');
         $PAGE->navbar->add($emailconfirm);
         $PAGE->set_title($emailconfirm);
         $PAGE->set_heading($PAGE->course->fullname);
         echo $OUTPUT->header();
         notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
     } else {
         return true;
     }
 }
 /**
  * Test create_users.
  */
 public function test_create_users()
 {
     global $DB;
     $this->resetAfterTest();
     $user = array('username' => 'usernametest1', 'password' => 'Moodle2012!', 'idnumber' => 'idnumbertest1', 'firstname' => 'First Name User Test 1', 'lastname' => 'Last Name User Test 1', 'middlename' => 'Middle Name User Test 1', 'lastnamephonetic' => '最後のお名前のテスト一号', 'firstnamephonetic' => 'お名前のテスト一号', 'alternatename' => 'Alternate Name User Test 1', 'email' => '*****@*****.**', 'description' => 'This is a description for user 1', 'city' => 'Perth', 'country' => 'au');
     // Create user and capture event.
     $sink = $this->redirectEvents();
     $user['id'] = user_create_user($user);
     $events = $sink->get_events();
     $sink->close();
     $event = array_pop($events);
     // Test user info in DB.
     $dbuser = $DB->get_record('user', array('id' => $user['id']));
     $this->assertEquals($dbuser->username, $user['username']);
     $this->assertEquals($dbuser->idnumber, $user['idnumber']);
     $this->assertEquals($dbuser->firstname, $user['firstname']);
     $this->assertEquals($dbuser->lastname, $user['lastname']);
     $this->assertEquals($dbuser->email, $user['email']);
     $this->assertEquals($dbuser->description, $user['description']);
     $this->assertEquals($dbuser->city, $user['city']);
     $this->assertEquals($dbuser->country, $user['country']);
     // Test event.
     $this->assertInstanceOf('\\core\\event\\user_created', $event);
     $this->assertEquals($user['id'], $event->objectid);
     $this->assertEquals('user_created', $event->get_legacy_eventname());
     $this->assertEquals(context_user::instance($user['id']), $event->get_context());
     $this->assertEventLegacyData($dbuser, $event);
     $expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id=' . $event->objectid, fullname($dbuser));
     $this->assertEventLegacyLogData($expectedlogdata, $event);
 }
function create_user($ridnumber, $fname, $sname)
{
    if (!$ridnumber) {
        throw new coding_exception('scantron student idnumber (teex ID) is empty');
    }
    $authtype = 'nologin';
    $from = 'from certification office';
    $user = array('username' => 'escert' . $ridnumber, 'firstname' => $fname, 'lastname' => $sname, 'auth' => $authtype, 'idnumber' => $ridnumber, 'description' => "{$from}");
    $user['id'] = user_create_user($user);
    return $user['id'];
}
Example #4
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/lib.php';
     unset($CFG->passwordpolicy);
     foreach ($this->arguments as $argument) {
         $this->expandOptionsManually(array($argument));
         $options = $this->expandedOptions;
         $user = new \stdClass();
         if ($options['auth']) {
             $user->auth = $options['auth'];
         }
         // new version of GetOptionKit does not allow a blank string as input
         // to -p or --password, so 'magic' value NONE is needed to allow
         // an explicitly blank password be specified, which needs to be
         // possible when specifying an auth type of ldap - Bart Busschots 2 Sep 2013
         $password = $options['password'];
         if ($password == 'NONE') {
             // needed to stop errors when trying to set empty PW
             $password = '';
         }
         $user->password = $password;
         $user->email = $options['email'];
         $maildigest = 0;
         if ($options['digest'] && is_numeric($options['digest']) && $options['digest'] > 0 && $options['digest'] <= 2) {
             $maildigest = $options['digest'];
         }
         $user->maildigest = $maildigest;
         $user->city = $options['city'];
         $user->country = $options['country'];
         $user->firstname = $options['firstname'];
         $user->lastname = $options['lastname'];
         $user->idnumber = $options['idnumber'];
         $user->timecreated = time();
         $user->timemodified = $user->timecreated;
         $user->username = $argument;
         $user->confirmed = 1;
         $user->mnethostid = $CFG->mnet_localhost_id;
         // to prevent errors about insufficiently strong passwords, use a
         // direct DB insert rather than an API call when adding a user
         // with external auth and no password specified
         if ($options['auth'] && $options['auth'] != "manual" && !$password) {
             $newuserid = $DB->insert_record('user', $user);
         } else {
             $newuserid = user_create_user($user);
         }
         echo "{$newuserid}\n";
     }
 }
Example #5
0
 /**
  * Create the fixture
  *
  * This method must be safe to call multiple times.
  *
  * @return void
  * @throws moodle_exception
  */
 public function build()
 {
     global $CFG, $DB;
     if (!$this->exists()) {
         $user = (object) $this->get_options();
         // Clean user table - can happen when unit tests fail...
         if (!empty($user->username) and $record = $DB->get_record('user', array('username' => $user->username))) {
             $this->delete_user($record);
         }
         if (!empty($user->idnumber) and $record = $DB->get_record('user', array('idnumber' => $user->idnumber))) {
             $this->delete_user($record);
         }
         if (!property_exists($user, 'mnethostid')) {
             $user->mnethostid = $CFG->mnet_localhost_id;
         }
         $userid = user_create_user($user);
         $this->set_results($DB->get_record('user', array('id' => $userid), '*', MUST_EXIST));
     }
 }
function application_user_signup($user)
{
    // Derived from email->user_signup
    global $CFG, $PAGE, $OUTPUT;
    $user->password = hash_internal_user_password($user->password);
    if (empty($user->calendartype)) {
        $user->calendartype = $CFG->calendartype;
    }
    $user->id = user_create_user($user, false, false);
    // Save any custom profile field information
    profile_save_data($user);
    // Save contact information
    write_contact_details($user->id, $user);
    // Trigger event
    \core\event\user_created::create_from_userid($user->id)->trigger();
    if (!send_application_confirmation_email($user)) {
        print_error('auth_emailnoemail', 'auth_email');
    }
    $PAGE->set_title($CFG->pageheading . ': ' . get_string('emailconfirm'));
    echo $OUTPUT->header();
    notice(get_string('emailconfirmsent', '', $user->email), $CFG->wwwroot . '/local/obu_application/login.php');
}
Example #7
0
 /**
  * Create one or more users
  *
  * @param array $users An array of users to create.
  * @return array An array of arrays
  * @since Moodle 2.2
  */
 public static function create_users($users)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/lib/weblib.php";
     require_once $CFG->dirroot . "/user/lib.php";
     require_once $CFG->dirroot . "/user/profile/lib.php";
     //required for customfields related function
     // Ensure the current user is allowed to run this function
     $context = context_system::instance();
     self::validate_context($context);
     require_capability('moodle/user:create', $context);
     // Do basic automatic PARAM checks on incoming data, using params description
     // If any problems are found then exceptions are thrown with helpful error messages
     $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
     $availableauths = get_plugin_list('auth');
     unset($availableauths['mnet']);
     // these would need mnethostid too
     unset($availableauths['webservice']);
     // we do not want new webservice users for now
     $availablethemes = get_plugin_list('theme');
     $availablelangs = get_string_manager()->get_list_of_translations();
     $transaction = $DB->start_delegated_transaction();
     $userids = array();
     foreach ($params['users'] as $user) {
         // Make sure that the username doesn't already exist
         if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
             throw new invalid_parameter_exception('Username already exists: ' . $user['username']);
         }
         // Make sure auth is valid
         if (empty($availableauths[$user['auth']])) {
             throw new invalid_parameter_exception('Invalid authentication type: ' . $user['auth']);
         }
         // Make sure lang is valid
         if (empty($availablelangs[$user['lang']])) {
             throw new invalid_parameter_exception('Invalid language code: ' . $user['lang']);
         }
         // Make sure lang is valid
         if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) {
             //theme is VALUE_OPTIONAL,
             // so no default value.
             // We need to test if the client sent it
             // => !empty($user['theme'])
             throw new invalid_parameter_exception('Invalid theme: ' . $user['theme']);
         }
         $user['confirmed'] = true;
         $user['mnethostid'] = $CFG->mnet_localhost_id;
         // Start of user info validation.
         // Lets make sure we validate current user info as handled by current GUI. see user/editadvanced_form.php function validation()
         if (!validate_email($user['email'])) {
             throw new invalid_parameter_exception('Email address is invalid: ' . $user['email']);
         } else {
             if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
                 throw new invalid_parameter_exception('Email address already exists: ' . $user['email']);
             }
         }
         // End of user info validation.
         // create the user data now!
         $user['id'] = user_create_user($user);
         // custom fields
         if (!empty($user['customfields'])) {
             foreach ($user['customfields'] as $customfield) {
                 $user["profile_field_" . $customfield['type']] = $customfield['value'];
                 //profile_save_data() saves profile file
                 //it's expecting a user with the correct id,
                 //and custom field to be named profile_field_"shortname"
             }
             profile_save_data((object) $user);
         }
         //preferences
         if (!empty($user['preferences'])) {
             foreach ($user['preferences'] as $preference) {
                 set_user_preference($preference['type'], $preference['value'], $user['id']);
             }
         }
         $userids[] = array('id' => $user['id'], 'username' => $user['username']);
     }
     $transaction->allow_commit();
     return $userids;
 }
Example #8
0
     $user->lastname = $ltirequest->info['lis_person_name_family'];
 } else {
     $user->lastname = $ltirequest->info['context_id'];
 }
 $user->email = \core_user::clean_field($ltirequest->getUserEmail(), 'email');
 // Get the user data from the LTI consumer.
 $user = \enrol_lti\helper::assign_user_tool_data($tool, $user);
 // Check if the user exists.
 if (!($dbuser = $DB->get_record('user', array('username' => $user->username, 'deleted' => 0)))) {
     // If the email was stripped/not set then fill it with a default one. This
     // stops the user from being redirected to edit their profile page.
     if (empty($user->email)) {
         $user->email = $user->username . "@example.com";
     }
     $user->auth = 'lti';
     $user->id = user_create_user($user);
     // Get the updated user record.
     $user = $DB->get_record('user', array('id' => $user->id));
 } else {
     if (\enrol_lti\helper::user_match($user, $dbuser)) {
         $user = $dbuser;
     } else {
         // If email is empty remove it, so we don't update the user with an empty email.
         if (empty($user->email)) {
             unset($user->email);
         }
         $user->id = $dbuser->id;
         user_update_user($user);
         // Get the updated user record.
         $user = $DB->get_record('user', array('id' => $user->id));
     }
Example #9
0
 /**
  * Synchronizes user from external db to moodle user table.
  *
  * Sync should be done by using idnumber attribute, not username.
  * You need to pass firstsync parameter to function to fill in
  * idnumbers if they don't exists in moodle user table.
  *
  * Syncing users removes (disables) users that don't exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * This implementation is simpler but less scalable than the one found in the LDAP module.
  *
  * @param progress_trace $trace
  * @param bool $do_updates  Optional: set to true to force an update of existing accounts
  * @return int 0 means success, 1 means failure
  */
 function sync_users(progress_trace $trace, $do_updates = false)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/lib.php';
     // List external users.
     $userlist = $this->get_userlist();
     // Delete obsolete internal users.
     if (!empty($this->config->removeuser)) {
         $suspendselect = "";
         if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
             $suspendselect = "AND u.suspended = 0";
         }
         // Find obsolete users.
         if (count($userlist)) {
             list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', false);
             $params['authtype'] = $this->authtype;
             $sql = "SELECT u.*\n                          FROM {user} u\n                         WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid {$suspendselect} AND u.username {$notin_sql}";
         } else {
             $sql = "SELECT u.*\n                          FROM {user} u\n                         WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid {$suspendselect}";
             $params = array();
             $params['authtype'] = $this->authtype;
         }
         $params['mnethostid'] = $CFG->mnet_localhost_id;
         $remove_users = $DB->get_records_sql($sql, $params);
         if (!empty($remove_users)) {
             $trace->output(get_string('auth_dbuserstoremove', 'auth_db', count($remove_users)));
             foreach ($remove_users as $user) {
                 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
                     delete_user($user);
                     $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name' => $user->username, 'id' => $user->id)), 1);
                 } else {
                     if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
                         $updateuser = new stdClass();
                         $updateuser->id = $user->id;
                         $updateuser->suspended = 1;
                         user_update_user($updateuser, false);
                         $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name' => $user->username, 'id' => $user->id)), 1);
                     }
                 }
             }
         }
         unset($remove_users);
     }
     if (!count($userlist)) {
         // Exit right here, nothing else to do.
         $trace->finished();
         return 0;
     }
     // Update existing accounts.
     if ($do_updates) {
         // Narrow down what fields we need to update.
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 if ($this->config->{$key} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // The actual key name.
                 }
             }
         }
         unset($all_keys);
         unset($key);
         // Only go ahead if we actually have fields to update locally.
         if (!empty($updatekeys)) {
             list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', true);
             $params['authtype'] = $this->authtype;
             $sql = "SELECT u.id, u.username\n                          FROM {user} u\n                         WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
             if ($update_users = $DB->get_records_sql($sql, $params)) {
                 $trace->output("User entries to update: " . count($update_users));
                 foreach ($update_users as $user) {
                     if ($this->update_user_record($user->username, $updatekeys)) {
                         $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name' => $user->username, 'id' => $user->id)), 1);
                     } else {
                         $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name' => $user->username, 'id' => $user->id)) . " - " . get_string('skipped'), 1);
                     }
                 }
                 unset($update_users);
             }
         }
     }
     // Create missing accounts.
     // NOTE: this is very memory intensive and generally inefficient.
     $suspendselect = "";
     if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
         $suspendselect = "AND u.suspended = 0";
     }
     $sql = "SELECT u.id, u.username\n                  FROM {user} u\n                 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid {$suspendselect}";
     $users = $DB->get_records_sql($sql, array('authtype' => $this->authtype, 'mnethostid' => $CFG->mnet_localhost_id));
     // Simplify down to usernames.
     $usernames = array();
     if (!empty($users)) {
         foreach ($users as $user) {
             array_push($usernames, $user->username);
         }
         unset($users);
     }
     $add_users = array_diff($userlist, $usernames);
     unset($usernames);
     if (!empty($add_users)) {
         $trace->output(get_string('auth_dbuserstoadd', 'auth_db', count($add_users)));
         // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
         foreach ($add_users as $user) {
             $username = $user;
             if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
                 if ($olduser = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'suspended' => 1, 'mnethostid' => $CFG->mnet_localhost_id, 'auth' => $this->authtype))) {
                     $updateuser = new stdClass();
                     $updateuser->id = $olduser->id;
                     $updateuser->suspended = 0;
                     user_update_user($updateuser);
                     $trace->output(get_string('auth_dbreviveduser', 'auth_db', array('name' => $username, 'id' => $olduser->id)), 1);
                     continue;
                 }
             }
             // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
             // Prep a few params.
             $user = $this->get_userinfo_asobj($user);
             $user->username = $username;
             $user->confirmed = 1;
             $user->auth = $this->authtype;
             $user->mnethostid = $CFG->mnet_localhost_id;
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             if ($collision = $DB->get_record_select('user', "username = :username AND mnethostid = :mnethostid AND auth <> :auth", array('username' => $user->username, 'mnethostid' => $CFG->mnet_localhost_id, 'auth' => $this->authtype), 'id,username,auth')) {
                 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username' => $user->username, 'auth' => $collision->auth)), 1);
                 continue;
             }
             try {
                 $id = user_create_user($user, false);
                 // It is truly a new user.
                 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name' => $user->username, 'id' => $id)), 1);
             } catch (moodle_exception $e) {
                 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
                 continue;
             }
             // If relevant, tag for password generation.
             if ($this->is_internal()) {
                 set_user_preference('auth_forcepasswordchange', 1, $id);
                 set_user_preference('create_password', 1, $id);
             }
             // Make sure user context is present.
             context_user::instance($id);
         }
         unset($add_users);
     }
     $trace->finished();
     return 0;
 }
 /**
  * Creates a test user
  *
  * @param string $username The user's username
  * @param string $email The user's email
  * @param string $idnumber The user's idnumber
  *
  * @return int The database record id of the created user
  */
 private function create_test_user($username = '******', $email = '*****@*****.**', $idnumber = 'rlipidnumber')
 {
     global $CFG;
     require_once $CFG->dirroot . '/user/lib.php';
     $user = new stdClass();
     $user->username = $username;
     $user->mnethostid = $CFG->mnet_localhost_id;
     $user->email = $email;
     $user->password = '******';
     $user->idnumber = $idnumber;
     return user_create_user($user);
 }
Example #11
0
    /**
     * Create one or more users
     *
     * @param array $users  An array of users to create.
     * @return array An array of arrays
     */
    public static function create_users($users) {
        global $CFG, $DB;
        require_once($CFG->dirroot."/user/lib.php");
        require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function
                                                             //TODO: move the functions somewhere else as
                                                             //they are "user" related

        // Ensure the current user is allowed to run this function
        $context = get_context_instance(CONTEXT_SYSTEM);
        self::validate_context($context);
        require_capability('moodle/user:create', $context);

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));

        $availableauths  = get_plugin_list('auth');
        unset($availableauths['mnet']);       // these would need mnethostid too
        unset($availableauths['webservice']); // we do not want new webservice users for now

        $availablethemes = get_plugin_list('theme');
        $availablelangs  = get_string_manager()->get_list_of_translations();

        $transaction = $DB->start_delegated_transaction();

        $userids = array();
        foreach ($params['users'] as $user) {
            // Make sure that the username doesn't already exist
            if ($DB->record_exists('user', array('username'=>$user['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
                throw new invalid_parameter_exception('Username already exists: '.$user['username']);
            }

            // Make sure auth is valid
            if (empty($availableauths[$user['auth']])) {
                throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
            }

            // Make sure lang is valid
            if (empty($availablelangs[$user['lang']])) {
                throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
            }

            // Make sure lang is valid
            if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { //theme is VALUE_OPTIONAL,
                                                                                     // so no default value.
                                                                                     // We need to test if the client sent it
                                                                                     // => !empty($user['theme'])
                throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
            }

            // make sure there is no data loss during truncation
            $truncated = truncate_userinfo($user);
            foreach ($truncated as $key=>$value) {
                    if ($truncated[$key] !== $user[$key]) {
                        throw new invalid_parameter_exception('Property: '.$key.' is too long: '.$user[$key]);
                    }
            }

            $user['confirmed'] = true;
            $user['mnethostid'] = $CFG->mnet_localhost_id;
            $user['id'] = user_create_user($user);

            // custom fields
            if(!empty($user['customfields'])) {
                foreach($user['customfields'] as $customfield) {
                    $user["profile_field_".$customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
                                                                                            //it's expecting a user with the correct id,
                                                                                            //and custom field to be named profile_field_"shortname"
                }
                profile_save_data((object) $user);
            }

            //preferences
            if (!empty($user['preferences'])) {
                foreach($user['preferences'] as $preference) {
                    set_user_preference($preference['type'], $preference['value'],$user['id']);
                }
            }

            $userids[] = array('id'=>$user['id'], 'username'=>$user['username']);
        }

        $transaction->allow_commit();

        return $userids;
    }
Example #12
0
                 $weakpasswords++;
                 $upt->track('password', $strinvalidpasswordpolicy, 'warning');
             }
             $forcechangepassword = true;
         }
         // Use a low cost factor when generating bcrypt hash otherwise
         // hashing would be slow when uploading lots of users. Hashes
         // will be automatically updated to a higher cost factor the first
         // time the user logs in.
         $user->password = hash_internal_user_password($user->password, true);
     }
 } else {
     $user->password = AUTH_PASSWORD_NOT_CACHED;
     $upt->track('password', '-', 'normal', false);
 }
 $user->id = user_create_user($user, false, false);
 $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id' => $user->id)), s($user->username)), 'normal', false);
 // pre-process custom profile menu fields data from csv file
 $user = uu_pre_process_custom_profile_data($user);
 // save custom profile fields data
 profile_save_data($user);
 if ($forcechangepassword) {
     set_user_preference('auth_forcepasswordchange', 1, $user);
 }
 if ($user->password === 'to be generated') {
     set_user_preference('create_password', 1, $user);
 }
 // Trigger event.
 \core\event\user_created::create_from_userid($user->id)->trigger();
 $upt->track('status', $struseradded);
 $upt->track('id', $user->id, 'normal', false);
Example #13
0
 /**
  * Performs the synchronisation of members.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'membersync' => 1))) {
         $ltiplugin = enrol_get_plugin('lti');
         $consumers = array();
         $currentusers = array();
         $userphotos = array();
         foreach ($tools as $tool) {
             mtrace("Starting - Member sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $enrolcount = 0;
             $unenrolcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount++;
                     // Check if we do not have a membershipsurl - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsurl) {
                         mtrace("Skipping - Empty membershipsurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a membershipsid - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsid) {
                         mtrace("Skipping - Empty membershipsid {$mtracecontent}.");
                         continue;
                     }
                     $consumer = sha1($ltiuser->membershipsurl . ':' . $ltiuser->membershipsid . ':' . $ltiuser->consumerkey . ':' . $ltiuser->consumersecret);
                     if (in_array($consumer, $consumers)) {
                         // We have already synchronised with this consumer.
                         continue;
                     }
                     $consumers[] = $consumer;
                     $params = array('lti_message_type' => self::LTI_MESSAGE_TYPE, 'id' => $ltiuser->membershipsid, 'lti_version' => self::LTI_VERSION);
                     mtrace("Calling memberships url '{$ltiuser->membershipsurl}' with body '" . json_encode($params) . "'");
                     try {
                         $response = sendOAuthParamsPOST('POST', $ltiuser->membershipsurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/x-www-form-urlencoded', $params);
                     } catch (\Exception $e) {
                         mtrace("Skipping - No response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace($e->getMessage());
                         continue;
                     }
                     // Check the response from the consumer.
                     $data = new \SimpleXMLElement($response);
                     // Check if we did not receive a valid response.
                     if (empty($data->statusinfo)) {
                         mtrace("Skipping - Bad response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace('Skipping - Error parsing the XML received \'' . substr($response, 0, 125) . '\' ... (Displaying only 125 chars)');
                         continue;
                     }
                     // Check if we did not receive a valid response.
                     if (strpos(strtolower($data->statusinfo->codemajor), 'success') === false) {
                         mtrace('Skipping - Error received from the remote system: ' . $data->statusinfo->codemajor . ' ' . $data->statusinfo->severity . ' ' . $data->statusinfo->codeminor);
                         continue;
                     }
                     $members = $data->memberships->member;
                     mtrace(count($members) . ' members received.');
                     foreach ($members as $member) {
                         // Set the user data.
                         $user = new \stdClass();
                         $user->username = \enrol_lti\helper::create_username($ltiuser->consumerkey, $member->user_id);
                         $user->firstname = \core_user::clean_field($member->person_name_given, 'firstname');
                         $user->lastname = \core_user::clean_field($member->person_name_family, 'lastname');
                         $user->email = \core_user::clean_field($member->person_contact_email_primary, 'email');
                         // Get the user data from the LTI consumer.
                         $user = \enrol_lti\helper::assign_user_tool_data($tool, $user);
                         if (!($dbuser = $DB->get_record('user', array('username' => $user->username, 'deleted' => 0)))) {
                             if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                                 // If the email was stripped/not set then fill it with a default one. This
                                 // stops the user from being redirected to edit their profile page.
                                 if (empty($user->email)) {
                                     $user->email = $user->username . "@example.com";
                                 }
                                 $user->auth = 'lti';
                                 $user->id = user_create_user($user);
                                 // Add the information to the necessary arrays.
                                 $currentusers[] = $user->id;
                                 $userphotos[$user->id] = $member->user_image;
                             }
                         } else {
                             // If email is empty remove it, so we don't update the user with an empty email.
                             if (empty($user->email)) {
                                 unset($user->email);
                             }
                             $user->id = $dbuser->id;
                             user_update_user($user);
                             // Add the information to the necessary arrays.
                             $currentusers[] = $user->id;
                             $userphotos[$user->id] = $member->user_image;
                         }
                         if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                             // Enrol the user in the course.
                             \enrol_lti\helper::enrol_user($tool, $user->id);
                         }
                     }
                 }
                 // Now we check if we have to unenrol users who were not listed.
                 if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_UNENROL_MISSING) {
                     // Go through the users and check if any were never listed, if so, remove them.
                     foreach ($ltiusers as $ltiuser) {
                         if (!in_array($ltiuser->userid, $currentusers)) {
                             $instance = new \stdClass();
                             $instance->id = $tool->enrolid;
                             $instance->courseid = $tool->courseid;
                             $instance->enrol = 'lti';
                             $ltiplugin->unenrol_user($instance, $ltiuser->id);
                         }
                     }
                 }
             }
             mtrace("Completed - Synced members for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; enrolled {$enrolcount} members; unenrolled {$unenrolcount} members.");
             mtrace("");
         }
         // Sync the user profile photos.
         mtrace("Started - Syncing user profile images.");
         $counter = 0;
         if (!empty($userphotos)) {
             foreach ($userphotos as $userid => $url) {
                 if ($url) {
                     $result = \enrol_lti\helper::update_user_profile_image($userid, $url);
                     if ($result === \enrol_lti\helper::PROFILE_IMAGE_UPDATE_SUCCESSFUL) {
                         $counter++;
                         mtrace("Profile image succesfully downloaded and created for user '{$userid}' from {$url}.");
                     } else {
                         mtrace($result);
                     }
                 }
             }
         }
         mtrace("Completed - Synced {$counter} profile images.");
     }
 }
 /**
  * Auto create the moodle user that the robot logs in as
  */
 public function auto_create_bot()
 {
     global $DB, $CFG;
     // TODO roles?
     $botusername = self::get_config()->botusername;
     $botuser = $DB->get_record('user', array('username' => $botusername));
     if ($botuser) {
         return $botuser;
     } else {
         $botuser = (object) array();
         $botuser->username = $botusername;
         $botuser->password = hash_internal_user_password(self::get_config()->botpassword);
         $botuser->firstname = 'Link checker';
         $botuser->lastname = 'Robot';
         $botuser->auth = 'basic';
         $botuser->confirmed = 1;
         $botuser->email = '*****@*****.**';
         $botuser->city = 'Botville';
         $botuser->country = 'AU';
         $botuser->mnethostid = $CFG->mnet_localhost_id;
         $botuser->id = user_create_user($botuser, false, false);
         return $botuser;
     }
 }
Example #15
0
    function moodle_group_delete_groups($client) {
        global $DB, $CFG;

        //create category
        $category = new stdClass();
        $category->name = 'tmpcategoryfortest123';
        $category->id = $DB->insert_record('course_categories', $category);

        //create a course
        $course = new stdClass();
        $course->fullname = 'tmpcoursefortest123';
        $course->shortname = 'tmpcoursefortest123';
        $course->idnumber = 'tmpcoursefortest123';
        $course->category = $category->id;
        $course->id = $DB->insert_record('course', $course);

        //create a role
        $role1->id = create_role('role1thatshouldnotexist', 'role1thatshouldnotexist', '');

        //create a user
        $user = new stdClass();
        $user->username = '******';
        $user->password = '******';
        $user->firstname = 'testfirstname2';
        $user->lastname = 'testlastname2';
        $user->email = '*****@*****.**';
        $user->mnethostid = $CFG->mnet_localhost_id;
        require_once($CFG->dirroot."/user/lib.php");
        $user->id = user_create_user($user);

        //create course context
        $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);

        //enrol the user in the course with the created role
        role_assign($role1->id, $user->id, $context->id);
        $enrol = new stdClass();
        $enrol->courseid = $course->id;
        $enrol->roleid = $role1->id;
        $enrol->id = $DB->insert_record('enrol', $enrol);
        $enrolment = new stdClass();
        $enrolment->userid = $user->id;
        $enrolment->enrolid = $enrol->id;
        $enrolment->id = $DB->insert_record('user_enrolments', $enrolment);

        //create a group in the course
        $group = new stdClass();
        $group->courseid = $course->id;
        $group->name = 'tmpgroufortest123';
        $group->enrolmentkey = '';
        $group->description = '';
        $group->id = $DB->insert_record('groups', $group);
        $group2 = new stdClass();
        $group2->courseid = $course->id;
        $group2->name = 'tmpgroufortest1233';
        $group2->enrolmentkey = '';
        $group2->description = '';
        $group2->id = $DB->insert_record('groups', $group2);
        $paramgroups = array($group, $group2);

        require_once($CFG->dirroot . "/group/lib.php");
        $groups = groups_get_all_groups($course->id);
        $this->assertEqual(2, count($groups));

        //WEBSERVICE CALL -  delete the group
        $function = 'moodle_group_delete_groups';
        $params = array('groupids' => array($group->id, $group2->id));
        $client->call($function, $params);

        $groups = groups_get_all_groups($course->id);
        $this->assertEqual(0, count($groups));

        //unenrol the user
        $DB->delete_records('user_enrolments', array('id' => $enrolment->id));
        $DB->delete_records('enrol', array('id' => $enrol->id));
        role_unassign($role1->id, $user->id, $context->id);

        //delete course context
        delete_context(CONTEXT_COURSE, $course->id);

        //delete the user
        $DB->delete_records('user', array('id' => $user->id));

        //delete the role
        delete_role($role1->id);

        //delete the course
        $DB->delete_records('course', array('id' => $course->id));

        //delete the category
        $DB->delete_records('course_categories', array('id' => $category->id));

    }
Example #16
0
 /**
  * This function confirms the remote (ID provider) host's mnet session
  * by communicating the token and UA over the XMLRPC transport layer, and
  * returns the local user record on success.
  *
  *   @param string    $token           The random session token.
  *   @param mnet_peer $remotepeer   The ID provider mnet_peer object.
  *   @return array The local user record.
  */
 function confirm_mnet_session($token, $remotepeer)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     require_once $CFG->libdir . '/gdlib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     // verify the remote host is configured locally before attempting RPC call
     if (!($remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotepeer->wwwroot, 'deleted' => 0)))) {
         print_error('notpermittedtoland', 'mnet');
     }
     // set up the RPC request
     $mnetrequest = new mnet_xmlrpc_client();
     $mnetrequest->set_method('auth/mnet/auth.php/user_authorise');
     // set $token and $useragent parameters
     $mnetrequest->add_param($token);
     $mnetrequest->add_param(sha1($_SERVER['HTTP_USER_AGENT']));
     // Thunderbirds are go! Do RPC call and store response
     if ($mnetrequest->send($remotepeer) === true) {
         $remoteuser = (object) $mnetrequest->response;
     } else {
         foreach ($mnetrequest->error as $errormessage) {
             list($code, $message) = array_map('trim', explode(':', $errormessage, 2));
             if ($code == 702) {
                 $site = get_site();
                 print_error('mnet_session_prohibited', 'mnet', $remotepeer->wwwroot, format_string($site->fullname));
                 exit;
             }
             $message .= "ERROR {$code}:<br/>{$errormessage}<br/>";
         }
         print_error("rpcerror", '', '', $message);
     }
     unset($mnetrequest);
     if (empty($remoteuser) or empty($remoteuser->username)) {
         print_error('unknownerror', 'mnet');
         exit;
     }
     if (user_not_fully_set_up($remoteuser, false)) {
         print_error('notenoughidpinfo', 'mnet');
         exit;
     }
     $remoteuser = mnet_strip_user($remoteuser, mnet_fields_to_import($remotepeer));
     $remoteuser->auth = 'mnet';
     $remoteuser->wwwroot = $remotepeer->wwwroot;
     // the user may roam from Moodle 1.x where lang has _utf8 suffix
     // also, make sure that the lang is actually installed, otherwise set site default
     if (isset($remoteuser->lang)) {
         $remoteuser->lang = clean_param(str_replace('_utf8', '', $remoteuser->lang), PARAM_LANG);
     }
     if (empty($remoteuser->lang)) {
         if (!empty($CFG->lang)) {
             $remoteuser->lang = $CFG->lang;
         } else {
             $remoteuser->lang = 'en';
         }
     }
     $firsttime = false;
     // get the local record for the remote user
     $localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id));
     // add the remote user to the database if necessary, and if allowed
     // TODO: refactor into a separate function
     if (empty($localuser) || !$localuser->id) {
         /*
         if (empty($this->config->auto_add_remote_users)) {
             print_error('nolocaluser', 'mnet');
         } See MDL-21327   for why this is commented out
         */
         $remoteuser->mnethostid = $remotehost->id;
         $remoteuser->firstaccess = 0;
         $remoteuser->confirmed = 1;
         $remoteuser->id = user_create_user($remoteuser, false);
         $firsttime = true;
         $localuser = $remoteuser;
     }
     // check sso access control list for permission first
     if (!$this->can_login_remotely($localuser->username, $remotehost->id)) {
         print_error('sso_mnet_login_refused', 'mnet', '', array('user' => $localuser->username, 'host' => $remotehost->name));
     }
     $fs = get_file_storage();
     // update the local user record with remote user data
     foreach ((array) $remoteuser as $key => $val) {
         if ($key == '_mnet_userpicture_timemodified' and empty($CFG->disableuserimages) and isset($remoteuser->picture)) {
             // update the user picture if there is a newer verion at the identity provider
             $usercontext = context_user::instance($localuser->id, MUST_EXIST);
             if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.png')) {
                 $localtimemodified = $usericonfile->get_timemodified();
             } else {
                 if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.jpg')) {
                     $localtimemodified = $usericonfile->get_timemodified();
                 } else {
                     $localtimemodified = 0;
                 }
             }
             if (!empty($val) and $localtimemodified < $val) {
                 mnet_debug('refetching the user picture from the identity provider host');
                 $fetchrequest = new mnet_xmlrpc_client();
                 $fetchrequest->set_method('auth/mnet/auth.php/fetch_user_image');
                 $fetchrequest->add_param($localuser->username);
                 if ($fetchrequest->send($remotepeer) === true) {
                     if (strlen($fetchrequest->response['f1']) > 0) {
                         $imagefilename = $CFG->tempdir . '/mnet-usericon-' . $localuser->id;
                         $imagecontents = base64_decode($fetchrequest->response['f1']);
                         file_put_contents($imagefilename, $imagecontents);
                         if ($newrev = process_new_icon($usercontext, 'user', 'icon', 0, $imagefilename)) {
                             $localuser->picture = $newrev;
                         }
                         unlink($imagefilename);
                     }
                     // note that since Moodle 2.0 we ignore $fetchrequest->response['f2']
                     // the mimetype information provided is ignored and the type of the file is detected
                     // by process_new_icon()
                 }
             }
         }
         if ($key == 'myhosts') {
             $localuser->mnet_foreign_host_array = array();
             foreach ($val as $rhost) {
                 $name = clean_param($rhost['name'], PARAM_ALPHANUM);
                 $url = clean_param($rhost['url'], PARAM_URL);
                 $count = clean_param($rhost['count'], PARAM_INT);
                 $url_is_local = stristr($url, $CFG->wwwroot);
                 if (!empty($name) && !empty($count) && empty($url_is_local)) {
                     $localuser->mnet_foreign_host_array[] = array('name' => $name, 'url' => $url, 'count' => $count);
                 }
             }
         }
         $localuser->{$key} = $val;
     }
     $localuser->mnethostid = $remotepeer->id;
     user_update_user($localuser, false);
     if (!$firsttime) {
         // repeat customer! let the IDP know about enrolments
         // we have for this user.
         // set up the RPC request
         $mnetrequest = new mnet_xmlrpc_client();
         $mnetrequest->set_method('auth/mnet/auth.php/update_enrolments');
         // pass username and an assoc array of "my courses"
         // with info so that the IDP can maintain mnetservice_enrol_enrolments
         $mnetrequest->add_param($remoteuser->username);
         $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary, startdate, visible';
         $courses = enrol_get_users_courses($localuser->id, false, $fields, 'visible DESC,sortorder ASC');
         if (is_array($courses) && !empty($courses)) {
             // Second request to do the JOINs that we'd have done
             // inside enrol_get_users_courses() if we had been allowed
             $sql = "SELECT c.id,\n                               cc.name AS cat_name, cc.description AS cat_description\n                          FROM {course} c\n                          JOIN {course_categories} cc ON c.category = cc.id\n                         WHERE c.id IN (" . join(',', array_keys($courses)) . ')';
             $extra = $DB->get_records_sql($sql);
             $keys = array_keys($courses);
             $studentroles = get_archetype_roles('student');
             if (!empty($studentroles)) {
                 $defaultrole = reset($studentroles);
                 //$defaultrole = get_default_course_role($ccache[$shortname]); //TODO: rewrite this completely, there is no default course role any more!!!
                 foreach ($keys as $id) {
                     if ($courses[$id]->visible == 0) {
                         unset($courses[$id]);
                         continue;
                     }
                     $courses[$id]->cat_id = $courses[$id]->category;
                     $courses[$id]->defaultroleid = $defaultrole->id;
                     unset($courses[$id]->category);
                     unset($courses[$id]->visible);
                     $courses[$id]->cat_name = $extra[$id]->cat_name;
                     $courses[$id]->cat_description = $extra[$id]->cat_description;
                     $courses[$id]->defaultrolename = $defaultrole->name;
                     // coerce to array
                     $courses[$id] = (array) $courses[$id];
                 }
             } else {
                 throw new moodle_exception('unknownrole', 'error', '', 'student');
             }
         } else {
             // if the array is empty, send it anyway
             // we may be clearing out stale entries
             $courses = array();
         }
         $mnetrequest->add_param($courses);
         // Call 0800-RPC Now! -- we don't care too much if it fails
         // as it's just informational.
         if ($mnetrequest->send($remotepeer) === false) {
             // error_log(print_r($mnetrequest->error,1));
         }
     }
     return $localuser;
 }
 /**
  * Sign up a new user ready for confirmation.
  * Password is passed in plaintext.
  *
  * @param object $user new user object
  * @param boolean $notify print notice with link and terminate
  */
 function user_signup($user, $notify = true)
 {
     global $CFG, $DB, $SESSION;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     if (isset($SESSION->wantsurl)) {
         $wantsurl = $SESSION->wantsurl;
     }
     $plainpassword = $user->password;
     $user->password = hash_internal_user_password($user->password);
     if (empty($user->calendartype)) {
         $user->calendartype = $CFG->calendartype;
     }
     $user->confirmed = 1;
     $user->id = user_create_user($user, false, false);
     user_add_password_history($user->id, $plainpassword);
     // Save any custom profile field information.
     profile_save_data($user);
     // Trigger event.
     \core\event\user_created::create_from_userid($user->id)->trigger();
     $thisuser = authenticate_user_login($user->username, $plainpassword, false, $errorcode);
     if ($thisuser == false) {
         print_error('authfailure');
     } else {
         complete_user_login($thisuser);
         if (isset($wantsurl)) {
             $urltogo = $wantsurl;
             if (isset($_SESSION["fiaction"]) && isset($_SESSION["ficourseid"]) && is_numeric($_SESSION["ficourseid"]) && $_SESSION["fiaction"] == "enroll") {
                 $urltogo = $CFG->wwwroot . '/course/enrol.php?id=' . $_SESSION["ficourseid"];
                 unset($_SESSION['fiaction']);
                 unset($_SESSION['ficourseid']);
                 unset($SESSION->wantsurl);
             }
         } else {
             $urltogo = $CFG->wwwroot . '/';
         }
         redirect($urltogo);
     }
     // if ($notify) {
     //     global $CFG, $PAGE, $OUTPUT;
     //     $emailconfirm = get_string('emailconfirm');
     //     $PAGE->navbar->add($emailconfirm);
     //     $PAGE->set_title($emailconfirm);
     //     $PAGE->set_heading($PAGE->course->fullname);
     //     echo $OUTPUT->header();
     //     notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
     // } else {
     //     return true;
     // }
 }
 /**
  * Proceed with the import of the user.
  *
  * @return void
  */
 public function proceed()
 {
     if (!$this->prepared) {
         throw new coding_exception('The course has not been prepared.');
     } else {
         if ($this->has_errors()) {
             throw new moodle_exception('Cannot proceed, errors were detected.');
         } else {
             if ($this->processstarted) {
                 throw new coding_exception('The process has already been started.');
             }
         }
     }
     $this->processstarted = true;
     if ($this->do === self::DO_DELETE) {
         $this->finaldata = $this->existing;
         try {
             $success = delete_user($this->existing);
         } catch (moodle_exception $e) {
             $success = false;
         }
         if (!$success) {
             $this->error('usernotdeletederror', new lang_string('usernotdeletederror', 'tool_uploadusercli'));
             return false;
         }
         $this->set_status('userdeleted', new lang_string('userdeleted', 'tool_uploaduser'));
         return true;
     } else {
         if ($this->do === self::DO_CREATE) {
             try {
                 $this->finaldata->id = user_create_user($this->finaldata, false, false);
             } catch (Exception $e) {
                 $this->error('errorcreatinguser', new lang_string('errorcreatinguser', 'tool_uploadusercli'));
                 return false;
             }
             if ($this->needpasswordchange) {
                 set_user_preference('auth_forcepasswordchange', 1, $this->finaldata);
                 $this->set_status('forcepasswordchange', new lang_string('forcepasswordchange', 'tool_uploadusercli'));
             }
             if ($this->finaldata->password === 'to be generated') {
                 set_user_preference('create_password', 1, $this->finaldata);
             }
             $this->set_status('useradded', new lang_string('newuser'));
         } else {
             if ($this->do === self::DO_UPDATE) {
                 try {
                     user_update_user($this->finaldata, false, false);
                 } catch (Exception $e) {
                     $this->error('usernotupdatederror', new lang_string('usernotupdatederror', 'error'));
                     return false;
                 }
                 if ($this->dologout) {
                     \core\session\manager::kill_user_sessions($this->finaldata->id);
                 }
                 $this->set_status('useraccountupdated', new lang_string('useraccountupdated', 'tool_uploaduser'));
             }
         }
     }
     if ($this->do === self::DO_UPDATE || $this->do === self::DO_CREATE) {
         if (!$this->isremote) {
             $this->finaldata = uu_pre_process_custom_profile_data($this->finaldata);
             profile_save_data($this->finaldata);
         }
         $success = $this->add_to_cohort();
         $success = $success && $this->add_to_egr();
         if (!$success) {
             return false;
         }
     }
     return true;
 }
Example #19
0
 /**
  * Validate that My Moodle redirection works when it's supposed to
  */
 public function test_myoodleredirectreturnstruewhensettingenabled()
 {
     global $CFG, $USER, $DB;
     require_once $CFG->dirroot . '/user/lib.php';
     // Set up our test user.
     $user = new stdClass();
     $user->username = "******";
     $userid = user_create_user($user);
     $USER = $DB->get_record('user', array('id' => $userid));
     // Enable functionality.
     pm_set_config('mymoodle_redirect', 1);
     elis::$config = new elis_config();
     // Validation.
     $result = pm_mymoodle_redirect();
     $this->assertTrue($result);
 }
Example #20
0
 /**
  * Creates a user using company user defaults and attaches it to a company
  * User will be emailed a password when the cron job has run
  * @param object $data
  * @return userid
  */
 public static function create($data)
 {
     global $DB, $CFG, $USER;
     if ($data->companyid) {
         $company = new company($data->companyid);
         $c = $company->get('shortname');
         $data->company = $c->shortname;
     } else {
         $company = company::by_shortname($data->company);
     }
     $defaults = $company->get_user_defaults();
     $user = (object) array_merge((array) $defaults, (array) $data);
     //$user->username = self::generate_username( $user->email );    //GWL : Remove Generate Usernaame From Email for Phone No.
     //$user->username = clean_param($user->username, PARAM_USERNAME);   //GWL : Remove Generate Usernaame From Email for Phone No.
     /* GWL : Get Usernamme as phone no. */
     $user->username = $user->phone;
     /* GWL : Get Usernamme as phone no. */
     // Deal with the company theme.
     $user->theme = $company->get_theme();
     if ($user->sendnewpasswordemails && !$user->preference_auth_forcepasswordchange) {
         throw new Exception(get_string('cannotemailnontemporarypasswords', 'local_iomad'));
     }
     /*
      There are 8 possible combinations of password, sendbyemail and forcepasswordchange
      fields:
     
      pwd     email yes   force change            -> temporary password
      pwd     email no    force change            -> temporary password
      pwd     email no    dont force change       -> not a temporary password
     
      no pwd  email yes   force change            -> create password -> store temp
      no pwd  email no    force change            -> create password -> store temp
      no pwd  email no    dont force change       -> create password -> store temp
     
      These two combinations shouldn't happen (caught by form validation and exception above):
      pwd    email yes dont force change->needs to be stored as temp password -> not secure
      no pwd email yes dont force change->create password->store temp->not secure
     
      The next set of variables ($sendemail, $passwordentered, $createpassword,
      $forcepasswordchange, $storetemppassword) are used to distinguish between
      the first 6 combinations and to take appropriate action.
     */
     $sendemail = $user->sendnewpasswordemails;
     $passwordentered = !empty($user->newpassword);
     $createpassword = !$passwordentered;
     $forcepasswordchange = $user->preference_auth_forcepasswordchange;
     // Store temp password unless password was entered and it's not going to be send by
     // email nor is it going to be forced to change.
     $storetemppassword = !($passwordentered && !$sendemail && !$forcepasswordchange);
     if ($passwordentered) {
         $user->password = $user->newpassword;
         // Don't hash it, user_create_user will do that.
     }
     $user->confirmed = 1;
     $user->mnethostid = 1;
     $user->maildisplay = 0;
     // Hide email addresses by default.
     // Create user record and return id.
     $id = user_create_user($user);
     $user->id = $id;
     // Passwords will be created and sent out on cron.
     if ($createpassword) {
         set_user_preference('create_password', 1, $user->id);
         $user->newpassword = generate_password();
         if (!empty($CFG->iomad_email_senderisreal)) {
             EmailTemplate::send('user_create', array('user' => $user, 'sender' => $USER));
         } else {
             EmailTemplate::send('user_create', array('user' => $user, 'headers' => serialize(array("To:" . $user->email . ", " . $USER->email))));
         }
         $sendemail = false;
     }
     if ($forcepasswordchange) {
         set_user_preference('auth_forcepasswordchange', 1, $user->id);
     }
     if ($createpassword) {
         $DB->set_field('user', 'password', hash_internal_user_password($user->newpassword), array('id' => $user->id));
     }
     if ($storetemppassword) {
         // Store password as temporary password, sendemail if necessary.
         self::store_temporary_password($user, $sendemail, $user->newpassword);
     }
     // Attach user to company.
     // Do we have a department?
     if (empty($data->departmentid)) {
         $departmentinfo = $DB->get_record('department', array('company' => $company->id, 'parent' => 0));
         $data->departmentid = $departmentinfo->id;
     }
     // Deal with unset variable.
     if (empty($data->managertype)) {
         $data->managertype = 0;
     }
     // Create the user association.
     $DB->insert_record('company_users', array('userid' => $user->id, 'companyid' => $company->id, 'managertype' => $data->managertype, 'departmentid' => $data->departmentid));
     if (isset($data->selectedcourses)) {
         self::enrol($user, array_keys($data->selectedcourses));
     }
     return $user->id;
 }
Example #21
0
 /**
  * Create a Moodle user from Azure AD user data.
  *
  * @param array $aaddata Array of Azure AD user data.
  * @return \stdClass An object representing the created Moodle user.
  */
 public function create_user_from_aaddata($aaddata)
 {
     global $CFG;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     $newuser = (object) ['auth' => 'oidc', 'username' => trim(\core_text::strtolower($aaddata['userPrincipalName'])), 'email' => isset($aaddata['mail']) ? $aaddata['mail'] : '', 'firstname' => isset($aaddata['givenName']) ? $aaddata['givenName'] : '', 'lastname' => isset($aaddata['surname']) ? $aaddata['surname'] : '', 'city' => isset($aaddata['city']) ? $aaddata['city'] : '', 'country' => isset($aaddata['country']) ? $aaddata['country'] : '', 'department' => isset($aaddata['department']) ? $aaddata['department'] : '', 'lang' => isset($aaddata['preferredLanguage']) ? substr($aaddata['preferredLanguage'], 0, 2) : 'en', 'confirmed' => 1, 'timecreated' => time(), 'mnethostid' => $CFG->mnet_localhost_id];
     $password = null;
     $newuser->idnumber = $newuser->username;
     if (!empty($newuser->email)) {
         if (email_is_not_allowed($newuser->email)) {
             unset($newuser->email);
         }
     }
     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
         $newuser->lang = $CFG->lang;
     }
     $newuser->timemodified = $newuser->timecreated;
     $newuser->id = user_create_user($newuser, false, false);
     // Save user profile data.
     profile_save_data($newuser);
     $user = get_complete_user_data('id', $newuser->id);
     if (!empty($CFG->{'auth_' . $newuser->auth . '_forcechangepassword'})) {
         set_user_preference('auth_forcepasswordchange', 1, $user);
     }
     // Set the password.
     update_internal_user_password($user, $password);
     // Trigger event.
     \core\event\user_created::create_from_userid($newuser->id)->trigger();
     return $user;
 }
Example #22
0
     unset($usernew->createpassword);
     $usernew = file_postupdate_standard_editor($usernew, 'description', $editoroptions, null, 'user', 'profile', null);
     $usernew->mnethostid = $CFG->mnet_localhost_id;
     // Always local user.
     $usernew->confirmed = 1;
     $usernew->timecreated = time();
     if ($authplugin->is_internal()) {
         if ($createpassword or empty($usernew->newpassword)) {
             $usernew->password = '';
         } else {
             $usernew->password = hash_internal_user_password($usernew->newpassword);
         }
     } else {
         $usernew->password = AUTH_PASSWORD_NOT_CACHED;
     }
     $usernew->id = user_create_user($usernew, false, false);
     if (!$authplugin->is_internal() and $authplugin->can_change_password() and !empty($usernew->newpassword)) {
         if (!$authplugin->user_update_password($usernew, $usernew->newpassword)) {
             // Do not stop here, we need to finish user creation.
             debugging(get_string('cannotupdatepasswordonextauth', '', '', $usernew->auth), DEBUG_NONE);
         }
     }
     $usercreated = true;
 } else {
     $usernew = file_postupdate_standard_editor($usernew, 'description', $editoroptions, $usercontext, 'user', 'profile', 0);
     // Pass a true old $user here.
     if (!$authplugin->user_update($user, $usernew)) {
         // Auth update failed.
         print_error('cannotupdateuseronexauth', '', '', $user->auth);
     }
     user_update_user($usernew, false, false);
Example #23
0
 /**
  * Syncronizes user fron external LDAP server to moodle user table
  *
  * Sync is now using username attribute.
  *
  * Syncing users removes or suspends users that dont exists anymore in external LDAP.
  * Creates new users and updates coursecreator status of users.
  *
  * @param bool $do_updates will do pull in data updates from LDAP if relevant
  */
 function sync_users($do_updates = true)
 {
     global $CFG, $DB;
     print_string('connectingldap', 'auth_ldap');
     $ldapconnection = $this->ldap_connect();
     $dbman = $DB->get_manager();
     /// Define table user to be created
     $table = new xmldb_table('tmp_extuser');
     $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
     $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
     $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
     $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
     $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
     print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
     $dbman->create_temp_table($table);
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*)' . $this->config->objectclass . ')';
     $contexts = explode(';', $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
     $ldap_cookie = '';
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         do {
             if ($ldap_pagedresults) {
                 ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
             }
             if ($this->config->search_sub) {
                 // Use ldap_search to find first user from subtree.
                 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
             } else {
                 // Search only in this context.
                 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
             }
             if (!$ldap_result) {
                 continue;
             }
             if ($ldap_pagedresults) {
                 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
             }
             if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
                 do {
                     $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                     $value = core_text::convert($value[0], $this->config->ldapencoding, 'utf-8');
                     $value = trim($value);
                     $this->ldap_bulk_insert($value);
                 } while ($entry = ldap_next_entry($ldapconnection, $entry));
             }
             unset($ldap_result);
             // Free mem.
         } while ($ldap_pagedresults && $ldap_cookie !== null && $ldap_cookie != '');
     }
     // If LDAP paged results were used, the current connection must be completely
     // closed and a new one created, to work without paged results from here on.
     if ($ldap_pagedresults) {
         $this->ldap_close(true);
         $ldapconnection = $this->ldap_connect();
     }
     /// preserve our user database
     /// if the temp table is empty, it probably means that something went wrong, exit
     /// so as to avoid mass deletion of users; which is hard to undo
     $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
     if ($count < 1) {
         print_string('didntgetusersfromldap', 'auth_ldap');
         exit;
     } else {
         print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
     }
     /// User removal
     // Find users in DB that aren't in ldap -- to be removed!
     // this is still not as scalable (but how often do we mass delete?)
     if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
         $sql = "SELECT u.*\n                      FROM {user} u\n                 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE u.auth = :auth\n                           AND u.deleted = 0\n                           AND e.username IS NULL";
         $remove_users = $DB->get_records_sql($sql, array('auth' => $this->authtype));
         if (!empty($remove_users)) {
             print_string('userentriestoremove', 'auth_ldap', count($remove_users));
             foreach ($remove_users as $user) {
                 if (delete_user($user)) {
                     echo "\t";
                     print_string('auth_dbdeleteuser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                     echo "\n";
                 } else {
                     echo "\t";
                     print_string('auth_dbdeleteusererror', 'auth_db', $user->username);
                     echo "\n";
                 }
             }
         } else {
             print_string('nouserentriestoremove', 'auth_ldap');
         }
         unset($remove_users);
         // Free mem!
     } else {
         if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
             $sql = "SELECT u.*\n                      FROM {user} u\n                 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE u.auth = :auth\n                           AND u.deleted = 0\n                           AND u.suspended = 0\n                           AND e.username IS NULL";
             $remove_users = $DB->get_records_sql($sql, array('auth' => $this->authtype));
             if (!empty($remove_users)) {
                 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
                 foreach ($remove_users as $user) {
                     $updateuser = new stdClass();
                     $updateuser->id = $user->id;
                     $updateuser->suspended = 1;
                     user_update_user($updateuser, false);
                     echo "\t";
                     print_string('auth_dbsuspenduser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                     echo "\n";
                     \core\session\manager::kill_user_sessions($user->id);
                 }
             } else {
                 print_string('nouserentriestoremove', 'auth_ldap');
             }
             unset($remove_users);
             // Free mem!
         }
     }
     /// Revive suspended users
     if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
         $sql = "SELECT u.id, u.username\n                      FROM {user} u\n                      JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE (u.auth = 'nologin' OR (u.auth = ? AND u.suspended = 1)) AND u.deleted = 0";
         // Note: 'nologin' is there for backwards compatibility.
         $revive_users = $DB->get_records_sql($sql, array($this->authtype));
         if (!empty($revive_users)) {
             print_string('userentriestorevive', 'auth_ldap', count($revive_users));
             foreach ($revive_users as $user) {
                 $updateuser = new stdClass();
                 $updateuser->id = $user->id;
                 $updateuser->auth = $this->authtype;
                 $updateuser->suspended = 0;
                 user_update_user($updateuser, false);
                 echo "\t";
                 print_string('auth_dbreviveduser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                 echo "\n";
             }
         } else {
             print_string('nouserentriestorevive', 'auth_ldap');
         }
         unset($revive_users);
     }
     /// User Updates - time-consuming (optional)
     if ($do_updates) {
         // Narrow down what fields we need to update
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 // If we have a field to update it from
                 // and it must be updated 'onlogin' we
                 // update it on cron
                 if (!empty($this->config->{'field_map_' . $match[1]}) and $this->config->{$match[0]} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         unset($all_keys);
         unset($key);
     } else {
         print_string('noupdatestobedone', 'auth_ldap');
     }
     if ($do_updates and !empty($updatekeys)) {
         // run updates only if relevant
         $users = $DB->get_records_sql('SELECT u.username, u.id
                                          FROM {user} u
                                         WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?', array($this->authtype, $CFG->mnet_localhost_id));
         if (!empty($users)) {
             print_string('userentriestoupdate', 'auth_ldap', count($users));
             $sitecontext = context_system::instance();
             if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_archetype_roles('coursecreator')) {
                 $creatorrole = array_shift($roles);
                 // We can only use one, let's use the first one
             } else {
                 $creatorrole = false;
             }
             $transaction = $DB->start_delegated_transaction();
             $xcount = 0;
             $maxxcount = 100;
             foreach ($users as $user) {
                 echo "\t";
                 print_string('auth_dbupdatinguser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                 if (!$this->update_user_record($user->username, $updatekeys, true)) {
                     echo ' - ' . get_string('skipped');
                 }
                 echo "\n";
                 $xcount++;
                 // Update course creators if needed
                 if ($creatorrole !== false) {
                     if ($this->iscreator($user->username)) {
                         role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
                     } else {
                         role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
                     }
                 }
             }
             $transaction->allow_commit();
             unset($users);
             // free mem
         }
     } else {
         // end do updates
         print_string('noupdatestobedone', 'auth_ldap');
     }
     /// User Additions
     // Find users missing in DB that are in LDAP
     // and gives me a nifty object I don't want.
     // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
     $sql = 'SELECT e.id, e.username
               FROM {tmp_extuser} e
               LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
              WHERE u.id IS NULL';
     $add_users = $DB->get_records_sql($sql);
     if (!empty($add_users)) {
         print_string('userentriestoadd', 'auth_ldap', count($add_users));
         $sitecontext = context_system::instance();
         if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_archetype_roles('coursecreator')) {
             $creatorrole = array_shift($roles);
             // We can only use one, let's use the first one
         } else {
             $creatorrole = false;
         }
         $transaction = $DB->start_delegated_transaction();
         foreach ($add_users as $user) {
             $user = $this->get_userinfo_asobj($user->username);
             // Prep a few params
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = $this->authtype;
             $user->mnethostid = $CFG->mnet_localhost_id;
             // get_userinfo_asobj() might have replaced $user->username with the value
             // from the LDAP server (which can be mixed-case). Make sure it's lowercase
             $user->username = trim(core_text::strtolower($user->username));
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             if (empty($user->calendartype)) {
                 $user->calendartype = $CFG->calendartype;
             }
             $id = user_create_user($user, false);
             echo "\t";
             print_string('auth_dbinsertuser', 'auth_db', array('name' => $user->username, 'id' => $id));
             echo "\n";
             $euser = $DB->get_record('user', array('id' => $id));
             if (!empty($this->config->forcechangepassword)) {
                 set_user_preference('auth_forcepasswordchange', 1, $id);
             }
             // Add course creators if needed
             if ($creatorrole !== false and $this->iscreator($user->username)) {
                 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
             }
         }
         $transaction->allow_commit();
         unset($add_users);
         // free mem
     } else {
         print_string('nouserstobeadded', 'auth_ldap');
     }
     $dbman->drop_table($table);
     $this->ldap_close();
     return true;
 }
/**
 * Create one or more users
 *
 * @param array $users  An array of users to create.
 * @return array An array of arrays
 */
function create_users($users)
{
    global $CFG, $DB;
    require_once $CFG->dirroot . "/user/lib.php";
    require_once $CFG->dirroot . "/user/profile/lib.php";
    //required for customfields related function
    //TODO: move the functions somewhere else as
    //they are "user" related
    $availableauths = get_plugin_list('auth');
    $availablethemes = get_plugin_list('theme');
    $availablelangs = get_string_manager()->get_list_of_translations();
    $transaction = $DB->start_delegated_transaction();
    $userids = array();
    foreach ($users as $user) {
        // Make sure that the username doesn't already exist
        if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
            //            $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error'=>'Username already exists: ' . $user['username']);
            $user_rec = $DB->get_record('user', array('username' => $user['username']));
            $user['id'] = $user_rec->id;
            unset($user['password']);
            unset($user['auth']);
            user_update_user($user);
            $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => 'Updated');
            continue;
        }
        // Make sure auth is valid
        if (empty($availableauths[$user['auth']])) {
            $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => 'Invalid authentication type: ' . $user['auth']);
            continue;
        }
        // Make sure lang is valid
        if (empty($availablelangs[$user['lang']])) {
            $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => 'Invalid language code: ' . $user['lang']);
            continue;
        }
        // Make sure lang is valid
        if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) {
            //theme is VALUE_OPTIONAL,
            // so no default value.
            // We need to test if the client sent it
            // => !empty($user['theme'])
            $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => 'Invalid theme: ' . $user['theme']);
            continue;
        }
        // make sure there is no data loss during truncation
        $truncated = truncate_userinfo($user);
        foreach ($truncated as $key => $value) {
            if ($truncated[$key] !== $user[$key]) {
                $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => 'Property: ' . $key . ' is too long: ' . $user[$key]);
                continue;
            }
        }
        $user['confirmed'] = true;
        $user['mnethostid'] = $CFG->mnet_localhost_id;
        $user['id'] = user_create_user($user);
        //        // custom fields
        //        if (!empty($user['customfields'])) {
        //            foreach ($user['customfields'] as $customfield) {
        //                $user["profile_field_" . $customfield['type']] = $customfield['value']; //profile_save_data() saves profile file
        //                //it's expecting a user with the correct id,
        //                //and custom field to be named profile_field_"shortname"
        //            }
        //            profile_save_data((object)$user);
        //        }
        //
        //        //preferences
        //        if (!empty($user['preferences'])) {
        //            foreach ($user['preferences'] as $preference) {
        //                set_user_preference($preference['type'], $preference['value'], $user['id']);
        //            }
        //        }
        $userids[] = array('id' => $user['id'], 'username' => $user['username'], 'error' => "");
    }
    $transaction->allow_commit();
    return $userids;
}
Example #25
0
 /**
  * Validate that scheduled jobs are retrieved via API call
  */
 public function test_getscheduledjobs()
 {
     global $CFG, $DB;
     // Create a user.
     require_once $CFG->dirroot . '/user/lib.php';
     $user = new stdClass();
     $user->username = '******';
     $user->firstname = 'rlipfirstname';
     $user->lastname = 'rliplastname';
     $user->mnethostid = $CFG->mnet_localhost_id;
     $user->email = '*****@*****.**';
     $user->password = '******';
     $user->timezone = -5.0;
     $userid = user_create_user($user);
     // Create a scheduled job.
     $data = array('plugin' => 'dhexport_version1', 'period' => '5m', 'label' => 'bogus', 'type' => 'dhexport', 'userid' => $userid);
     $starttime = time();
     $ipid = rlip_schedule_add_job($data);
     $endtime = time();
     // Fetch jobs.
     $recordset = rlip_get_scheduled_jobs($data['plugin']);
     // Data validation.
     $this->assertTrue($recordset->valid());
     $current = $recordset->current();
     // Ip schedule fields.
     $this->assertEquals($current->plugin, $data['plugin']);
     // User fields.
     $this->assertEquals($current->username, $user->username);
     $this->assertEquals($current->firstname, $user->firstname);
     $this->assertEquals($current->lastname, $user->lastname);
     $this->assertEquals($current->timezone, $user->timezone);
     $this->assertEquals($current->lastruntime, 0);
     // Elis scheduled task field.
     $this->assertGreaterThanOrEqual($starttime + 5 * MINSECS, (int) $current->nextruntime);
     $this->assertGreaterThanOrEqual((int) $current->nextruntime, $endtime + 5 * MINSECS);
 }
Example #26
0
 /**
  * Create one or more users
  *
  * @param array $users  An array of users to create.
  * @return array An array of arrays
  */
 public static function create_users($users)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/lib/weblib.php";
     require_once $CFG->dirroot . "/user/lib.php";
     require_once $CFG->dirroot . "/user/profile/lib.php";
     //required for customfields related function
     //TODO: move the functions somewhere else as
     //they are "user" related
     // Ensure the current user is allowed to run this function
     $context = get_context_instance(CONTEXT_SYSTEM);
     self::validate_context($context);
     require_capability('moodle/user:create', $context);
     // Do basic automatic PARAM checks on incoming data, using params description
     // If any problems are found then exceptions are thrown with helpful error messages
     $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
     $availableauths = get_plugin_list('auth');
     unset($availableauths['mnet']);
     // these would need mnethostid too
     unset($availableauths['webservice']);
     // we do not want new webservice users for now
     $availablethemes = get_plugin_list('theme');
     $availablelangs = get_string_manager()->get_list_of_translations();
     $transaction = $DB->start_delegated_transaction();
     $userids = array();
     foreach ($params['users'] as $user) {
         // Start of user info validation.
         //
         // Make sure that the username doesn't already exist
         if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
             $a = array('idnumber' => $user['idnumber'], 'username' => $user['username']);
             throw new moodle_exception('username_already_exists', 'local_sistemaaulaws', '', $a);
         }
         // Make sure auth is valid
         if (empty($availableauths[$user['auth']])) {
             $a = array('idnumber' => $user['idnumber'], 'username' => $user['username'], 'auth' => $user['auth']);
             throw new moodle_exception('invalid_authentication_type', 'local_sistemaaulaws', '', $a);
         }
         // Make sure lang is valid
         if (empty($availablelangs[$user['lang']])) {
             $a = new stdClass();
             $a->idnumber = $user['idnumber'];
             $a->name = $user['username'];
             $a->lang = $user['lang'];
             $a->object = get_string('object_name_user', 'local_sistemaaulaws');
             $a->object_text_name = get_string('object_text_name_user', 'local_sistemaaulaws');
             throw new modle('invalid_language_code', 'local_sistemaaulaws', '', $a);
         }
         // Make sure lang is valid
         if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) {
             //theme is VALUE_OPTIONAL,
             // so no default value.
             // We need to test if the client sent it
             // => !empty($user['theme'])
             $a = new stdClass();
             $a->idnumber = $user['idnumber'];
             $a->name = $user['username'];
             $a->theme = $user['theme'];
             $a->object = get_string('object_name_user', 'local_sistemaaulaws');
             $a->object_text_name = get_string('object_text_name_user', 'local_sistemaaulaws');
             throw new modle_exception('invalid_theme', 'local_sistemaaulaws', '', $a);
         }
         if (!empty($user['email'])) {
             if (!validate_email($user['email'])) {
                 $a = new stdClass();
                 $a->idnumber = $user['idnumber'];
                 $a->name = $user['username'];
                 $a->email = $user['email'];
                 throw new moodle_exception('email_address_is_invalid', 'local_sistemaaulaws', $a);
             } else {
                 if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
                     $a = new stdClass();
                     $a->idnumber = $user['idnumber'];
                     $a->name = $user['username'];
                     $a->email = $user['email'];
                     throw new moodle_exception('email_address_already_exists', 'local_sistemaaulaws', $a);
                 }
             }
         }
         //
         // End of user info validation.
         // CDCP: Achei válido deixar esta verificação em nossa função,
         // CDCP: é importante não perder nenhum dado.
         // CDCP: eles devem ser enviados no tamanho certo.
         //
         // make sure there is no data loss during truncation
         $truncated = truncate_userinfo($user);
         foreach ($truncated as $key => $value) {
             if ($truncated[$key] !== $user[$key]) {
                 $a = array('idnumber' => $user['idnumber'], 'username', 'key' => $key, 'value' => $user[$key]);
                 throw new moodle_exception('property_is_too_long', 'local_sistemaaulaws', '', $a);
             }
         }
         $user['confirmed'] = true;
         $user['mnethostid'] = $CFG->mnet_localhost_id;
         $user['id'] = user_create_user($user);
         // custom fields
         if (!empty($user['customfields'])) {
             foreach ($user['customfields'] as $customfield) {
                 $user["profile_field_" . $customfield['type']] = $customfield['value'];
                 //profile_save_data() saves profile file
                 //it's expecting a user with the correct id,
                 //and custom field to be named profile_field_"shortname"
             }
             profile_save_data((object) $user);
         }
         //preferences
         if (!empty($user['preferences'])) {
             foreach ($user['preferences'] as $preference) {
                 set_user_preference($preference['type'], $preference['value'], $user['id']);
             }
         }
         $userids[] = array('id' => $user['id'], 'idnumber' => $user['idnumber'], 'username' => $user['username']);
     }
     $transaction->allow_commit();
     return $userids;
 }
Example #27
0
/**
 * Creates a bare-bones user record
 *
 * @todo Outline auth types and provide code example
 *
 * @param string $username New user's username to add to record
 * @param string $password New user's password to add to record
 * @param string $auth Form of authentication required
 * @return stdClass A complete user object
 */
function create_user_record($username, $password, $auth = 'manual')
{
    global $CFG, $DB;
    require_once $CFG->dirroot . '/user/profile/lib.php';
    require_once $CFG->dirroot . '/user/lib.php';
    // Just in case check text case.
    $username = trim(core_text::strtolower($username));
    $authplugin = get_auth_plugin($auth);
    $customfields = $authplugin->get_custom_user_profile_fields();
    $newuser = new stdClass();
    if ($newinfo = $authplugin->get_userinfo($username)) {
        $newinfo = truncate_userinfo($newinfo);
        foreach ($newinfo as $key => $value) {
            if (in_array($key, $authplugin->userfields) || in_array($key, $customfields)) {
                $newuser->{$key} = $value;
            }
        }
    }
    if (!empty($newuser->email)) {
        if (email_is_not_allowed($newuser->email)) {
            unset($newuser->email);
        }
    }
    if (!isset($newuser->city)) {
        $newuser->city = '';
    }
    $newuser->auth = $auth;
    $newuser->username = $username;
    // Fix for MDL-8480
    // user CFG lang for user if $newuser->lang is empty
    // or $user->lang is not an installed language.
    if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
        $newuser->lang = $CFG->lang;
    }
    $newuser->confirmed = 1;
    $newuser->lastip = getremoteaddr();
    $newuser->timecreated = time();
    $newuser->timemodified = $newuser->timecreated;
    $newuser->mnethostid = $CFG->mnet_localhost_id;
    $newuser->id = user_create_user($newuser, false, false);
    // Save user profile data.
    profile_save_data($newuser);
    $user = get_complete_user_data('id', $newuser->id);
    if (!empty($CFG->{'auth_' . $newuser->auth . '_forcechangepassword'})) {
        set_user_preference('auth_forcepasswordchange', 1, $user);
    }
    // Set the password.
    update_internal_user_password($user, $password);
    // Trigger event.
    \core\event\user_created::create_from_userid($newuser->id)->trigger();
    return $user;
}
Example #28
0
     /**
     * @method cobalt_admission_info
     * @todo process the appicants
     * @param int $id applcationid
     * @param int $curid curriculumid
     * @param string $username Username
     * @param string $password Password
     */

    public function cobalt_admission_info($id, $curid, $username, $password, $needuserid=false,$batchuploadfields=false) {

        global $DB, $USER;
        $applicant = $DB->get_record('local_admission', array('id' => $id));	
        $dbpwd = hash_internal_user_password($password);
        $record = new stdclass();
        $record->id = $id;
        $record->status = 1;
        $localadmission = $DB->update_record('local_admission', $record);
        //Inserting in user table
        if ($applicant->previousstudent == 1) {
	    $existsuser=$DB->get_record('user',array('email'=>$applicant->email));
	     if(!$existsuser->id){
            $user = new stdclass();
            $user->confirmed = 1;
            $user->mnethostid = 1;
            $user->username = strtolower( $username);
            $user->password = $dbpwd;
            $user->firstname = $applicant->firstname;
            $user->lastname = $applicant->lastname;
            $user->email = $applicant->email;
            $user->phone1 = $applicant->phone;
            $user->address = $applicant->address;
            $user->city = $applicant->city;
            $user->country = $applicant->currentcountry;

            $user->theme = $DB->get_field('local_school', 'theme', array('id' => $applicant->schoolid));

            //$userid = $DB->insert_record('user', $user);
            //
            ////Inserting in context table
            //$context = new stdClass();
            //$context->contextlevel = 30;
            //$context->instanceid = $userid;
            //$context->depth = 2;
            //$contextid = $DB->insert_record('context', $context);
            ////Updating context table
            //$updatecontext = new stdClass();
            //$updatecontext->id = $contextid;
            //$updatecontext->path = '/1/' . $contextid . '';
            //$updated = $DB->update_record('context', $updatecontext);
	    $userid =  user_create_user($user, false, false);
	    
	    
	    $contextid =$DB->get_field('context','id',array('contextlevel'=>30, 'instanceid'=>$userid));
            /* ---code to display blocks starts here--- */
            $blocks = array("academic_status", "events", "calendar_upcoming");
            foreach ($blocks as $key => $block) {
                $blockdata = new stdClass();
                $blockdata->blockname = $block;
                $blockdata->parentcontextid = $contextid;
                $blockdata->showinsubcontexts = 0;
                $blockdata->pagetypepattern = 'my-index';
                $blockdata->subpagepattern = 16;
                $blockdata->defaultregion = 'dashboard-one';
                $blockdata->defaultweight = $key;
                $blockinstanceid = $DB->insert_record('block_instances', $blockdata);
                $blockcontext = new stdClass();
                $blockcontext->contextlevel = 80;
                $blockcontext->instanceid = $blockinstanceid;
                $blockcontext->depth = 3;
                $bkcontext = $DB->insert_record('context', $blockcontext);
                $updatebkcontext = new stdClass();
                $updatebkcontext->id = $bkcontext;
                $updatebkcontext->path = '/1/' . $contextid . '/' . $bkcontext . '';
                $blockresult = $DB->update_record('context', $updatebkcontext);
            }
            /* ---code to display blocks ends here--- */

            //Inserting in role_assignments
            $role = new stdClass();
            $role->roleid = 5;
            $role->contextid = $contextid;
            $role->userid = $userid;
            $role->timemodified = time();
            $role->modifierid = $USER->id;
            $roleassign = $DB->insert_record('role_assignments', $role);
            $prefix = $DB->get_record('local_prefix_suffix', array('entityid' => 2, 'schoolid' => $applicant->schoolid, 'programid' => $applicant->programid));
            $random = random_string(5);
            $serviceid = $prefix->prefix . $userid . $prefix->suffix . $random;
	  }
        }
	
        if(isset($existsuser->id))
	$userid = $existsuser->id;
	else
	$userid = $userid;
	
	
        //Inserting in local_admission
        $local = new stdclass();
        $local->middlename = $applicant->middlename;
        $local->gender = $applicant->gender;
        $local->dob = $applicant->dob;
        $local->birthcountry = $applicant->birthcountry;
        $local->birthplace = $applicant->birthplace;
        $local->fathername = $applicant->fathername;
        $local->pob = $applicant->pob;
        $local->region = $applicant->region;
        $local->town = $applicant->town;
        $local->currenthno = $applicant->currenthno;
        $local->currentcountry = $applicant->currentcountry;
        $local->howlong = $applicant->howlong;
        $local->same = $applicant->same;
        $local->permanenthno = $applicant->permanenthno;
        $local->state = $applicant->state;
        $local->pincode = $applicant->pincode;
        $local->contactname = $applicant->contactname;
        $local->primaryschoolname = $applicant->primaryschoolname;
        $local->primaryyear = $applicant->primaryyear;
        $local->primaryscore = $applicant->primaryscore;
        $local->ugin = $applicant->ugin;
        $local->ugname = $applicant->ugname;
        $local->ugyear = $applicant->ugyear;
        $local->ugscore = $applicant->ugscore;
        $local->graduatein = $applicant->graduatein;
        $local->graduatename = $applicant->graduatename;
        $local->graduateyear = $applicant->graduateyear;
        $local->graduatescore = $applicant->graduatescore;
        $local->examname = $applicant->examname;
        $local->hallticketno = $applicant->hallticketno;
        $local->score = $applicant->score;
        $local->noofmonths = $applicant->noofmonths;
        $local->reason = $applicant->reason;
        $local->description = $applicant->description;
        $local->typeofprogram = $applicant->typeofprogram;
        $local->typeofapplication = $applicant->typeofapplication;
        $local->typeofstudent = $applicant->typeofstudent;
        $local->dateofapplication = $applicant->dateofapplication;
        $local->applicationid = $applicant->applicationid;
        $local->applicantid = $id;
        $local->status = 0;
        $local->usermodified = $USER->id;
        $local->timemodified = time();
        $local->timecreated = time();

        $local->userid = $userid;
        $local->primaryplace = $applicant->primaryplace;
        $local->ugplace = $applicant->ugplace;
        $local->graduateplace = $applicant->graduateplace;
        $local->previousstudent = $applicant->previousstudent;
	$local->otherphone= $applicant->otherphone;
	$local->fatheremail= $applicant->fatheremail;
	$local->category= $applicant->category;
	$local->caste= $applicant->caste;
	$local->mothername= $applicant->mothername;
        $localuser = $DB->insert_record('local_users', $local);

        if ($applicant->previousstudent == 2) {
            $userid = $DB->get_field('user', 'id', array('email' => $applicant->email));
            $result = $DB->get_record('local_userdata', array('userid' => $userid));
            if (empty($result) || !isset($result)) {
                $prefix = $DB->get_record('local_prefix_suffix', array('entityid' => 2, 'schoolid' => $applicant->schoolid, 'programid' => $applicant->programid));
                $random = random_string(5);
                $serviceid = $prefix->prefix . $userid . $prefix->suffix . $random;
            } else {
                $serviceid = $result->serviceid;
            }
        }
	
	if($applicant->previousstudent == 1){
	    $serviceid= $batchuploadfields->serviceid;
	}
	
        //Inserting in user details
        $data = new stdclass();
        $data->schoolid = $applicant->schoolid;
        $data->programid = $applicant->programid;

        $data->curriculumid = $curid;
        $data->userid = $userid;
        $data->usermodified = $USER->id;
        $data->timemodified = time();
        $data->timecreated = time();
        $data->serviceid = $serviceid;
        $data->applicationid = $applicant->applicationid;
        $data->applicantid = $id;
        $data->fundsbygovt = $applicant->fundsbygovt;
	$data->batchid=$batchuploadfields->batchid;

        $result = $DB->insert_record('local_userdata', $data);
	if($needuserid){
	    return array('serviceid'=>$serviceid ,'userid' =>$userid);
	}
	else
        return $serviceid;
    }
Example #29
0
 /**
  * Test create_users.
  */
 public function test_create_users()
 {
     global $DB;
     $this->resetAfterTest();
     $user = array('username' => 'usernametest1', 'password' => 'Moodle2012!', 'idnumber' => 'idnumbertest1', 'firstname' => 'First Name User Test 1', 'lastname' => 'Last Name User Test 1', 'middlename' => 'Middle Name User Test 1', 'lastnamephonetic' => '最後のお名前のテスト一号', 'firstnamephonetic' => 'お名前のテスト一号', 'alternatename' => 'Alternate Name User Test 1', 'email' => '*****@*****.**', 'description' => 'This is a description for user 1', 'city' => 'Perth', 'country' => 'AU');
     // Create user and capture event.
     $sink = $this->redirectEvents();
     $user['id'] = user_create_user($user);
     $events = $sink->get_events();
     $sink->close();
     $event = array_pop($events);
     // Test user info in DB.
     $dbuser = $DB->get_record('user', array('id' => $user['id']));
     $this->assertEquals($dbuser->username, $user['username']);
     $this->assertEquals($dbuser->idnumber, $user['idnumber']);
     $this->assertEquals($dbuser->firstname, $user['firstname']);
     $this->assertEquals($dbuser->lastname, $user['lastname']);
     $this->assertEquals($dbuser->email, $user['email']);
     $this->assertEquals($dbuser->description, $user['description']);
     $this->assertEquals($dbuser->city, $user['city']);
     $this->assertEquals($dbuser->country, $user['country']);
     // Test event.
     $this->assertInstanceOf('\\core\\event\\user_created', $event);
     $this->assertEquals($user['id'], $event->objectid);
     $this->assertEquals('user_created', $event->get_legacy_eventname());
     $this->assertEquals(context_user::instance($user['id']), $event->get_context());
     $this->assertEventLegacyData($dbuser, $event);
     $expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id=' . $event->objectid, fullname($dbuser));
     $this->assertEventLegacyLogData($expectedlogdata, $event);
     // Verify event is not triggred by user_create_user when needed.
     $user = array('username' => 'usernametest2');
     // Create another user.
     $sink = $this->redirectEvents();
     user_create_user($user, true, false);
     $events = $sink->get_events();
     $sink->close();
     $this->assertCount(0, $events);
     // Test user data validation, first some invalid data.
     $user['username'] = '******';
     $user['auth'] = 'shibolth';
     $user['country'] = 'WW';
     $user['lang'] = 'xy';
     $user['theme'] = 'somewrongthemename';
     $user['timezone'] = 'Paris';
     $user['url'] = 'wwww.somewrong@#$url.com.aus';
     $debugmessages = $this->getDebuggingMessages();
     $user['id'] = user_create_user($user, true, false);
     $this->assertDebuggingCalledCount(6, $debugmessages);
     $dbuser = $DB->get_record('user', array('id' => $user['id']));
     $this->assertEquals($dbuser->country, 0);
     $this->assertEquals($dbuser->lang, 'en');
     $this->assertEquals($dbuser->timezone, 'Australia/Perth');
     // Now, with valid user data.
     $user['username'] = '******';
     $user['auth'] = 'shibboleth';
     $user['country'] = 'AU';
     $user['lang'] = 'en';
     $user['theme'] = 'clean';
     $user['timezone'] = 'Australia/Perth';
     $user['url'] = 'www.moodle.org';
     user_create_user($user, true, false);
     $this->assertDebuggingNotCalled();
 }
Example #30
0
 /**
  * Performs synchronisation of member information and enrolments.
  *
  * @param stdClass $tool
  * @param ToolConsumer $consumer
  * @param User[] $members
  * @return array An array containing the number of members that were processed and the number of members that were enrolled.
  */
 protected function sync_member_information(stdClass $tool, ToolConsumer $consumer, $members)
 {
     global $DB;
     $usercount = 0;
     $enrolcount = 0;
     // Process member information.
     foreach ($members as $member) {
         $usercount++;
         // Set the user data.
         $user = new stdClass();
         $user->username = helper::create_username($consumer->getKey(), $member->ltiUserId);
         $user->firstname = core_user::clean_field($member->firstname, 'firstname');
         $user->lastname = core_user::clean_field($member->lastname, 'lastname');
         $user->email = core_user::clean_field($member->email, 'email');
         // Get the user data from the LTI consumer.
         $user = helper::assign_user_tool_data($tool, $user);
         $dbuser = core_user::get_user_by_username($user->username, 'id');
         if ($dbuser) {
             // If email is empty remove it, so we don't update the user with an empty email.
             if (empty($user->email)) {
                 unset($user->email);
             }
             $user->id = $dbuser->id;
             user_update_user($user);
             // Add the information to the necessary arrays.
             if (!in_array($user->id, $this->currentusers)) {
                 $this->currentusers[] = $user->id;
             }
             $this->userphotos[$user->id] = $member->image;
         } else {
             if ($this->should_sync_enrol($tool->membersyncmode)) {
                 // If the email was stripped/not set then fill it with a default one. This
                 // stops the user from being redirected to edit their profile page.
                 if (empty($user->email)) {
                     $user->email = $user->username . "@example.com";
                 }
                 $user->auth = 'lti';
                 $user->id = user_create_user($user);
                 // Add the information to the necessary arrays.
                 $this->currentusers[] = $user->id;
                 $this->userphotos[$user->id] = $member->image;
             }
         }
         // Sync enrolments.
         if ($this->should_sync_enrol($tool->membersyncmode)) {
             // Enrol the user in the course.
             if (helper::enrol_user($tool, $user->id) === helper::ENROLMENT_SUCCESSFUL) {
                 // Increment enrol count.
                 $enrolcount++;
             }
             // Check if this user has already been registered in the enrol_lti_users table.
             if (!$DB->record_exists('enrol_lti_users', ['toolid' => $tool->id, 'userid' => $user->id])) {
                 // Create an initial enrol_lti_user record that we can use later when syncing grades and members.
                 $userlog = new stdClass();
                 $userlog->userid = $user->id;
                 $userlog->toolid = $tool->id;
                 $userlog->consumerkey = $consumer->getKey();
                 $DB->insert_record('enrol_lti_users', $userlog);
             }
         }
     }
     return [$usercount, $enrolcount];
 }