/**
 * Add the users to the system. Make sure that they have to change their
 * password on next login also.
 */
function uploadcsv_submit(Pieform $form, $values)
{
    global $USER, $SESSION, $CSVDATA, $FORMAT, $UPDATES;
    $formatkeylookup = array_flip($FORMAT);
    $authinstance = (int) $values['authinstance'];
    $authrecord = get_record('auth_instance', 'id', $authinstance);
    $authobj = AuthFactory::create($authinstance);
    $institution = new Institution($authobj->institution);
    $maxusers = $institution->maxuseraccounts;
    if (!empty($maxusers)) {
        $members = count_records_sql('
            SELECT COUNT(*) FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
            WHERE i.institution = ? AND u.deleted = 0', array($institution->name));
        if ($members + count($CSVDATA) > $maxusers) {
            $SESSION->add_error_msg(get_string('uploadcsvfailedusersexceedmaxallowed', 'admin'));
            redirect('/admin/users/uploadcsv.php');
        }
    }
    if ($values['updateusers']) {
        log_info('Updating users from the CSV file');
    } else {
        log_info('Inserting users from the CSV file');
    }
    db_begin();
    $addedusers = array();
    $cfgsendemail = get_config('sendemail');
    if (empty($values['emailusers'])) {
        // Temporarily disable email sent during user creation, e.g. institution membership
        $GLOBALS['CFG']->sendemail = false;
    }
    foreach ($CSVDATA as $record) {
        $user = new StdClass();
        $gcr_users = array();
        $gcr_users["state"] = "";
        $gcr_users["country"] = "";
        foreach ($FORMAT as $field) {
            if ($field == 'username' || $field == 'firstname' || $field == 'lastname' || $field == 'password' || $field == 'email' || $field == 'studentid' || $field == 'preferredname') {
                $user->{$field} = $record[$formatkeylookup[$field]];
            }
            if ($field == 'state' || $field == 'country') {
                $gcr_users[$field] = $record[$formatkeylookup[$field]];
            }
        }
        $user->authinstance = $authinstance;
        if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
            $user->quota = $values['quota'];
        }
        $profilefields = new StdClass();
        $remoteuser = null;
        foreach ($FORMAT as $field) {
            if ($field == 'username' || $field == 'password') {
                continue;
            }
            if ($field == 'remoteuser') {
                if (!empty($record[$formatkeylookup[$field]])) {
                    $remoteuser = $record[$formatkeylookup[$field]];
                }
                continue;
            }
            if ($field != 'state' && $field != 'country') {
                $profilefields->{$field} = $record[$formatkeylookup[$field]];
            }
        }
        if (!$values['updateusers'] || !isset($UPDATES[$user->username])) {
            $user->passwordchange = (int) $values['forcepasswordchange'];
            unset($values["state"]);
            unset($values["country"]);
            $user->id = create_user($user, $profilefields, $institution, $authrecord, $remoteuser, $values, true);
            $current_app_name = explode(".", $_SERVER["HTTP_HOST"]);
            $current_app_short_name = $current_app_name[0];
            $current_app_short_name = str_replace("http://", "", $current_app_short_name);
            $current_app_short_name = str_replace("https://", "", $current_app_short_name);
            $user_obj = new GcrUsers();
            $user_obj->setPlatformShortName($current_app_short_name);
            $user_obj->setUsername($user->username);
            $user_obj->setUserId($user->id);
            $user_obj->setState($gcr_users["state"]);
            $user_obj->setCountry($gcr_users["country"]);
            $user_obj->setCreatedDatetime(date("Y-m-d H:i:s"));
            $user_obj->save();
            $addedusers[] = $user;
            log_debug('added user ' . $user->username);
        } else {
            if (isset($UPDATES[$user->username])) {
                $updated = update_user($user, $profilefields, $remoteuser, $values, true, true);
                if (empty($updated)) {
                    // Nothing changed for this user
                    unset($UPDATES[$user->username]);
                } else {
                    $UPDATES[$user->username] = $updated;
                    log_debug('updated user ' . $user->username . ' (' . implode(', ', array_keys($updated)) . ')');
                }
            }
        }
        set_time_limit(10);
    }
    db_commit();
    // Reenable email
    set_config('sendemail', $cfgsendemail);
    // Only send e-mail to users after we're sure they have been inserted
    // successfully
    $straccountcreatedtext = $values['forcepasswordchange'] ? 'accountcreatedchangepasswordtext' : 'accountcreatedtext';
    $straccountcreatedhtml = $values['forcepasswordchange'] ? 'accountcreatedchangepasswordhtml' : 'accountcreatedhtml';
    if ($values['emailusers'] && $addedusers) {
        foreach ($addedusers as $user) {
            $failedusers = array();
            try {
                email_user($user, null, get_string('accountcreated', 'mahara', get_config('sitename')), get_string($straccountcreatedtext, 'mahara', $user->firstname, get_config('sitename'), $user->username, $user->password, get_config('wwwroot'), get_config('sitename')), get_string($straccountcreatedhtml, 'mahara', $user->firstname, get_config('wwwroot'), get_config('sitename'), $user->username, $user->password, get_config('wwwroot'), get_config('wwwroot'), get_config('sitename')));
            } catch (EmailException $e) {
                log_info($e->getMessage());
                $failedusers[] = $user;
            }
        }
        if ($failedusers) {
            $message = get_string('uploadcsvsomeuserscouldnotbeemailed', 'admin') . "\n<ul>\n";
            foreach ($failedusers as $user) {
                $message .= '<li>' . full_name($user) . ' &lt;' . hsc($user->email) . "&gt;</li>\n";
            }
            $message .= "</ul>\n";
            $SESSION->add_info_msg($message, false);
        }
    }
    log_info('Added ' . count($addedusers) . ' users, updated ' . count($UPDATES) . ' users.');
    $SESSION->add_ok_msg(get_string('csvfileprocessedsuccessfully', 'admin'));
    if ($UPDATES) {
        $updatemsg = smarty_core();
        $updatemsg->assign('added', count($addedusers));
        $updatemsg->assign('updates', $UPDATES);
        $SESSION->add_info_msg($updatemsg->fetch('admin/users/csvupdatemessage.tpl'), false);
    } else {
        $SESSION->add_ok_msg(get_string('numbernewusersadded', 'admin', count($addedusers)));
    }
    redirect('/admin/users/uploadcsv.php');
}
Esempio n. 2
0
function adduser_submit(Pieform $form, $values)
{
    global $USER, $SESSION, $TRANSPORTER;
    db_begin();
    raise_time_limit(180);
    // Create user
    $user = (object) array('authinstance' => $values['authinstance'], 'username' => $values['username'], 'firstname' => $values['firstname'] ? $values['firstname'] : 'Imported', 'lastname' => $values['lastname'] ? $values['lastname'] : 'User', 'email' => $values['email'], 'password' => $values['password'], 'passwordchange' => 1);
    if ($USER->get('admin')) {
        // Not editable by institutional admins
        $user->staff = (int) ($values['staff'] == 'on');
        $user->admin = (int) ($values['admin'] == 'on');
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $user->quota = $values['quota'];
    }
    $authinstance = get_record('auth_instance', 'id', $values['authinstance']);
    $remoteauth = false;
    if ($authinstance->authname != 'internal') {
        $remoteauth = true;
    }
    if (!isset($values['remoteusername'])) {
        $values['remoteusername'] = null;
    }
    $user->id = create_user($user, array(), $authinstance->institution, $remoteauth, $values['remoteusername'], $values);
    $current_app_name = explode(".", $_SERVER["HTTP_HOST"]);
    $current_app_short_name = $current_app_name[0];
    $current_app_short_name = str_replace("http://", "", $current_app_short_name);
    $current_app_short_name = str_replace("https://", "", $current_app_short_name);
    $user_obj = new GcrUsers();
    $user_obj->setPlatformShortName($current_app_short_name);
    $user_obj->setUsername($user->username);
    $user_obj->setUserId($user->id);
    $user_obj->setCountry($values['country']);
    $user_obj->setState($values['state']);
    $user_obj->setCreatedDatetime(date("Y-m-d H:i:s"));
    $user_obj->save();
    if (isset($user->admin) && $user->admin) {
        require_once 'activity.php';
        activity_add_admin_defaults(array($user->id));
    }
    if ($values['institutionadmin']) {
        set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $authinstance->institution);
    }
    if (isset($values['leap2afile'])) {
        // And we're good to go
        $importdata = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
        $importer = PluginImport::create_importer(null, $TRANSPORTER, $importdata);
        try {
            $importer->process();
            log_info("Imported user account {$user->id} from Leap2A file, see " . $importer->get('logfile') . ' for a full log');
        } catch (ImportException $e) {
            log_info("Leap2A import failed: " . $e->getMessage());
            die_info(get_string('leap2aimportfailed', 'admin'));
        }
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $user = get_record('usr', 'id', $user->id);
    }
    db_commit();
    if (!empty($user->email)) {
        try {
            email_user($user, $USER, get_string('accountcreated', 'mahara', get_config('sitename')), get_string('accountcreatedchangepasswordtext', 'mahara', $user->firstname, get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('sitename')), get_string('accountcreatedchangepasswordhtml', 'mahara', $user->firstname, get_config('wwwroot'), get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('wwwroot'), get_config('sitename')));
        } catch (EmailException $e) {
            $SESSION->add_error_msg(get_string('newuseremailnotsent', 'admin'));
        }
    }
    $SESSION->add_ok_msg(get_string('newusercreated', 'admin'));
    redirect('/admin/users/edit.php?id=' . $user->id);
}