• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP user_create_user函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中user_create_user函数的典型用法代码示例。如果您正苦于以下问题:PHP user_create_user函数的具体用法?PHP user_create_user怎么用?PHP user_create_user使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了user_create_user函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: user_signup

 /**
  * 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;
     }
 }
开发者ID:posttechguy,项目名称:moodle-whia-auth_whia,代码行数:38,代码来源:auth.php


示例2: test_create_users

 /**
  * 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' => '[email protected]', '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);
 }
开发者ID:tyleung,项目名称:CMPUT401MoodleExams,代码行数:33,代码来源:userlib_test.php


示例3: create_user

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'];
}
开发者ID:advancingdesign,项目名称:moodle-quiz_papercopy,代码行数:11,代码来源:createuser.php


示例4: execute

 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";
     }
 }
开发者ID:dariogs,项目名称:moosh,代码行数:49,代码来源:UserCreate.php


示例5: build

 /**
  * 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));
     }
 }
开发者ID:bgao-ca,项目名称:moodle-local_mr,代码行数:27,代码来源:user.php


示例6: application_user_signup

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');
}
开发者ID:OBU-OBIS,项目名称:moodle-local_obu_application,代码行数:22,代码来源:locallib.php


示例7: create_users

 /**
  * 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;
 }
开发者ID:vinoth4891,项目名称:clinique,代码行数:86,代码来源:externallib.php


示例8: user_create_user

     $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));
     }
开发者ID:sirromas,项目名称:lms,代码行数:31,代码来源:tool.php


示例9: sync_users


//.........这里部分代码省略.........
     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;
 }
开发者ID:janaece,项目名称:globalclassroom4_clean,代码行数:101,代码来源:auth.php


示例10: create_test_user

 /**
  * 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 = 'rlipusername', $email = '[email protected]', $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 = 'Rlippassword!1234';
     $user->idnumber = $idnumber;
     return user_create_user($user);
 }
开发者ID:jamesmcq,项目名称:elis,代码行数:21,代码来源:version1elis_filesystem_logging_test.php


示例11: create_users

    /**
     * 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;
    }
开发者ID:ravivare,项目名称:moodle-1,代码行数:92,代码来源:externallib.php


示例12: hash_internal_user_password

                 $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);
开发者ID:educakanchay,项目名称:campus,代码行数:31,代码来源:index.php


示例13: execute

 /**
  * 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;
                             }
//.........这里部分代码省略.........
开发者ID:evltuma,项目名称:moodle,代码行数:101,代码来源:sync_members.php


示例14: auto_create_bot

 /**
  * 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 = '[email protected]';
         $botuser->city = 'Botville';
         $botuser->country = 'AU';
         $botuser->mnethostid = $CFG->mnet_localhost_id;
         $botuser->id = user_create_user($botuser, false, false);
         return $botuser;
     }
 }
开发者ID:central-queensland-uni,项目名称:moodle-local_linkchecker_robot,代码行数:27,代码来源:crawler.php


示例15: moodle_group_delete_groups

    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 = 'veryimprobabletestusername2';
        $user->password = 'testpassword2';
        $user->firstname = 'testfirstname2';
        $user->lastname = 'testlastname2';
        $user->email = '[email protected]';
        $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));

    }
开发者ID:nuckey,项目名称:moodle,代码行数:92,代码来源:testwebservice.php


示例16: confirm_mnet_session

 /**
  * 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;
  

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP user_current_username函数代码示例发布时间:2022-05-23
下一篇:
PHP user_create函数代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap