diff --git a/admin/tool/uploaduser/classes/cli_helper.php b/admin/tool/uploaduser/classes/cli_helper.php
new file mode 100644
index 00000000000..e258e7d8ad9
--- /dev/null
+++ b/admin/tool/uploaduser/classes/cli_helper.php
@@ -0,0 +1,402 @@
+.
+
+/**
+ * Class cli_helper
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_uploaduser;
+
+defined('MOODLE_INTERNAL') || die();
+
+use tool_uploaduser\local\cli_progress_tracker;
+
+require_once($CFG->dirroot.'/user/profile/lib.php');
+require_once($CFG->dirroot.'/user/lib.php');
+require_once($CFG->dirroot.'/group/lib.php');
+require_once($CFG->dirroot.'/cohort/lib.php');
+require_once($CFG->libdir.'/csvlib.class.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/user_form.php');
+require_once($CFG->libdir . '/clilib.php');
+
+/**
+ * Helper method for CLI script to upload users (also has special wrappers for cli* functions for phpunit testing)
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cli_helper {
+
+ /** @var string */
+ protected $operation;
+ /** @var array */
+ protected $clioptions;
+ /** @var array */
+ protected $unrecognized;
+ /** @var string */
+ protected $progresstrackerclass;
+
+ /** @var process */
+ protected $process;
+
+ /**
+ * cli_helper constructor.
+ *
+ * @param string|null $progresstrackerclass
+ */
+ public function __construct(?string $progresstrackerclass = null) {
+ $this->progresstrackerclass = $progresstrackerclass ?? cli_progress_tracker::class;
+ $optionsdefinitions = $this->options_definitions();
+ $longoptions = [];
+ $shortmapping = [];
+ foreach ($optionsdefinitions as $key => $option) {
+ $longoptions[$key] = $option['default'];
+ if (!empty($option['alias'])) {
+ $shortmapping[$option['alias']] = $key;
+ }
+ }
+
+ list($this->clioptions, $this->unrecognized) = cli_get_params(
+ $longoptions,
+ $shortmapping
+ );
+ }
+
+ /**
+ * Options used in this CLI script
+ *
+ * @return array
+ */
+ protected function options_definitions(): array {
+ $options = [
+ 'help' => [
+ 'hasvalue' => false,
+ 'description' => get_string('clihelp', 'tool_uploaduser'),
+ 'default' => 0,
+ 'alias' => 'h',
+ ],
+ 'file' => [
+ 'hasvalue' => 'PATH',
+ 'description' => get_string('clifile', 'tool_uploaduser'),
+ 'default' => null,
+ 'validation' => function($file) {
+ if (!$file) {
+ $this->cli_error(get_string('climissingargument', 'tool_uploaduser', 'file'));
+ }
+ if ($file && (!file_exists($file) || !is_readable($file))) {
+ $this->cli_error(get_string('clifilenotreadable', 'tool_uploaduser', $file));
+ }
+ }
+ ],
+ ];
+ $form = new \admin_uploaduser_form1();
+ [$elements, $defaults] = $form->get_form_for_cli();
+ $options += $this->prepare_form_elements_for_cli($elements, $defaults);
+ $form = new \admin_uploaduser_form2(null, ['columns' => ['type1'], 'data' => []]);
+ [$elements, $defaults] = $form->get_form_for_cli();
+ $options += $this->prepare_form_elements_for_cli($elements, $defaults);
+ return $options;
+ }
+
+ /**
+ * Print help for export
+ */
+ public function print_help(): void {
+ $this->cli_writeln(get_string('clititle', 'tool_uploaduser'));
+ $this->cli_writeln('');
+ $this->print_help_options($this->options_definitions());
+ $this->cli_writeln('');
+ $this->cli_writeln('Example:');
+ $this->cli_writeln('$sudo -u www-data /usr/bin/php admin/tool/uploaduser/cli/uploaduser.php --file=PATH');
+ }
+
+ /**
+ * Get CLI option
+ *
+ * @param string $key
+ * @return mixed|null
+ */
+ public function get_cli_option(string $key) {
+ return $this->clioptions[$key] ?? null;
+ }
+
+ /**
+ * Write a text to the given stream
+ *
+ * @param string $text text to be written
+ */
+ protected function cli_write($text): void {
+ if (PHPUNIT_TEST) {
+ echo $text;
+ } else {
+ cli_write($text);
+ }
+ }
+
+ /**
+ * Write error notification
+ * @param string $text
+ * @return void
+ */
+ protected function cli_problem($text): void {
+ if (PHPUNIT_TEST) {
+ echo $text;
+ } else {
+ cli_problem($text);
+ }
+ }
+
+ /**
+ * Write a text followed by an end of line symbol to the given stream
+ *
+ * @param string $text text to be written
+ */
+ protected function cli_writeln($text): void {
+ $this->cli_write($text . PHP_EOL);
+ }
+
+ /**
+ * Write to standard error output and exit with the given code
+ *
+ * @param string $text
+ * @param int $errorcode
+ * @return void (does not return)
+ */
+ protected function cli_error($text, $errorcode = 1): void {
+ $this->cli_problem($text);
+ $this->die($errorcode);
+ }
+
+ /**
+ * Wrapper for "die()" method so we can unittest it
+ *
+ * @param mixed $errorcode
+ * @throws \moodle_exception
+ */
+ protected function die($errorcode): void {
+ if (!PHPUNIT_TEST) {
+ die($errorcode);
+ } else {
+ throw new \moodle_exception('CLI script finished with error code '.$errorcode);
+ }
+ }
+
+ /**
+ * Display as CLI table
+ *
+ * @param array $column1
+ * @param array $column2
+ * @param int $indent
+ * @return string
+ */
+ protected function convert_to_table(array $column1, array $column2, int $indent = 0): string {
+ $maxlengthleft = 0;
+ $left = [];
+ $column1 = array_values($column1);
+ $column2 = array_values($column2);
+ foreach ($column1 as $i => $l) {
+ $left[$i] = str_repeat(' ', $indent) . $l;
+ if (strlen('' . $column2[$i])) {
+ $maxlengthleft = max($maxlengthleft, strlen($l) + $indent);
+ }
+ }
+ $maxlengthright = 80 - $maxlengthleft - 1;
+ $output = '';
+ foreach ($column2 as $i => $r) {
+ if (!strlen('' . $r)) {
+ $output .= $left[$i] . "\n";
+ continue;
+ }
+ $right = wordwrap($r, $maxlengthright, "\n");
+ $output .= str_pad($left[$i], $maxlengthleft) . ' ' .
+ str_replace("\n", PHP_EOL . str_repeat(' ', $maxlengthleft + 1), $right) . PHP_EOL;
+ }
+ return $output;
+ }
+
+ /**
+ * Display available CLI options as a table
+ *
+ * @param array $options
+ */
+ protected function print_help_options(array $options): void {
+ $left = [];
+ $right = [];
+ foreach ($options as $key => $option) {
+ if ($option['hasvalue'] !== false) {
+ $l = "--$key={$option['hasvalue']}";
+ } else if (!empty($option['alias'])) {
+ $l = "-{$option['alias']}, --$key";
+ } else {
+ $l = "--$key";
+ }
+ $left[] = $l;
+ $right[] = $option['description'];
+ }
+ $this->cli_write('Options:' . PHP_EOL . $this->convert_to_table($left, $right));
+ }
+
+ /**
+ * Process the upload
+ */
+ public function process(): void {
+ // First, validate all arguments.
+ $definitions = $this->options_definitions();
+ foreach ($this->clioptions as $key => $value) {
+ if ($validator = $definitions[$key]['validation'] ?? null) {
+ $validator($value);
+ }
+ }
+
+ // Read the CSV file.
+ $iid = \csv_import_reader::get_new_iid('uploaduser');
+ $cir = new \csv_import_reader($iid, 'uploaduser');
+ $cir->load_csv_content(file_get_contents($this->get_cli_option('file')),
+ $this->get_cli_option('encoding'), $this->get_cli_option('delimiter_name'));
+ $csvloaderror = $cir->get_error();
+
+ if (!is_null($csvloaderror)) {
+ $this->cli_error(get_string('csvloaderror', 'error', $csvloaderror), 1);
+ }
+
+ // Start upload user process.
+ $this->process = new \tool_uploaduser\process($cir, $this->progresstrackerclass);
+ $filecolumns = $this->process->get_file_columns();
+
+ $form = $this->mock_form(['columns' => $filecolumns, 'data' => ['iid' => $iid, 'previewrows' => 1]], $this->clioptions);
+
+ if (!$form->is_validated()) {
+ $errors = $form->get_validation_errors();
+ $this->cli_error(get_string('clivalidationerror', 'tool_uploaduser') . PHP_EOL .
+ $this->convert_to_table(array_keys($errors), array_values($errors), 2));
+ }
+
+ $this->process->set_form_data($form->get_data());
+ $this->process->process();
+ }
+
+ /**
+ * Mock form submission
+ *
+ * @param array $customdata
+ * @param array $submitteddata
+ * @return \admin_uploaduser_form2
+ */
+ protected function mock_form(array $customdata, array $submitteddata): \admin_uploaduser_form2 {
+ global $USER;
+ $submitteddata['description'] = ['text' => $submitteddata['description'], 'format' => FORMAT_HTML];
+
+ // Now mock the form submission.
+ $submitteddata['_qf__admin_uploaduser_form2'] = 1;
+ $oldignoresesskey = $USER->ignoresesskey ?? null;
+ $USER->ignoresesskey = true;
+ $form = new \admin_uploaduser_form2(null, $customdata, 'post', '', [], true, $submitteddata);
+ $USER->ignoresesskey = $oldignoresesskey;
+
+ $form->set_data($submitteddata);
+ return $form;
+ }
+
+ /**
+ * Prepare form elements for CLI
+ *
+ * @param \HTML_QuickForm_element[] $elements
+ * @param array $defaults
+ * @return array
+ */
+ protected function prepare_form_elements_for_cli(array $elements, array $defaults): array {
+ $options = [];
+ foreach ($elements as $element) {
+ if ($element instanceof \HTML_QuickForm_submit || $element instanceof \HTML_QuickForm_static) {
+ continue;
+ }
+ $type = $element->getType();
+ if ($type === 'html' || $type === 'hidden' || $type === 'header') {
+ continue;
+ }
+
+ $name = $element->getName();
+ if ($name === null || preg_match('/^mform_isexpanded_/', $name)
+ || preg_match('/^_qf__/', $name)) {
+ continue;
+ }
+
+ $label = $element->getLabel();
+ if (!strlen($label) && method_exists($element, 'getText')) {
+ $label = $element->getText();
+ }
+ $default = $defaults[$element->getName()] ?? null;
+
+ $postfix = '';
+ $possiblevalues = null;
+ if ($element instanceof \HTML_QuickForm_select) {
+ $selectoptions = $element->_options;
+ $possiblevalues = [];
+ foreach ($selectoptions as $option) {
+ $possiblevalues[] = '' . $option['attr']['value'];
+ }
+ if (count($selectoptions) < 10) {
+ $postfix .= ':';
+ foreach ($selectoptions as $option) {
+ $postfix .= "\n ".$option['attr']['value']." - ".$option['text'];
+ }
+ }
+ if (!array_key_exists($name, $defaults)) {
+ $firstoption = reset($selectoptions);
+ $default = $firstoption['attr']['value'];
+ }
+ }
+
+ if ($element instanceof \HTML_QuickForm_checkbox) {
+ $postfix = ":\n 0|1";
+ $possiblevalues = ['0', '1'];
+ }
+
+ if ($default !== null & $default !== '') {
+ $postfix .= "\n ".get_string('clidefault', 'tool_uploaduser')." ".$default;
+ }
+ $options[$name] = [
+ 'hasvalue' => 'VALUE',
+ 'description' => $label.$postfix,
+ 'default' => $default,
+ ];
+ if ($possiblevalues !== null) {
+ $options[$name]['validation'] = function($v) use ($possiblevalues, $name) {
+ if (!in_array('' . $v, $possiblevalues)) {
+ $this->cli_error(get_string('clierrorargument', 'tool_uploaduser',
+ (object)['name' => $name, 'values' => join(', ', $possiblevalues)]));
+ }
+ };
+ }
+ }
+ return $options;
+ }
+
+ /**
+ * Get process statistics.
+ *
+ * @return array
+ */
+ public function get_stats(): array {
+ return $this->process->get_stats();
+ }
+}
diff --git a/admin/tool/uploaduser/classes/local/cli_progress_tracker.php b/admin/tool/uploaduser/classes/local/cli_progress_tracker.php
new file mode 100644
index 00000000000..39c5529f94b
--- /dev/null
+++ b/admin/tool/uploaduser/classes/local/cli_progress_tracker.php
@@ -0,0 +1,43 @@
+.
+
+/**
+ * Class cli_progress_tracker
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_uploaduser\local;
+
+/**
+ * Tracks the progress of the user upload and outputs it in CLI script (writes to STDOUT)
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cli_progress_tracker extends text_progress_tracker {
+
+ /**
+ * Output one line (followed by newline)
+ * @param string $line
+ */
+ protected function output_line(string $line): void {
+ cli_writeln($line);
+ }
+}
diff --git a/admin/tool/uploaduser/classes/local/text_progress_tracker.php b/admin/tool/uploaduser/classes/local/text_progress_tracker.php
new file mode 100644
index 00000000000..9e14640e412
--- /dev/null
+++ b/admin/tool/uploaduser/classes/local/text_progress_tracker.php
@@ -0,0 +1,124 @@
+.
+
+/**
+ * Class text_progress_tracker
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_uploaduser\local;
+
+/**
+ * Tracks the progress of the user upload and echos it in a text format
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class text_progress_tracker extends \uu_progress_tracker {
+
+ /**
+ * Print table header.
+ * @return void
+ */
+ public function start() {
+ $this->_row = null;
+ }
+
+ /**
+ * Output one line (followed by newline)
+ * @param string $line
+ */
+ protected function output_line(string $line): void {
+ echo $line . PHP_EOL;
+ }
+
+ /**
+ * Flush previous line and start a new one.
+ * @return void
+ */
+ public function flush() {
+ if (empty($this->_row) or empty($this->_row['line']['normal'])) {
+ // Nothing to print - each line has to have at least number.
+ $this->_row = array();
+ foreach ($this->columns as $col) {
+ $this->_row[$col] = ['normal' => '', 'info' => '', 'warning' => '', 'error' => ''];
+ }
+ return;
+ }
+ $this->output_line(get_string('linex', 'tool_uploaduser', $this->_row['line']['normal']));
+ $prefix = [
+ 'normal' => '',
+ 'info' => '',
+ 'warning' => get_string('warningprefix', 'tool_uploaduser') . ' ',
+ 'error' => get_string('errorprefix', 'tool_uploaduser') . ' ',
+ ];
+ foreach ($this->_row['status'] as $type => $content) {
+ if (strlen($content)) {
+ $this->output_line(' '.$prefix[$type].$content);
+ }
+ }
+
+ foreach ($this->_row as $key => $field) {
+ foreach ($field as $type => $content) {
+ if ($key !== 'status' && $type !== 'normal' && strlen($content)) {
+ $this->output_line(' ' . $prefix[$type] . $this->headers[$key] . ': ' .
+ str_replace("\n", "\n".str_repeat(" ", strlen($prefix[$type] . $this->headers[$key]) + 4), $content));
+ }
+ }
+ }
+ foreach ($this->columns as $col) {
+ $this->_row[$col] = ['normal' => '', 'info' => '', 'warning' => '', 'error' => ''];
+ }
+ }
+
+ /**
+ * Add tracking info
+ * @param string $col name of column
+ * @param string $msg message
+ * @param string $level 'normal', 'warning' or 'error'
+ * @param bool $merge true means add as new line, false means override all previous text of the same type
+ * @return void
+ */
+ public function track($col, $msg, $level = 'normal', $merge = true) {
+ if (empty($this->_row)) {
+ $this->flush();
+ }
+ if (!in_array($col, $this->columns)) {
+ return;
+ }
+ if ($merge) {
+ if ($this->_row[$col][$level] != '') {
+ $this->_row[$col][$level] .= "\n";
+ }
+ $this->_row[$col][$level] .= $msg;
+ } else {
+ $this->_row[$col][$level] = $msg;
+ }
+ }
+
+ /**
+ * Print the table end
+ * @return void
+ */
+ public function close() {
+ $this->flush();
+ $this->output_line(str_repeat('-', 79));
+ }
+}
diff --git a/admin/tool/uploaduser/classes/preview.php b/admin/tool/uploaduser/classes/preview.php
new file mode 100644
index 00000000000..a59302430b0
--- /dev/null
+++ b/admin/tool/uploaduser/classes/preview.php
@@ -0,0 +1,158 @@
+.
+
+/**
+ * Class preview
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_uploaduser;
+
+defined('MOODLE_INTERNAL') || die();
+
+use tool_uploaduser\local\field_value_validators;
+
+require_once($CFG->libdir.'/csvlib.class.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+
+/**
+ * Display the preview of a CSV file
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class preview extends \html_table {
+
+ /** @var \csv_import_reader */
+ protected $cir;
+ /** @var array */
+ protected $filecolumns;
+ /** @var int */
+ protected $previewrows;
+ /** @var bool */
+ protected $noerror = true; // Keep status of any error.
+
+ /**
+ * preview constructor.
+ *
+ * @param \csv_import_reader $cir
+ * @param array $filecolumns
+ * @param int $previewrows
+ * @throws \coding_exception
+ */
+ public function __construct(\csv_import_reader $cir, array $filecolumns, int $previewrows) {
+ parent::__construct();
+ $this->cir = $cir;
+ $this->filecolumns = $filecolumns;
+ $this->previewrows = $previewrows;
+
+ $this->id = "uupreview";
+ $this->attributes['class'] = 'generaltable';
+ $this->tablealign = 'center';
+ $this->summary = get_string('uploaduserspreview', 'tool_uploaduser');
+ $this->head = array();
+ $this->data = $this->read_data();
+
+ $this->head[] = get_string('uucsvline', 'tool_uploaduser');
+ foreach ($filecolumns as $column) {
+ $this->head[] = $column;
+ }
+ $this->head[] = get_string('status');
+
+ }
+
+ /**
+ * Read data
+ *
+ * @return array
+ * @throws \coding_exception
+ * @throws \dml_exception
+ * @throws \moodle_exception
+ */
+ protected function read_data() {
+ global $DB, $CFG;
+
+ $data = array();
+ $this->cir->init();
+ $linenum = 1; // Column header is first line.
+ while ($linenum <= $this->previewrows and $fields = $this->cir->next()) {
+ $linenum++;
+ $rowcols = array();
+ $rowcols['line'] = $linenum;
+ foreach ($fields as $key => $field) {
+ $rowcols[$this->filecolumns[$key]] = s(trim($field));
+ }
+ $rowcols['status'] = array();
+
+ if (isset($rowcols['username'])) {
+ $stdusername = \core_user::clean_field($rowcols['username'], 'username');
+ if ($rowcols['username'] !== $stdusername) {
+ $rowcols['status'][] = get_string('invalidusernameupload');
+ }
+ if ($userid = $DB->get_field('user', 'id',
+ ['username' => $stdusername, 'mnethostid' => $CFG->mnet_localhost_id])) {
+ $rowcols['username'] = \html_writer::link(
+ new \moodle_url('/user/profile.php', ['id' => $userid]), $rowcols['username']);
+ }
+ } else {
+ $rowcols['status'][] = get_string('missingusername');
+ }
+
+ if (isset($rowcols['email'])) {
+ if (!validate_email($rowcols['email'])) {
+ $rowcols['status'][] = get_string('invalidemail');
+ }
+
+ $select = $DB->sql_like('email', ':email', false, true, false, '|');
+ $params = array('email' => $DB->sql_like_escape($rowcols['email'], '|'));
+ if ($DB->record_exists_select('user', $select , $params)) {
+ $rowcols['status'][] = get_string('useremailduplicate', 'error');
+ }
+ }
+
+ if (isset($rowcols['theme'])) {
+ list($status, $message) = field_value_validators::validate_theme($rowcols['theme']);
+ if ($status !== 'normal' && !empty($message)) {
+ $rowcols['status'][] = $message;
+ }
+ }
+
+ // Check if rowcols have custom profile field with correct data and update error state.
+ $this->noerror = uu_check_custom_profile_data($rowcols) && $this->noerror;
+ $rowcols['status'] = implode('
', $rowcols['status']);
+ $data[] = $rowcols;
+ }
+ if ($fields = $this->cir->next()) {
+ $data[] = array_fill(0, count($fields) + 2, '...');
+ }
+ $this->cir->close();
+
+ return $data;
+ }
+
+ /**
+ * Getter for noerror
+ *
+ * @return bool
+ */
+ public function get_no_error() {
+ return $this->noerror;
+ }
+}
\ No newline at end of file
diff --git a/admin/tool/uploaduser/classes/process.php b/admin/tool/uploaduser/classes/process.php
new file mode 100644
index 00000000000..12c21011732
--- /dev/null
+++ b/admin/tool/uploaduser/classes/process.php
@@ -0,0 +1,1327 @@
+.
+
+/**
+ * Class process
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Moodle
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_uploaduser;
+
+defined('MOODLE_INTERNAL') || die();
+
+use tool_uploaduser\local\field_value_validators;
+
+require_once($CFG->dirroot.'/user/profile/lib.php');
+require_once($CFG->dirroot.'/user/lib.php');
+require_once($CFG->dirroot.'/group/lib.php');
+require_once($CFG->dirroot.'/cohort/lib.php');
+require_once($CFG->libdir.'/csvlib.class.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+
+/**
+ * Process CSV file with users data, this will create/update users, enrol them into courses, etc
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Moodle
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class process {
+
+ /** @var \csv_import_reader */
+ protected $cir;
+ /** @var \stdClass */
+ protected $formdata;
+ /** @var \uu_progress_tracker */
+ protected $upt;
+ /** @var array */
+ protected $filecolumns = null;
+ /** @var int */
+ protected $today;
+ /** @var \enrol_plugin|null */
+ protected $manualenrol = null;
+ /** @var array */
+ protected $standardfields = [];
+ /** @var array */
+ protected $profilefields = [];
+ /** @var array */
+ protected $allprofilefields = [];
+ /** @var string|\uu_progress_tracker|null */
+ protected $progresstrackerclass = null;
+
+ /** @var int */
+ protected $usersnew = 0;
+ /** @var int */
+ protected $usersupdated = 0;
+ /** @var int /not printed yet anywhere */
+ protected $usersuptodate = 0;
+ /** @var int */
+ protected $userserrors = 0;
+ /** @var int */
+ protected $deletes = 0;
+ /** @var int */
+ protected $deleteerrors = 0;
+ /** @var int */
+ protected $renames = 0;
+ /** @var int */
+ protected $renameerrors = 0;
+ /** @var int */
+ protected $usersskipped = 0;
+ /** @var int */
+ protected $weakpasswords = 0;
+
+ /** @var array course cache - do not fetch all courses here, we will not probably use them all anyway */
+ protected $ccache = [];
+ /** @var array */
+ protected $cohorts = [];
+ /** @var array Course roles lookup cache. */
+ protected $rolecache = [];
+ /** @var array System roles lookup cache. */
+ protected $sysrolecache = [];
+ /** @var array cache of used manual enrol plugins in each course */
+ protected $manualcache = [];
+ /** @var array officially supported plugins that are enabled */
+ protected $supportedauths = [];
+
+ /**
+ * process constructor.
+ *
+ * @param \csv_import_reader $cir
+ * @param string|null $progresstrackerclass
+ * @throws \coding_exception
+ */
+ public function __construct(\csv_import_reader $cir, string $progresstrackerclass = null) {
+ $this->cir = $cir;
+ if ($progresstrackerclass) {
+ if (!class_exists($progresstrackerclass) || !is_subclass_of($progresstrackerclass, \uu_progress_tracker::class)) {
+ throw new \coding_exception('Progress tracker class must extend \uu_progress_tracker');
+ }
+ $this->progresstrackerclass = $progresstrackerclass;
+ } else {
+ $this->progresstrackerclass = \uu_progress_tracker::class;
+ }
+
+ // Keep timestamp consistent.
+ $today = time();
+ $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
+ $this->today = $today;
+
+ $this->rolecache = uu_allowed_roles_cache(); // Course roles lookup cache.
+ $this->sysrolecache = uu_allowed_sysroles_cache(); // System roles lookup cache.
+ $this->supportedauths = uu_supported_auths(); // Officially supported plugins that are enabled.
+
+ if (enrol_is_enabled('manual')) {
+ // We use only manual enrol plugin here, if it is disabled no enrol is done.
+ $this->manualenrol = enrol_get_plugin('manual');
+ }
+
+ $this->find_profile_fields();
+ $this->find_standard_fields();
+ }
+
+ /**
+ * Standard user fields.
+ */
+ protected function find_standard_fields(): void {
+ $this->standardfields = array('id', 'username', 'email', 'emailstop',
+ 'city', 'country', 'lang', 'timezone', 'mailformat',
+ 'maildisplay', 'maildigest', 'htmleditor', 'autosubscribe',
+ 'institution', 'department', 'idnumber', 'skype',
+ 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
+ 'url', 'description', 'descriptionformat', 'password',
+ 'auth', // Watch out when changing auth type or using external auth plugins!
+ 'oldusername', // Use when renaming users - this is the original username.
+ 'suspended', // 1 means suspend user account, 0 means activate user account, nothing means keep as is.
+ 'theme', // Define a theme for user when 'allowuserthemes' is enabled.
+ 'deleted', // 1 means delete user
+ 'mnethostid', // Can not be used for adding, updating or deleting of users - only for enrolments,
+ // groups, cohorts and suspending.
+ 'interests',
+ );
+ // Include all name fields.
+ $this->standardfields = array_merge($this->standardfields, get_all_user_name_fields());
+ }
+
+ /**
+ * Profile fields
+ */
+ protected function find_profile_fields(): void {
+ global $DB;
+ $this->allprofilefields = $DB->get_records('user_info_field');
+ $this->profilefields = [];
+ if ($proffields = $this->allprofilefields) {
+ foreach ($proffields as $key => $proffield) {
+ $profilefieldname = 'profile_field_'.$proffield->shortname;
+ $this->profilefields[] = $profilefieldname;
+ // Re-index $proffields with key as shortname. This will be
+ // used while checking if profile data is key and needs to be converted (eg. menu profile field).
+ $proffields[$profilefieldname] = $proffield;
+ unset($proffields[$key]);
+ }
+ $this->allprofilefields = $proffields;
+ }
+ }
+
+ /**
+ * Returns the list of columns in the file
+ *
+ * @return array
+ */
+ public function get_file_columns(): array {
+ if ($this->filecolumns === null) {
+ $returnurl = new \moodle_url('/admin/tool/uploaduser/index.php');
+ $this->filecolumns = uu_validate_user_upload_columns($this->cir,
+ $this->standardfields, $this->profilefields, $returnurl);
+ }
+ return $this->filecolumns;
+ }
+
+ /**
+ * Set data from the form (or from CLI options)
+ *
+ * @param \stdClass $formdata
+ */
+ public function set_form_data(\stdClass $formdata): void {
+ global $SESSION;
+ $this->formdata = $formdata;
+
+ // Clear bulk selection.
+ if ($this->get_bulk()) {
+ $SESSION->bulk_users = array();
+ }
+ }
+
+ /**
+ * Operation type
+ * @return int
+ */
+ protected function get_operation_type(): int {
+ return (int)$this->formdata->uutype;
+ }
+
+ /**
+ * Setting to allow deletes
+ * @return bool
+ */
+ protected function get_allow_deletes(): bool {
+ $optype = $this->get_operation_type();
+ return (!empty($this->formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
+ }
+
+ /**
+ * Setting to allow deletes
+ * @return bool
+ */
+ protected function get_allow_renames(): bool {
+ $optype = $this->get_operation_type();
+ return (!empty($this->formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
+ }
+
+ /**
+ * Setting to select for bulk actions (not available in CLI)
+ * @return bool
+ */
+ public function get_bulk(): bool {
+ return $this->formdata->uubulk ?? false;
+ }
+
+ /**
+ * Setting for update type
+ * @return int
+ */
+ protected function get_update_type(): int {
+ return isset($this->formdata->uuupdatetype) ? $this->formdata->uuupdatetype : 0;
+ }
+
+ /**
+ * Setting to allow update passwords
+ * @return bool
+ */
+ protected function get_update_passwords(): bool {
+ return !empty($this->formdata->uupasswordold)
+ and $this->get_operation_type() != UU_USER_ADDNEW
+ and $this->get_operation_type() != UU_USER_ADDINC
+ and ($this->get_update_type() == UU_UPDATE_FILEOVERRIDE or $this->get_update_type() == UU_UPDATE_ALLOVERRIDE);
+ }
+
+ /**
+ * Setting to allow email duplicates
+ * @return bool
+ */
+ protected function get_allow_email_duplicates(): bool {
+ global $CFG;
+ return !(empty($CFG->allowaccountssameemail) ? 1 : $this->formdata->uunoemailduplicates);
+ }
+
+ /**
+ * Setting for reset password
+ * @return int UU_PWRESET_NONE, UU_PWRESET_WEAK, UU_PWRESET_ALL
+ */
+ protected function get_reset_passwords(): int {
+ return isset($this->formdata->uuforcepasswordchange) ? $this->formdata->uuforcepasswordchange : UU_PWRESET_NONE;
+ }
+
+ /**
+ * Setting to allow create passwords
+ * @return bool
+ */
+ protected function get_create_paswords(): bool {
+ return (!empty($this->formdata->uupasswordnew) and $this->get_operation_type() != UU_USER_UPDATE);
+ }
+
+ /**
+ * Setting to allow suspends
+ * @return bool
+ */
+ protected function get_allow_suspends(): bool {
+ return !empty($this->formdata->uuallowsuspends);
+ }
+
+ /**
+ * Setting to normalise user names
+ * @return bool
+ */
+ protected function get_normalise_user_names(): bool {
+ return !empty($this->formdata->uustandardusernames);
+ }
+
+ /**
+ * Helper method to return Yes/No string
+ *
+ * @param bool $value
+ * @return string
+ */
+ protected function get_string_yes_no($value): string {
+ return $value ? get_string('yes') : get_string('no');
+ }
+
+ /**
+ * Process the CSV file
+ */
+ public function process() {
+ // Init csv import helper.
+ $this->cir->init();
+
+ $classname = $this->progresstrackerclass;
+ $this->upt = new $classname();
+ $this->upt->start(); // Start table.
+
+ $linenum = 1; // Column header is first line.
+ while ($line = $this->cir->next()) {
+ $this->upt->flush();
+ $linenum++;
+
+ $this->upt->track('line', $linenum);
+ $this->process_line($line);
+ }
+
+ $this->upt->close(); // Close table.
+ $this->cir->close();
+ $this->cir->cleanup(true);
+ }
+
+ /**
+ * Prepare one line from CSV file as a user record
+ *
+ * @param array $line
+ * @return \stdClass|null
+ */
+ protected function prepare_user_record(array $line): ?\stdClass {
+ global $CFG, $USER;
+
+ $user = new \stdClass();
+
+ // Add fields to user object.
+ foreach ($line as $keynum => $value) {
+ if (!isset($this->get_file_columns()[$keynum])) {
+ // This should not happen.
+ continue;
+ }
+ $key = $this->get_file_columns()[$keynum];
+ if (strpos($key, 'profile_field_') === 0) {
+ // NOTE: bloody mega hack alert!!
+ if (isset($USER->$key) and is_array($USER->$key)) {
+ // This must be some hacky field that is abusing arrays to store content and format.
+ $user->$key = array();
+ $user->{$key['text']} = $value;
+ $user->{$key['format']} = FORMAT_MOODLE;
+ } else {
+ $user->$key = trim($value);
+ }
+ } else {
+ $user->$key = trim($value);
+ }
+
+ if (in_array($key, $this->upt->columns)) {
+ // Default value in progress tracking table, can be changed later.
+ $this->upt->track($key, s($value), 'normal');
+ }
+ }
+ if (!isset($user->username)) {
+ // Prevent warnings below.
+ $user->username = '';
+ }
+
+ if ($this->get_operation_type() == UU_USER_ADDNEW or $this->get_operation_type() == UU_USER_ADDINC) {
+ // User creation is a special case - the username may be constructed from templates using firstname and lastname
+ // better never try this in mixed update types.
+ $error = false;
+ if (!isset($user->firstname) or $user->firstname === '') {
+ $this->upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
+ $this->upt->track('firstname', get_string('error'), 'error');
+ $error = true;
+ }
+ if (!isset($user->lastname) or $user->lastname === '') {
+ $this->upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
+ $this->upt->track('lastname', get_string('error'), 'error');
+ $error = true;
+ }
+ if ($error) {
+ $this->userserrors++;
+ return null;
+ }
+ // We require username too - we might use template for it though.
+ if (empty($user->username) and !empty($this->formdata->username)) {
+ $user->username = uu_process_template($this->formdata->username, $user);
+ $this->upt->track('username', s($user->username));
+ }
+ }
+
+ // Normalize username.
+ $user->originalusername = $user->username;
+ if ($this->get_normalise_user_names()) {
+ $user->username = \core_user::clean_field($user->username, 'username');
+ }
+
+ // Make sure we really have username.
+ if (empty($user->username)) {
+ $this->upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
+ $this->upt->track('username', get_string('error'), 'error');
+ $this->userserrors++;
+ return null;
+ } else if ($user->username === 'guest') {
+ $this->upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
+ $this->userserrors++;
+ return null;
+ }
+
+ if ($user->username !== \core_user::clean_field($user->username, 'username')) {
+ $this->upt->track('status', get_string('invalidusername', 'error', 'username'), 'error');
+ $this->upt->track('username', get_string('error'), 'error');
+ $this->userserrors++;
+ }
+
+ if (empty($user->mnethostid)) {
+ $user->mnethostid = $CFG->mnet_localhost_id;
+ }
+
+ return $user;
+ }
+
+ /**
+ * Process one line from CSV file
+ *
+ * @param array $line
+ * @throws \coding_exception
+ * @throws \dml_exception
+ * @throws \moodle_exception
+ */
+ public function process_line(array $line) {
+ global $DB, $CFG, $SESSION;
+
+ if (!$user = $this->prepare_user_record($line)) {
+ return;
+ }
+
+ if ($existinguser = $DB->get_record('user', ['username' => $user->username, 'mnethostid' => $user->mnethostid])) {
+ $this->upt->track('id', $existinguser->id, 'normal', false);
+ }
+
+ if ($user->mnethostid == $CFG->mnet_localhost_id) {
+ $remoteuser = false;
+
+ // Find out if username incrementing required.
+ if ($existinguser and $this->get_operation_type() == UU_USER_ADDINC) {
+ $user->username = uu_increment_username($user->username);
+ $existinguser = false;
+ }
+
+ } else {
+ if (!$existinguser or $this->get_operation_type() == UU_USER_ADDINC) {
+ $this->upt->track('status', get_string('errormnetadd', 'tool_uploaduser'), 'error');
+ $this->userserrors++;
+ return;
+ }
+
+ $remoteuser = true;
+
+ // Make sure there are no changes of existing fields except the suspended status.
+ foreach ((array)$existinguser as $k => $v) {
+ if ($k === 'suspended') {
+ continue;
+ }
+ if (property_exists($user, $k)) {
+ $user->$k = $v;
+ }
+ if (in_array($k, $this->upt->columns)) {
+ if ($k === 'password' or $k === 'oldusername' or $k === 'deleted') {
+ $this->upt->track($k, '', 'normal', false);
+ } else {
+ $this->upt->track($k, s($v), 'normal', false);
+ }
+ }
+ }
+ unset($user->oldusername);
+ unset($user->password);
+ $user->auth = $existinguser->auth;
+ }
+
+ // Notify about nay username changes.
+ if ($user->originalusername !== $user->username) {
+ $this->upt->track('username', '', 'normal', false); // Clear previous.
+ $this->upt->track('username', s($user->originalusername).'-->'.s($user->username), 'info');
+ } else {
+ $this->upt->track('username', s($user->username), 'normal', false);
+ }
+ unset($user->originalusername);
+
+ // Verify if the theme is valid and allowed to be set.
+ if (isset($user->theme)) {
+ list($status, $message) = field_value_validators::validate_theme($user->theme);
+ if ($status !== 'normal' && !empty($message)) {
+ $this->upt->track('status', $message, $status);
+ // Unset the theme when validation fails.
+ unset($user->theme);
+ }
+ }
+
+ // Add default values for remaining fields.
+ $formdefaults = array();
+ if (!$existinguser ||
+ ($this->get_update_type() != UU_UPDATE_FILEOVERRIDE && $this->get_update_type() != UU_UPDATE_NOCHANGES)) {
+ foreach ($this->standardfields as $field) {
+ if (isset($user->$field)) {
+ continue;
+ }
+ // All validation moved to form2.
+ if (isset($this->formdata->$field)) {
+ // Process templates.
+ $user->$field = uu_process_template($this->formdata->$field, $user);
+ $formdefaults[$field] = true;
+ if (in_array($field, $this->upt->columns)) {
+ $this->upt->track($field, s($user->$field), 'normal');
+ }
+ }
+ }
+ $proffields = $this->allprofilefields;
+ foreach ($this->profilefields as $field) {
+ if (isset($user->$field)) {
+ continue;
+ }
+ if (isset($this->formdata->$field)) {
+ // Process templates.
+ $user->$field = uu_process_template($this->formdata->$field, $user);
+
+ // Form contains key and later code expects value.
+ // Convert key to value for required profile fields.
+ require_once($CFG->dirroot.'/user/profile/field/'.$proffields[$field]->datatype.'/field.class.php');
+ $profilefieldclass = 'profile_field_'.$proffields[$field]->datatype;
+ $profilefield = new $profilefieldclass($proffields[$field]->id);
+ if (method_exists($profilefield, 'convert_external_data')) {
+ $user->$field = $profilefield->edit_save_data_preprocess($user->$field, null);
+ }
+
+ $formdefaults[$field] = true;
+ }
+ }
+ }
+
+ // Delete user.
+ if (!empty($user->deleted)) {
+ if (!$this->get_allow_deletes() or $remoteuser) {
+ $this->usersskipped++;
+ $this->upt->track('status', get_string('usernotdeletedoff', 'error'), 'warning');
+ return;
+ }
+ if ($existinguser) {
+ if (is_siteadmin($existinguser->id)) {
+ $this->upt->track('status', get_string('usernotdeletedadmin', 'error'), 'error');
+ $this->deleteerrors++;
+ return;
+ }
+ if (delete_user($existinguser)) {
+ $this->upt->track('status', get_string('userdeleted', 'tool_uploaduser'));
+ $this->deletes++;
+ } else {
+ $this->upt->track('status', get_string('usernotdeletederror', 'error'), 'error');
+ $this->deleteerrors++;
+ }
+ } else {
+ $this->upt->track('status', get_string('usernotdeletedmissing', 'error'), 'error');
+ $this->deleteerrors++;
+ }
+ return;
+ }
+ // We do not need the deleted flag anymore.
+ unset($user->deleted);
+
+ // Renaming requested?
+ if (!empty($user->oldusername) ) {
+ if (!$this->get_allow_renames()) {
+ $this->usersskipped++;
+ $this->upt->track('status', get_string('usernotrenamedoff', 'error'), 'warning');
+ return;
+ }
+
+ if ($existinguser) {
+ $this->upt->track('status', get_string('usernotrenamedexists', 'error'), 'error');
+ $this->renameerrors++;
+ return;
+ }
+
+ if ($user->username === 'guest') {
+ $this->upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
+ $this->renameerrors++;
+ return;
+ }
+
+ if ($this->get_normalise_user_names()) {
+ $oldusername = \core_user::clean_field($user->oldusername, 'username');
+ } else {
+ $oldusername = $user->oldusername;
+ }
+
+ // No guessing when looking for old username, it must be exact match.
+ if ($olduser = $DB->get_record('user',
+ ['username' => $oldusername, 'mnethostid' => $CFG->mnet_localhost_id])) {
+ $this->upt->track('id', $olduser->id, 'normal', false);
+ if (is_siteadmin($olduser->id)) {
+ $this->upt->track('status', get_string('usernotrenamedadmin', 'error'), 'error');
+ $this->renameerrors++;
+ return;
+ }
+ $DB->set_field('user', 'username', $user->username, ['id' => $olduser->id]);
+ $this->upt->track('username', '', 'normal', false); // Clear previous.
+ $this->upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
+ $this->upt->track('status', get_string('userrenamed', 'tool_uploaduser'));
+ $this->renames++;
+ } else {
+ $this->upt->track('status', get_string('usernotrenamedmissing', 'error'), 'error');
+ $this->renameerrors++;
+ return;
+ }
+ $existinguser = $olduser;
+ $existinguser->username = $user->username;
+ }
+
+ // Can we process with update or insert?
+ $skip = false;
+ switch ($this->get_operation_type()) {
+ case UU_USER_ADDNEW:
+ if ($existinguser) {
+ $this->usersskipped++;
+ $this->upt->track('status', get_string('usernotaddedregistered', 'error'), 'warning');
+ $skip = true;
+ }
+ break;
+
+ case UU_USER_ADDINC:
+ if ($existinguser) {
+ // This should not happen!
+ $this->upt->track('status', get_string('usernotaddederror', 'error'), 'error');
+ $this->userserrors++;
+ $skip = true;
+ }
+ break;
+
+ case UU_USER_ADD_UPDATE:
+ break;
+
+ case UU_USER_UPDATE:
+ if (!$existinguser) {
+ $this->usersskipped++;
+ $this->upt->track('status', get_string('usernotupdatednotexists', 'error'), 'warning');
+ $skip = true;
+ }
+ break;
+
+ default:
+ // Unknown type.
+ $skip = true;
+ }
+
+ if ($skip) {
+ return;
+ }
+
+ if ($existinguser) {
+ $user->id = $existinguser->id;
+
+ $this->upt->track('username', \html_writer::link(
+ new \moodle_url('/user/profile.php', ['id' => $existinguser->id]), s($existinguser->username)), 'normal', false);
+ $this->upt->track('suspended', $this->get_string_yes_no($existinguser->suspended) , 'normal', false);
+ $this->upt->track('auth', $existinguser->auth, 'normal', false);
+
+ if (is_siteadmin($user->id)) {
+ $this->upt->track('status', get_string('usernotupdatedadmin', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ }
+
+ $existinguser->timemodified = time();
+ // Do NOT mess with timecreated or firstaccess here!
+
+ // Load existing profile data.
+ profile_load_data($existinguser);
+
+ $doupdate = false;
+ $dologout = false;
+
+ if ($this->get_update_type() != UU_UPDATE_NOCHANGES and !$remoteuser) {
+ if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
+ $this->upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
+ $existinguser->auth = $user->auth;
+ if (!isset($this->supportedauths[$user->auth])) {
+ $this->upt->track('auth', get_string('userauthunsupported', 'error'), 'warning');
+ }
+ $doupdate = true;
+ if ($existinguser->auth === 'nologin') {
+ $dologout = true;
+ }
+ }
+ $allcolumns = array_merge($this->standardfields, $this->profilefields);
+ foreach ($allcolumns as $column) {
+ if ($column === 'username' or $column === 'password' or $column === 'auth' or $column === 'suspended') {
+ // These can not be changed here.
+ continue;
+ }
+ if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
+ continue;
+ }
+ if ($this->get_update_type() == UU_UPDATE_MISSING) {
+ if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
+ continue;
+ }
+ } else if ($this->get_update_type() == UU_UPDATE_ALLOVERRIDE) {
+ // We override everything.
+ null;
+ } else if ($this->get_update_type() == UU_UPDATE_FILEOVERRIDE) {
+ if (!empty($formdefaults[$column])) {
+ // Do not override with form defaults.
+ continue;
+ }
+ }
+ if ($existinguser->$column !== $user->$column) {
+ if ($column === 'email') {
+ $select = $DB->sql_like('email', ':email', false, true, false, '|');
+ $params = array('email' => $DB->sql_like_escape($user->email, '|'));
+ if ($DB->record_exists_select('user', $select , $params)) {
+
+ $changeincase = \core_text::strtolower($existinguser->$column) === \core_text::strtolower(
+ $user->$column);
+
+ if ($changeincase) {
+ // If only case is different then switch to lower case and carry on.
+ $user->$column = \core_text::strtolower($user->$column);
+ continue;
+ } else if (!$this->get_allow_email_duplicates()) {
+ $this->upt->track('email', get_string('useremailduplicate', 'error'), 'error');
+ $this->upt->track('status', get_string('usernotupdatederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ } else {
+ $this->upt->track('email', get_string('useremailduplicate', 'error'), 'warning');
+ }
+ }
+ if (!validate_email($user->email)) {
+ $this->upt->track('email', get_string('invalidemail'), 'warning');
+ }
+ }
+
+ if ($column === 'lang') {
+ if (empty($user->lang)) {
+ // Do not change to not-set value.
+ continue;
+ } else if (\core_user::clean_field($user->lang, 'lang') === '') {
+ $this->upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
+ continue;
+ }
+ }
+
+ if (in_array($column, $this->upt->columns)) {
+ $this->upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
+ }
+ $existinguser->$column = $user->$column;
+ $doupdate = true;
+ }
+ }
+ }
+
+ try {
+ $auth = get_auth_plugin($existinguser->auth);
+ } catch (\Exception $e) {
+ $this->upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
+ $this->upt->track('status', get_string('usernotupdatederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ }
+ $isinternalauth = $auth->is_internal();
+
+ // Deal with suspending and activating of accounts.
+ if ($this->get_allow_suspends() and isset($user->suspended) and $user->suspended !== '') {
+ $user->suspended = $user->suspended ? 1 : 0;
+ if ($existinguser->suspended != $user->suspended) {
+ $this->upt->track('suspended', '', 'normal', false);
+ $this->upt->track('suspended',
+ $this->get_string_yes_no($existinguser->suspended).'-->'.$this->get_string_yes_no($user->suspended),
+ 'info', false);
+ $existinguser->suspended = $user->suspended;
+ $doupdate = true;
+ if ($existinguser->suspended) {
+ $dologout = true;
+ }
+ }
+ }
+
+ // Changing of passwords is a special case
+ // do not force password changes for external auth plugins!
+ $oldpw = $existinguser->password;
+
+ if ($remoteuser) {
+ // Do not mess with passwords of remote users.
+ null;
+ } else if (!$isinternalauth) {
+ $existinguser->password = AUTH_PASSWORD_NOT_CACHED;
+ $this->upt->track('password', '-', 'normal', false);
+ // Clean up prefs.
+ unset_user_preference('create_password', $existinguser);
+ unset_user_preference('auth_forcepasswordchange', $existinguser);
+
+ } else if (!empty($user->password)) {
+ if ($this->get_update_passwords()) {
+ // Check for passwords that we want to force users to reset next
+ // time they log in.
+ $errmsg = null;
+ $weak = !check_password_policy($user->password, $errmsg, $user);
+ if ($this->get_reset_passwords() == UU_PWRESET_ALL or
+ ($this->get_reset_passwords() == UU_PWRESET_WEAK and $weak)) {
+ if ($weak) {
+ $this->weakpasswords++;
+ $this->upt->track('password', get_string('invalidpasswordpolicy', 'error'), 'warning');
+ }
+ set_user_preference('auth_forcepasswordchange', 1, $existinguser);
+ } else {
+ unset_user_preference('auth_forcepasswordchange', $existinguser);
+ }
+ unset_user_preference('create_password', $existinguser); // No need to create password any more.
+
+ // 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.
+ $existinguser->password = hash_internal_user_password($user->password, true);
+ $this->upt->track('password', $user->password, 'normal', false);
+ } else {
+ // Do not print password when not changed.
+ $this->upt->track('password', '', 'normal', false);
+ }
+ }
+
+ if ($doupdate or $existinguser->password !== $oldpw) {
+ // We want only users that were really updated.
+ user_update_user($existinguser, false, false);
+
+ $this->upt->track('status', get_string('useraccountupdated', 'tool_uploaduser'));
+ $this->usersupdated++;
+
+ if (!$remoteuser) {
+ // Pre-process custom profile menu fields data from csv file.
+ $existinguser = uu_pre_process_custom_profile_data($existinguser);
+ // Save custom profile fields data from csv file.
+ profile_save_data($existinguser);
+ }
+
+ if ($this->get_bulk() == UU_BULK_UPDATED or $this->get_bulk() == UU_BULK_ALL) {
+ if (!in_array($user->id, $SESSION->bulk_users)) {
+ $SESSION->bulk_users[] = $user->id;
+ }
+ }
+
+ // Trigger event.
+ \core\event\user_updated::create_from_userid($existinguser->id)->trigger();
+
+ } else {
+ // No user information changed.
+ $this->upt->track('status', get_string('useraccountuptodate', 'tool_uploaduser'));
+ $this->usersuptodate++;
+
+ if ($this->get_bulk() == UU_BULK_ALL) {
+ if (!in_array($user->id, $SESSION->bulk_users)) {
+ $SESSION->bulk_users[] = $user->id;
+ }
+ }
+ }
+
+ if ($dologout) {
+ \core\session\manager::kill_user_sessions($existinguser->id);
+ }
+
+ } else {
+ // Save the new user to the database.
+ $user->confirmed = 1;
+ $user->timemodified = time();
+ $user->timecreated = time();
+ $user->mnethostid = $CFG->mnet_localhost_id; // We support ONLY local accounts here, sorry.
+
+ if (!isset($user->suspended) or $user->suspended === '') {
+ $user->suspended = 0;
+ } else {
+ $user->suspended = $user->suspended ? 1 : 0;
+ }
+ $this->upt->track('suspended', $this->get_string_yes_no($user->suspended), 'normal', false);
+
+ if (empty($user->auth)) {
+ $user->auth = 'manual';
+ }
+ $this->upt->track('auth', $user->auth, 'normal', false);
+
+ // Do not insert record if new auth plugin does not exist!
+ try {
+ $auth = get_auth_plugin($user->auth);
+ } catch (\Exception $e) {
+ $this->upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
+ $this->upt->track('status', get_string('usernotaddederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ }
+ if (!isset($this->supportedauths[$user->auth])) {
+ $this->upt->track('auth', get_string('userauthunsupported', 'error'), 'warning');
+ }
+
+ $isinternalauth = $auth->is_internal();
+
+ if (empty($user->email)) {
+ $this->upt->track('email', get_string('invalidemail'), 'error');
+ $this->upt->track('status', get_string('usernotaddederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+
+ } else if ($DB->record_exists('user', ['email' => $user->email])) {
+ if (!$this->get_allow_email_duplicates()) {
+ $this->upt->track('email', get_string('useremailduplicate', 'error'), 'error');
+ $this->upt->track('status', get_string('usernotaddederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ } else {
+ $this->upt->track('email', get_string('useremailduplicate', 'error'), 'warning');
+ }
+ }
+ if (!validate_email($user->email)) {
+ $this->upt->track('email', get_string('invalidemail'), 'warning');
+ }
+
+ if (empty($user->lang)) {
+ $user->lang = '';
+ } else if (\core_user::clean_field($user->lang, 'lang') === '') {
+ $this->upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
+ $user->lang = '';
+ }
+
+ $forcechangepassword = false;
+
+ if ($isinternalauth) {
+ if (empty($user->password)) {
+ if ($this->get_create_paswords()) {
+ $user->password = 'to be generated';
+ $this->upt->track('password', '', 'normal', false);
+ $this->upt->track('password', get_string('uupasswordcron', 'tool_uploaduser'), 'warning', false);
+ } else {
+ $this->upt->track('password', '', 'normal', false);
+ $this->upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
+ $this->upt->track('status', get_string('usernotaddederror', 'error'), 'error');
+ $this->userserrors++;
+ return;
+ }
+ } else {
+ $errmsg = null;
+ $weak = !check_password_policy($user->password, $errmsg, $user);
+ if ($this->get_reset_passwords() == UU_PWRESET_ALL or
+ ($this->get_reset_passwords() == UU_PWRESET_WEAK and $weak)) {
+ if ($weak) {
+ $this->weakpasswords++;
+ $this->upt->track('password', get_string('invalidpasswordpolicy', 'error'), '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;
+ $this->upt->track('password', '-', 'normal', false);
+ }
+
+ $user->id = user_create_user($user, false, false);
+ $this->upt->track('username', \html_writer::link(
+ new \moodle_url('/user/profile.php', ['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();
+
+ $this->upt->track('status', get_string('newuser'));
+ $this->upt->track('id', $user->id, 'normal', false);
+ $this->usersnew++;
+
+ // Make sure user context exists.
+ \context_user::instance($user->id);
+
+ if ($this->get_bulk() == UU_BULK_NEW or $this->get_bulk() == UU_BULK_ALL) {
+ if (!in_array($user->id, $SESSION->bulk_users)) {
+ $SESSION->bulk_users[] = $user->id;
+ }
+ }
+ }
+
+ // Update user interests.
+ if (isset($user->interests) && strval($user->interests) !== '') {
+ useredit_update_interests($user, preg_split('/\s*,\s*/', $user->interests, -1, PREG_SPLIT_NO_EMPTY));
+ }
+
+ // Add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
+ foreach ($this->get_file_columns() as $column) {
+ if (!preg_match('/^cohort\d+$/', $column)) {
+ continue;
+ }
+
+ if (!empty($user->$column)) {
+ $addcohort = $user->$column;
+ if (!isset($this->cohorts[$addcohort])) {
+ if (is_number($addcohort)) {
+ // Only non-numeric idnumbers!
+ $cohort = $DB->get_record('cohort', ['id' => $addcohort]);
+ } else {
+ $cohort = $DB->get_record('cohort', ['idnumber' => $addcohort]);
+ if (empty($cohort) && has_capability('moodle/cohort:manage', \context_system::instance())) {
+ // Cohort was not found. Create a new one.
+ $cohortid = cohort_add_cohort((object)array(
+ 'idnumber' => $addcohort,
+ 'name' => $addcohort,
+ 'contextid' => \context_system::instance()->id
+ ));
+ $cohort = $DB->get_record('cohort', ['id' => $cohortid]);
+ }
+ }
+
+ if (empty($cohort)) {
+ $this->cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
+ } else if (!empty($cohort->component)) {
+ // Cohorts synchronised with external sources must not be modified!
+ $this->cohorts[$addcohort] = get_string('external', 'core_cohort');
+ } else {
+ $this->cohorts[$addcohort] = $cohort;
+ }
+ }
+
+ if (is_object($this->cohorts[$addcohort])) {
+ $cohort = $this->cohorts[$addcohort];
+ if (!$DB->record_exists('cohort_members', ['cohortid' => $cohort->id, 'userid' => $user->id])) {
+ cohort_add_member($cohort->id, $user->id);
+ // We might add special column later, for now let's abuse enrolments.
+ $this->upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)), 'info');
+ }
+ } else {
+ // Error message.
+ $this->upt->track('enrolments', $this->cohorts[$addcohort], 'error');
+ }
+ }
+ }
+
+ // Find course enrolments, groups, roles/types and enrol periods
+ // this is again a special case, we always do this for any updated or created users.
+ foreach ($this->get_file_columns() as $column) {
+ if (preg_match('/^sysrole\d+$/', $column)) {
+
+ if (!empty($user->$column)) {
+ $sysrolename = $user->$column;
+ if ($sysrolename[0] == '-') {
+ $removing = true;
+ $sysrolename = substr($sysrolename, 1);
+ } else {
+ $removing = false;
+ }
+
+ if (array_key_exists($sysrolename, $this->sysrolecache)) {
+ $sysroleid = $this->sysrolecache[$sysrolename]->id;
+ } else {
+ $this->upt->track('enrolments', get_string('unknownrole', 'error', s($sysrolename)), 'error');
+ continue;
+ }
+
+ if ($removing) {
+ if (user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
+ role_unassign($sysroleid, $user->id, SYSCONTEXTID);
+ $this->upt->track('enrolments', get_string('unassignedsysrole',
+ 'tool_uploaduser', $this->sysrolecache[$sysroleid]->name), 'info');
+ }
+ } else {
+ if (!user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
+ role_assign($sysroleid, $user->id, SYSCONTEXTID);
+ $this->upt->track('enrolments', get_string('assignedsysrole',
+ 'tool_uploaduser', $this->sysrolecache[$sysroleid]->name), 'info');
+ }
+ }
+ }
+
+ continue;
+ }
+ if (!preg_match('/^course\d+$/', $column)) {
+ continue;
+ }
+ $i = substr($column, 6);
+
+ if (empty($user->{'course'.$i})) {
+ continue;
+ }
+ $shortname = $user->{'course'.$i};
+ if (!array_key_exists($shortname, $this->ccache)) {
+ if (!$course = $DB->get_record('course', ['shortname' => $shortname], 'id, shortname')) {
+ $this->upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
+ continue;
+ }
+ $ccache[$shortname] = $course;
+ $ccache[$shortname]->groups = null;
+ }
+ $courseid = $ccache[$shortname]->id;
+ $coursecontext = \context_course::instance($courseid);
+ if (!isset($this->manualcache[$courseid])) {
+ $this->manualcache[$courseid] = false;
+ if ($this->manualenrol) {
+ if ($instances = enrol_get_instances($courseid, false)) {
+ foreach ($instances as $instance) {
+ if ($instance->enrol === 'manual') {
+ $this->manualcache[$courseid] = $instance;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if ($courseid == SITEID) {
+ // Technically frontpage does not have enrolments, but only role assignments,
+ // let's not invent new lang strings here for this rarely used feature.
+
+ if (!empty($user->{'role'.$i})) {
+ $rolename = $user->{'role'.$i};
+ if (array_key_exists($rolename, $this->rolecache)) {
+ $roleid = $this->rolecache[$rolename]->id;
+ } else {
+ $this->upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
+ continue;
+ }
+
+ role_assign($roleid, $user->id, \context_course::instance($courseid));
+
+ $a = new \stdClass();
+ $a->course = $shortname;
+ $a->role = $this->rolecache[$roleid]->name;
+ $this->upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a), 'info');
+ }
+
+ } else if ($this->manualenrol and $this->manualcache[$courseid]) {
+
+ // Find role.
+ $roleid = false;
+ if (!empty($user->{'role'.$i})) {
+ $rolename = $user->{'role'.$i};
+ if (array_key_exists($rolename, $this->rolecache)) {
+ $roleid = $this->rolecache[$rolename]->id;
+ } else {
+ $this->upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
+ continue;
+ }
+
+ } else if (!empty($user->{'type'.$i})) {
+ // If no role, then find "old" enrolment type.
+ $addtype = $user->{'type'.$i};
+ if ($addtype < 1 or $addtype > 3) {
+ $this->upt->track('enrolments', get_string('error').': typeN = 1|2|3', 'error');
+ continue;
+ } else if (empty($this->formdata->{'uulegacy'.$addtype})) {
+ continue;
+ } else {
+ $roleid = $this->formdata->{'uulegacy'.$addtype};
+ }
+ } else {
+ // No role specified, use the default from manual enrol plugin.
+ $roleid = $this->manualcache[$courseid]->roleid;
+ }
+
+ if ($roleid) {
+ // Find duration and/or enrol status.
+ $timeend = 0;
+ $timestart = $this->today;
+ $status = null;
+
+ if (isset($user->{'enrolstatus'.$i})) {
+ $enrolstatus = $user->{'enrolstatus'.$i};
+ if ($enrolstatus == '') {
+ $status = null;
+ } else if ($enrolstatus === (string)ENROL_USER_ACTIVE) {
+ $status = ENROL_USER_ACTIVE;
+ } else if ($enrolstatus === (string)ENROL_USER_SUSPENDED) {
+ $status = ENROL_USER_SUSPENDED;
+ } else {
+ debugging('Unknown enrolment status.');
+ }
+ }
+
+ if (!empty($user->{'enroltimestart'.$i})) {
+ $parsedtimestart = strtotime($user->{'enroltimestart'.$i});
+ if ($parsedtimestart !== false) {
+ $timestart = $parsedtimestart;
+ }
+ }
+
+ if (!empty($user->{'enrolperiod'.$i})) {
+ $duration = (int)$user->{'enrolperiod'.$i} * 60 * 60 * 24; // Convert days to seconds.
+ if ($duration > 0) { // Sanity check.
+ $timeend = $timestart + $duration;
+ }
+ } else if ($this->manualcache[$courseid]->enrolperiod > 0) {
+ $timeend = $timestart + $this->manualcache[$courseid]->enrolperiod;
+ }
+
+ $this->manualenrol->enrol_user($this->manualcache[$courseid], $user->id, $roleid,
+ $timestart, $timeend, $status);
+
+ $a = new \stdClass();
+ $a->course = $shortname;
+ $a->role = $this->rolecache[$roleid]->name;
+ $this->upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a), 'info');
+ }
+ }
+
+ // Find group to add to.
+ if (!empty($user->{'group'.$i})) {
+ // Make sure user is enrolled into course before adding into groups.
+ if (!is_enrolled($coursecontext, $user->id)) {
+ $this->upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
+ continue;
+ }
+ // Build group cache.
+ if (is_null($ccache[$shortname]->groups)) {
+ $ccache[$shortname]->groups = array();
+ if ($groups = groups_get_all_groups($courseid)) {
+ foreach ($groups as $gid => $group) {
+ $ccache[$shortname]->groups[$gid] = new \stdClass();
+ $ccache[$shortname]->groups[$gid]->id = $gid;
+ $ccache[$shortname]->groups[$gid]->name = $group->name;
+ if (!is_numeric($group->name)) { // Only non-numeric names are supported!!!
+ $ccache[$shortname]->groups[$group->name] = new \stdClass();
+ $ccache[$shortname]->groups[$group->name]->id = $gid;
+ $ccache[$shortname]->groups[$group->name]->name = $group->name;
+ }
+ }
+ }
+ }
+ // Group exists?
+ $addgroup = $user->{'group'.$i};
+ if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
+ // If group doesn't exist, create it.
+ $newgroupdata = new \stdClass();
+ $newgroupdata->name = $addgroup;
+ $newgroupdata->courseid = $ccache[$shortname]->id;
+ $newgroupdata->description = '';
+ $gid = groups_create_group($newgroupdata);
+ if ($gid) {
+ $ccache[$shortname]->groups[$addgroup] = new \stdClass();
+ $ccache[$shortname]->groups[$addgroup]->id = $gid;
+ $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
+ } else {
+ $this->upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
+ continue;
+ }
+ }
+ $gid = $ccache[$shortname]->groups[$addgroup]->id;
+ $gname = $ccache[$shortname]->groups[$addgroup]->name;
+
+ try {
+ if (groups_add_member($gid, $user->id)) {
+ $this->upt->track('enrolments', get_string('addedtogroup', '', s($gname)), 'info');
+ } else {
+ $this->upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
+ }
+ } catch (\moodle_exception $e) {
+ $this->upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
+ continue;
+ }
+ }
+ }
+ if (($invalid = \core_user::validate($user)) !== true) {
+ $this->upt->track('status', get_string('invaliduserdata', 'tool_uploaduser', s($user->username)), 'warning');
+ }
+ }
+
+ /**
+ * Summary about the whole process (how many users created, skipped, updated, etc)
+ *
+ * @return array
+ */
+ public function get_stats() {
+ $lines = [];
+
+ if ($this->get_operation_type() != UU_USER_UPDATE) {
+ $lines[] = get_string('userscreated', 'tool_uploaduser').': '.$this->usersnew;
+ }
+ if ($this->get_operation_type() == UU_USER_UPDATE or $this->get_operation_type() == UU_USER_ADD_UPDATE) {
+ $lines[] = get_string('usersupdated', 'tool_uploaduser').': '.$this->usersupdated;
+ }
+ if ($this->get_allow_deletes()) {
+ $lines[] = get_string('usersdeleted', 'tool_uploaduser').': '.$this->deletes;
+ $lines[] = get_string('deleteerrors', 'tool_uploaduser').': '.$this->deleteerrors;
+ }
+ if ($this->get_allow_renames()) {
+ $lines[] = get_string('usersrenamed', 'tool_uploaduser').': '.$this->renames;
+ $lines[] = get_string('renameerrors', 'tool_uploaduser').': '.$this->renameerrors;
+ }
+ if ($usersskipped = $this->usersskipped) {
+ $lines[] = get_string('usersskipped', 'tool_uploaduser').': '.$usersskipped;
+ }
+ $lines[] = get_string('usersweakpassword', 'tool_uploaduser').': '.$this->weakpasswords;
+ $lines[] = get_string('errors', 'tool_uploaduser').': '.$this->userserrors;
+
+ return $lines;
+ }
+}
diff --git a/admin/tool/uploaduser/cli/uploaduser.php b/admin/tool/uploaduser/cli/uploaduser.php
new file mode 100644
index 00000000000..5db9e0261b3
--- /dev/null
+++ b/admin/tool/uploaduser/cli/uploaduser.php
@@ -0,0 +1,53 @@
+.
+
+/**
+ * CLI script to upload users
+ *
+ * @package tool_uploaduser
+ * @copyright 2020 Marina Glancy
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('CLI_SCRIPT', true);
+
+require_once(__DIR__ . '/../../../../config.php');
+require_once($CFG->libdir . '/clilib.php');
+
+if (moodle_needs_upgrading()) {
+ cli_error("Moodle upgrade pending, export execution suspended.");
+}
+
+// Increase time and memory limit.
+core_php_time_limit::raise();
+raise_memory_limit(MEMORY_EXTRA);
+
+// Emulate normal session - we use admin account by default, set language to the site language.
+cron_setup_user();
+$USER->lang = $CFG->lang;
+
+$clihelper = new \tool_uploaduser\cli_helper();
+
+if ($clihelper->get_cli_option('help')) {
+ $clihelper->print_help();
+ die();
+}
+
+$clihelper->process();
+
+foreach ($clihelper->get_stats() as $line) {
+ cli_writeln($line);
+}
diff --git a/admin/tool/uploaduser/index.php b/admin/tool/uploaduser/index.php
index eb881f6c911..a0ef7ab16f4 100644
--- a/admin/tool/uploaduser/index.php
+++ b/admin/tool/uploaduser/index.php
@@ -26,95 +26,20 @@
require('../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/csvlib.class.php');
-require_once($CFG->dirroot.'/user/profile/lib.php');
-require_once($CFG->dirroot.'/user/lib.php');
-require_once($CFG->dirroot.'/group/lib.php');
-require_once($CFG->dirroot.'/cohort/lib.php');
-require_once('locallib.php');
-require_once('user_form.php');
-require_once('classes/local/field_value_validators.php');
-use tool_uploaduser\local\field_value_validators;
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/user_form.php');
$iid = optional_param('iid', '', PARAM_INT);
$previewrows = optional_param('previewrows', 10, PARAM_INT);
-core_php_time_limit::raise(60*60); // 1 hour should be enough
+core_php_time_limit::raise(60 * 60); // 1 hour should be enough.
raise_memory_limit(MEMORY_HUGE);
admin_externalpage_setup('tooluploaduser');
-require_capability('moodle/site:uploadusers', context_system::instance());
-
-$struserrenamed = get_string('userrenamed', 'tool_uploaduser');
-$strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
-$strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
-$strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
-$strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
-
-$struserupdated = get_string('useraccountupdated', 'tool_uploaduser');
-$strusernotupdated = get_string('usernotupdatederror', 'error');
-$strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
-$strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
-
-$struseruptodate = get_string('useraccountuptodate', 'tool_uploaduser');
-
-$struseradded = get_string('newuser');
-$strusernotadded = get_string('usernotaddedregistered', 'error');
-$strusernotaddederror = get_string('usernotaddederror', 'error');
-
-$struserdeleted = get_string('userdeleted', 'tool_uploaduser');
-$strusernotdeletederror = get_string('usernotdeletederror', 'error');
-$strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
-$strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
-$strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
-
-$strcannotassignrole = get_string('cannotassignrole', 'error');
-
-$struserauthunsupported = get_string('userauthunsupported', 'error');
-$stremailduplicate = get_string('useremailduplicate', 'error');
-
-$strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
-$errorstr = get_string('error');
-
-$stryes = get_string('yes');
-$strno = get_string('no');
-$stryesnooptions = array(0=>$strno, 1=>$stryes);
$returnurl = new moodle_url('/admin/tool/uploaduser/index.php');
$bulknurl = new moodle_url('/admin/user/user_bulk.php');
-$today = time();
-$today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
-
-// array of all valid fields for validation
-$STD_FIELDS = array('id', 'username', 'email', 'emailstop',
- 'city', 'country', 'lang', 'timezone', 'mailformat',
- 'maildisplay', 'maildigest', 'htmleditor', 'autosubscribe',
- 'institution', 'department', 'idnumber', 'skype',
- 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
- 'url', 'description', 'descriptionformat', 'password',
- 'auth', // watch out when changing auth type or using external auth plugins!
- 'oldusername', // use when renaming users - this is the original username
- 'suspended', // 1 means suspend user account, 0 means activate user account, nothing means keep as is for existing users
- 'theme', // Define a theme for user when 'allowuserthemes' is enabled.
- 'deleted', // 1 means delete user
- 'mnethostid', // Can not be used for adding, updating or deleting of users - only for enrolments, groups, cohorts and suspending.
- 'interests',
- );
-// Include all name fields.
-$STD_FIELDS = array_merge($STD_FIELDS, get_all_user_name_fields());
-
-$PRF_FIELDS = array();
-if ($proffields = $DB->get_records('user_info_field')) {
- foreach ($proffields as $key => $proffield) {
- $profilefieldname = 'profile_field_'.$proffield->shortname;
- $PRF_FIELDS[] = $profilefieldname;
- // Re-index $proffields with key as shortname. This will be
- // used while checking if profile data is key and needs to be converted (eg. menu profile field)
- $proffields[$profilefieldname] = $proffield;
- unset($proffields[$key]);
- }
-}
-
if (empty($iid)) {
$mform1 = new admin_uploaduser_form1();
@@ -131,9 +56,7 @@ if (empty($iid)) {
if (!is_null($csvloaderror)) {
print_error('csvloaderror', '', $returnurl, $csvloaderror);
}
- // test if columns ok
- $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
- // continue to form2
+ // Continue to form2.
} else {
echo $OUTPUT->header();
@@ -146,1033 +69,33 @@ if (empty($iid)) {
}
} else {
$cir = new csv_import_reader($iid, 'uploaduser');
- $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
}
-$mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
+// Test if columns ok.
+$process = new \tool_uploaduser\process($cir);
+$filecolumns = $process->get_file_columns();
-// If a file has been uploaded, then process it
+$mform2 = new admin_uploaduser_form2(null,
+ ['columns' => $filecolumns, 'data' => ['iid' => $iid, 'previewrows' => $previewrows]]);
+
+// If a file has been uploaded, then process it.
if ($formdata = $mform2->is_cancelled()) {
$cir->cleanup(true);
redirect($returnurl);
} else if ($formdata = $mform2->get_data()) {
- // Print the header
+ // Print the header.
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('uploadusersresult', 'tool_uploaduser'));
- $optype = $formdata->uutype;
-
- $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
- $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
- $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
- $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
- $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
- $allowsuspends = (!empty($formdata->uuallowsuspends));
- $bulk = $formdata->uubulk;
- $noemailduplicates = empty($CFG->allowaccountssameemail) ? 1 : $formdata->uunoemailduplicates;
- $standardusernames = $formdata->uustandardusernames;
- $resetpasswords = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
-
- // verification moved to two places: after upload and into form2
- $usersnew = 0;
- $usersupdated = 0;
- $usersuptodate = 0; //not printed yet anywhere
- $userserrors = 0;
- $deletes = 0;
- $deleteerrors = 0;
- $renames = 0;
- $renameerrors = 0;
- $usersskipped = 0;
- $weakpasswords = 0;
-
- // caches
- $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
- $cohorts = array();
- $rolecache = uu_allowed_roles_cache(); // Course roles lookup cache.
- $sysrolecache = uu_allowed_sysroles_cache(); // System roles lookup cache.
- $manualcache = array(); // cache of used manual enrol plugins in each course
- $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
-
- // we use only manual enrol plugin here, if it is disabled no enrol is done
- if (enrol_is_enabled('manual')) {
- $manual = enrol_get_plugin('manual');
- } else {
- $manual = NULL;
- }
-
- // clear bulk selection
- if ($bulk) {
- $SESSION->bulk_users = array();
- }
-
- // init csv import helper
- $cir->init();
- $linenum = 1; //column header is first line
-
- // init upload progress tracker
- $upt = new uu_progress_tracker();
- $upt->start(); // start table
- $validation = array();
- while ($line = $cir->next()) {
- $upt->flush();
- $linenum++;
-
- $upt->track('line', $linenum);
-
- $user = new stdClass();
-
- // add fields to user object
- foreach ($line as $keynum => $value) {
- if (!isset($filecolumns[$keynum])) {
- // this should not happen
- continue;
- }
- $key = $filecolumns[$keynum];
- if (strpos($key, 'profile_field_') === 0) {
- //NOTE: bloody mega hack alert!!
- if (isset($USER->$key) and is_array($USER->$key)) {
- // this must be some hacky field that is abusing arrays to store content and format
- $user->$key = array();
- $user->{$key['text']} = $value;
- $user->{$key['format']} = FORMAT_MOODLE;
- } else {
- $user->$key = trim($value);
- }
- } else {
- $user->$key = trim($value);
- }
-
- if (in_array($key, $upt->columns)) {
- // default value in progress tracking table, can be changed later
- $upt->track($key, s($value), 'normal');
- }
- }
- if (!isset($user->username)) {
- // prevent warnings below
- $user->username = '';
- }
-
- if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
- // user creation is a special case - the username may be constructed from templates using firstname and lastname
- // better never try this in mixed update types
- $error = false;
- if (!isset($user->firstname) or $user->firstname === '') {
- $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
- $upt->track('firstname', $errorstr, 'error');
- $error = true;
- }
- if (!isset($user->lastname) or $user->lastname === '') {
- $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
- $upt->track('lastname', $errorstr, 'error');
- $error = true;
- }
- if ($error) {
- $userserrors++;
- continue;
- }
- // we require username too - we might use template for it though
- if (empty($user->username) and !empty($formdata->username)) {
- $user->username = uu_process_template($formdata->username, $user);
- $upt->track('username', s($user->username));
- }
- }
-
- // normalize username
- $originalusername = $user->username;
- if ($standardusernames) {
- $user->username = core_user::clean_field($user->username, 'username');
- }
-
- // make sure we really have username
- if (empty($user->username)) {
- $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
- $upt->track('username', $errorstr, 'error');
- $userserrors++;
- continue;
- } else if ($user->username === 'guest') {
- $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
- $userserrors++;
- continue;
- }
-
- if ($user->username !== core_user::clean_field($user->username, 'username')) {
- $upt->track('status', get_string('invalidusername', 'error', 'username'), 'error');
- $upt->track('username', $errorstr, 'error');
- $userserrors++;
- }
-
- if (empty($user->mnethostid)) {
- $user->mnethostid = $CFG->mnet_localhost_id;
- }
-
- if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
- $upt->track('id', $existinguser->id, 'normal', false);
- }
-
- if ($user->mnethostid == $CFG->mnet_localhost_id) {
- $remoteuser = false;
-
- // Find out if username incrementing required.
- if ($existinguser and $optype == UU_USER_ADDINC) {
- $user->username = uu_increment_username($user->username);
- $existinguser = false;
- }
-
- } else {
- if (!$existinguser or $optype == UU_USER_ADDINC) {
- $upt->track('status', get_string('errormnetadd', 'tool_uploaduser'), 'error');
- $userserrors++;
- continue;
- }
-
- $remoteuser = true;
-
- // Make sure there are no changes of existing fields except the suspended status.
- foreach ((array)$existinguser as $k => $v) {
- if ($k === 'suspended') {
- continue;
- }
- if (property_exists($user, $k)) {
- $user->$k = $v;
- }
- if (in_array($k, $upt->columns)) {
- if ($k === 'password' or $k === 'oldusername' or $k === 'deleted') {
- $upt->track($k, '', 'normal', false);
- } else {
- $upt->track($k, s($v), 'normal', false);
- }
- }
- }
- unset($user->oldusername);
- unset($user->password);
- $user->auth = $existinguser->auth;
- }
-
- // notify about nay username changes
- if ($originalusername !== $user->username) {
- $upt->track('username', '', 'normal', false); // clear previous
- $upt->track('username', s($originalusername).'-->'.s($user->username), 'info');
- } else {
- $upt->track('username', s($user->username), 'normal', false);
- }
-
- // Verify if the theme is valid and allowed to be set.
- if (isset($user->theme)) {
- list($status, $message) = field_value_validators::validate_theme($user->theme);
- if ($status !== 'normal' && !empty($message)) {
- $upt->track('status', $message, $status);
- // Unset the theme when validation fails.
- unset($user->theme);
- }
- }
-
- // add default values for remaining fields
- $formdefaults = array();
- if (!$existinguser || ($updatetype != UU_UPDATE_FILEOVERRIDE && $updatetype != UU_UPDATE_NOCHANGES)) {
- foreach ($STD_FIELDS as $field) {
- if (isset($user->$field)) {
- continue;
- }
- // all validation moved to form2
- if (isset($formdata->$field)) {
- // process templates
- $user->$field = uu_process_template($formdata->$field, $user);
- $formdefaults[$field] = true;
- if (in_array($field, $upt->columns)) {
- $upt->track($field, s($user->$field), 'normal');
- }
- }
- }
- foreach ($PRF_FIELDS as $field) {
- if (isset($user->$field)) {
- continue;
- }
- if (isset($formdata->$field)) {
- // process templates
- $user->$field = uu_process_template($formdata->$field, $user);
-
- // Form contains key and later code expects value.
- // Convert key to value for required profile fields.
- require_once($CFG->dirroot.'/user/profile/field/'.$proffields[$field]->datatype.'/field.class.php');
- $profilefieldclass = 'profile_field_'.$proffields[$field]->datatype;
- $profilefield = new $profilefieldclass($proffields[$field]->id);
- if (method_exists($profilefield, 'convert_external_data')) {
- $user->$field = $profilefield->edit_save_data_preprocess($user->$field, null);
- }
-
- $formdefaults[$field] = true;
- }
- }
- }
-
- // delete user
- if (!empty($user->deleted)) {
- if (!$allowdeletes or $remoteuser) {
- $usersskipped++;
- $upt->track('status', $strusernotdeletedoff, 'warning');
- continue;
- }
- if ($existinguser) {
- if (is_siteadmin($existinguser->id)) {
- $upt->track('status', $strusernotdeletedadmin, 'error');
- $deleteerrors++;
- continue;
- }
- if (delete_user($existinguser)) {
- $upt->track('status', $struserdeleted);
- $deletes++;
- } else {
- $upt->track('status', $strusernotdeletederror, 'error');
- $deleteerrors++;
- }
- } else {
- $upt->track('status', $strusernotdeletedmissing, 'error');
- $deleteerrors++;
- }
- continue;
- }
- // we do not need the deleted flag anymore
- unset($user->deleted);
-
- // renaming requested?
- if (!empty($user->oldusername) ) {
- if (!$allowrenames) {
- $usersskipped++;
- $upt->track('status', $strusernotrenamedoff, 'warning');
- continue;
- }
-
- if ($existinguser) {
- $upt->track('status', $strusernotrenamedexists, 'error');
- $renameerrors++;
- continue;
- }
-
- if ($user->username === 'guest') {
- $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
- $renameerrors++;
- continue;
- }
-
- if ($standardusernames) {
- $oldusername = core_user::clean_field($user->oldusername, 'username');
- } else {
- $oldusername = $user->oldusername;
- }
-
- // no guessing when looking for old username, it must be exact match
- if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
- $upt->track('id', $olduser->id, 'normal', false);
- if (is_siteadmin($olduser->id)) {
- $upt->track('status', $strusernotrenamedadmin, 'error');
- $renameerrors++;
- continue;
- }
- $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
- $upt->track('username', '', 'normal', false); // clear previous
- $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
- $upt->track('status', $struserrenamed);
- $renames++;
- } else {
- $upt->track('status', $strusernotrenamedmissing, 'error');
- $renameerrors++;
- continue;
- }
- $existinguser = $olduser;
- $existinguser->username = $user->username;
- }
-
- // can we process with update or insert?
- $skip = false;
- switch ($optype) {
- case UU_USER_ADDNEW:
- if ($existinguser) {
- $usersskipped++;
- $upt->track('status', $strusernotadded, 'warning');
- $skip = true;
- }
- break;
-
- case UU_USER_ADDINC:
- if ($existinguser) {
- //this should not happen!
- $upt->track('status', $strusernotaddederror, 'error');
- $userserrors++;
- $skip = true;
- }
- break;
-
- case UU_USER_ADD_UPDATE:
- break;
-
- case UU_USER_UPDATE:
- if (!$existinguser) {
- $usersskipped++;
- $upt->track('status', $strusernotupdatednotexists, 'warning');
- $skip = true;
- }
- break;
-
- default:
- // unknown type
- $skip = true;
- }
-
- if ($skip) {
- continue;
- }
-
- if ($existinguser) {
- $user->id = $existinguser->id;
-
- $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
- $upt->track('suspended', $stryesnooptions[$existinguser->suspended] , 'normal', false);
- $upt->track('auth', $existinguser->auth, 'normal', false);
-
- if (is_siteadmin($user->id)) {
- $upt->track('status', $strusernotupdatedadmin, 'error');
- $userserrors++;
- continue;
- }
-
- $existinguser->timemodified = time();
- // do NOT mess with timecreated or firstaccess here!
-
- //load existing profile data
- profile_load_data($existinguser);
-
- $doupdate = false;
- $dologout = false;
-
- if ($updatetype != UU_UPDATE_NOCHANGES and !$remoteuser) {
- if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
- $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
- $existinguser->auth = $user->auth;
- if (!isset($supportedauths[$user->auth])) {
- $upt->track('auth', $struserauthunsupported, 'warning');
- }
- $doupdate = true;
- if ($existinguser->auth === 'nologin') {
- $dologout = true;
- }
- }
- $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
- foreach ($allcolumns as $column) {
- if ($column === 'username' or $column === 'password' or $column === 'auth' or $column === 'suspended') {
- // these can not be changed here
- continue;
- }
- if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
- continue;
- }
- if ($updatetype == UU_UPDATE_MISSING) {
- if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
- continue;
- }
- } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
- // we override everything
-
- } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
- if (!empty($formdefaults[$column])) {
- // do not override with form defaults
- continue;
- }
- }
- if ($existinguser->$column !== $user->$column) {
- if ($column === 'email') {
- $select = $DB->sql_like('email', ':email', false, true, false, '|');
- $params = array('email' => $DB->sql_like_escape($user->email, '|'));
- if ($DB->record_exists_select('user', $select , $params)) {
-
- $changeincase = core_text::strtolower($existinguser->$column) === core_text::strtolower(
- $user->$column);
-
- if ($changeincase) {
- // If only case is different then switch to lower case and carry on.
- $user->$column = core_text::strtolower($user->$column);
- continue;
- } else if ($noemailduplicates) {
- $upt->track('email', $stremailduplicate, 'error');
- $upt->track('status', $strusernotupdated, 'error');
- $userserrors++;
- continue 2;
- } else {
- $upt->track('email', $stremailduplicate, 'warning');
- }
- }
- if (!validate_email($user->email)) {
- $upt->track('email', get_string('invalidemail'), 'warning');
- }
- }
-
- if ($column === 'lang') {
- if (empty($user->lang)) {
- // Do not change to not-set value.
- continue;
- } else if (core_user::clean_field($user->lang, 'lang') === '') {
- $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
- continue;
- }
- }
-
- if (in_array($column, $upt->columns)) {
- $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
- }
- $existinguser->$column = $user->$column;
- $doupdate = true;
- }
- }
- }
-
- try {
- $auth = get_auth_plugin($existinguser->auth);
- } catch (Exception $e) {
- $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
- $upt->track('status', $strusernotupdated, 'error');
- $userserrors++;
- continue;
- }
- $isinternalauth = $auth->is_internal();
-
- // deal with suspending and activating of accounts
- if ($allowsuspends and isset($user->suspended) and $user->suspended !== '') {
- $user->suspended = $user->suspended ? 1 : 0;
- if ($existinguser->suspended != $user->suspended) {
- $upt->track('suspended', '', 'normal', false);
- $upt->track('suspended', $stryesnooptions[$existinguser->suspended].'-->'.$stryesnooptions[$user->suspended], 'info', false);
- $existinguser->suspended = $user->suspended;
- $doupdate = true;
- if ($existinguser->suspended) {
- $dologout = true;
- }
- }
- }
-
- // changing of passwords is a special case
- // do not force password changes for external auth plugins!
- $oldpw = $existinguser->password;
-
- if ($remoteuser) {
- // Do not mess with passwords of remote users.
-
- } else if (!$isinternalauth) {
- $existinguser->password = AUTH_PASSWORD_NOT_CACHED;
- $upt->track('password', '-', 'normal', false);
- // clean up prefs
- unset_user_preference('create_password', $existinguser);
- unset_user_preference('auth_forcepasswordchange', $existinguser);
-
- } else if (!empty($user->password)) {
- if ($updatepasswords) {
- // Check for passwords that we want to force users to reset next
- // time they log in.
- $errmsg = null;
- $weak = !check_password_policy($user->password, $errmsg, $user);
- if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
- if ($weak) {
- $weakpasswords++;
- $upt->track('password', $strinvalidpasswordpolicy, 'warning');
- }
- set_user_preference('auth_forcepasswordchange', 1, $existinguser);
- } else {
- unset_user_preference('auth_forcepasswordchange', $existinguser);
- }
- unset_user_preference('create_password', $existinguser); // no need to create password any more
-
- // 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.
- $existinguser->password = hash_internal_user_password($user->password, true);
- $upt->track('password', $user->password, 'normal', false);
- } else {
- // do not print password when not changed
- $upt->track('password', '', 'normal', false);
- }
- }
-
- if ($doupdate or $existinguser->password !== $oldpw) {
- // We want only users that were really updated.
- user_update_user($existinguser, false, false);
-
- $upt->track('status', $struserupdated);
- $usersupdated++;
-
- if (!$remoteuser) {
- // pre-process custom profile menu fields data from csv file
- $existinguser = uu_pre_process_custom_profile_data($existinguser);
- // save custom profile fields data from csv file
- profile_save_data($existinguser);
- }
-
- if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
- if (!in_array($user->id, $SESSION->bulk_users)) {
- $SESSION->bulk_users[] = $user->id;
- }
- }
-
- // Trigger event.
- \core\event\user_updated::create_from_userid($existinguser->id)->trigger();
-
- } else {
- // no user information changed
- $upt->track('status', $struseruptodate);
- $usersuptodate++;
-
- if ($bulk == UU_BULK_ALL) {
- if (!in_array($user->id, $SESSION->bulk_users)) {
- $SESSION->bulk_users[] = $user->id;
- }
- }
- }
-
- if ($dologout) {
- \core\session\manager::kill_user_sessions($existinguser->id);
- }
-
- } else {
- // save the new user to the database
- $user->confirmed = 1;
- $user->timemodified = time();
- $user->timecreated = time();
- $user->mnethostid = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
-
- if (!isset($user->suspended) or $user->suspended === '') {
- $user->suspended = 0;
- } else {
- $user->suspended = $user->suspended ? 1 : 0;
- }
- $upt->track('suspended', $stryesnooptions[$user->suspended], 'normal', false);
-
- if (empty($user->auth)) {
- $user->auth = 'manual';
- }
- $upt->track('auth', $user->auth, 'normal', false);
-
- // do not insert record if new auth plugin does not exist!
- try {
- $auth = get_auth_plugin($user->auth);
- } catch (Exception $e) {
- $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
- $upt->track('status', $strusernotaddederror, 'error');
- $userserrors++;
- continue;
- }
- if (!isset($supportedauths[$user->auth])) {
- $upt->track('auth', $struserauthunsupported, 'warning');
- }
-
- $isinternalauth = $auth->is_internal();
-
- if (empty($user->email)) {
- $upt->track('email', get_string('invalidemail'), 'error');
- $upt->track('status', $strusernotaddederror, 'error');
- $userserrors++;
- continue;
-
- } else if ($DB->record_exists('user', array('email'=>$user->email))) {
- if ($noemailduplicates) {
- $upt->track('email', $stremailduplicate, 'error');
- $upt->track('status', $strusernotaddederror, 'error');
- $userserrors++;
- continue;
- } else {
- $upt->track('email', $stremailduplicate, 'warning');
- }
- }
- if (!validate_email($user->email)) {
- $upt->track('email', get_string('invalidemail'), 'warning');
- }
-
- if (empty($user->lang)) {
- $user->lang = '';
- } else if (core_user::clean_field($user->lang, 'lang') === '') {
- $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
- $user->lang = '';
- }
-
- $forcechangepassword = false;
-
- if ($isinternalauth) {
- if (empty($user->password)) {
- if ($createpasswords) {
- $user->password = 'to be generated';
- $upt->track('password', '', 'normal', false);
- $upt->track('password', get_string('uupasswordcron', 'tool_uploaduser'), 'warning', false);
- } else {
- $upt->track('password', '', 'normal', false);
- $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
- $upt->track('status', $strusernotaddederror, 'error');
- $userserrors++;
- continue;
- }
- } else {
- $errmsg = null;
- $weak = !check_password_policy($user->password, $errmsg, $user);
- if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
- if ($weak) {
- $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);
- $usersnew++;
-
- // make sure user context exists
- context_user::instance($user->id);
-
- if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
- if (!in_array($user->id, $SESSION->bulk_users)) {
- $SESSION->bulk_users[] = $user->id;
- }
- }
- }
-
- // Update user interests.
- if (isset($user->interests) && strval($user->interests) !== '') {
- useredit_update_interests($user, preg_split('/\s*,\s*/', $user->interests, -1, PREG_SPLIT_NO_EMPTY));
- }
-
- // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
- foreach ($filecolumns as $column) {
- if (!preg_match('/^cohort\d+$/', $column)) {
- continue;
- }
-
- if (!empty($user->$column)) {
- $addcohort = $user->$column;
- if (!isset($cohorts[$addcohort])) {
- if (is_number($addcohort)) {
- // only non-numeric idnumbers!
- $cohort = $DB->get_record('cohort', array('id'=>$addcohort));
- } else {
- $cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
- if (empty($cohort) && has_capability('moodle/cohort:manage', context_system::instance())) {
- // Cohort was not found. Create a new one.
- $cohortid = cohort_add_cohort((object)array(
- 'idnumber' => $addcohort,
- 'name' => $addcohort,
- 'contextid' => context_system::instance()->id
- ));
- $cohort = $DB->get_record('cohort', array('id'=>$cohortid));
- }
- }
-
- if (empty($cohort)) {
- $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
- } else if (!empty($cohort->component)) {
- // cohorts synchronised with external sources must not be modified!
- $cohorts[$addcohort] = get_string('external', 'core_cohort');
- } else {
- $cohorts[$addcohort] = $cohort;
- }
- }
-
- if (is_object($cohorts[$addcohort])) {
- $cohort = $cohorts[$addcohort];
- if (!$DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id))) {
- cohort_add_member($cohort->id, $user->id);
- // we might add special column later, for now let's abuse enrolments
- $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
- }
- } else {
- // error message
- $upt->track('enrolments', $cohorts[$addcohort], 'error');
- }
- }
- }
-
-
- // find course enrolments, groups, roles/types and enrol periods
- // this is again a special case, we always do this for any updated or created users
- foreach ($filecolumns as $column) {
- if (preg_match('/^sysrole\d+$/', $column)) {
-
- if (!empty($user->$column)) {
- $sysrolename = $user->$column;
- if ($sysrolename[0] == '-') {
- $removing = true;
- $sysrolename = substr($sysrolename, 1);
- } else {
- $removing = false;
- }
-
- if (array_key_exists($sysrolename, $sysrolecache)) {
- $sysroleid = $sysrolecache[$sysrolename]->id;
- } else {
- $upt->track('enrolments', get_string('unknownrole', 'error', s($sysrolename)), 'error');
- continue;
- }
-
- if ($removing) {
- if (user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
- role_unassign($sysroleid, $user->id, SYSCONTEXTID);
- $upt->track('enrolments', get_string('unassignedsysrole',
- 'tool_uploaduser', $sysrolecache[$sysroleid]->name));
- }
- } else {
- if (!user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
- role_assign($sysroleid, $user->id, SYSCONTEXTID);
- $upt->track('enrolments', get_string('assignedsysrole',
- 'tool_uploaduser', $sysrolecache[$sysroleid]->name));
- }
- }
- }
-
- continue;
- }
- if (!preg_match('/^course\d+$/', $column)) {
- continue;
- }
- $i = substr($column, 6);
-
- if (empty($user->{'course'.$i})) {
- continue;
- }
- $shortname = $user->{'course'.$i};
- if (!array_key_exists($shortname, $ccache)) {
- if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
- $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
- continue;
- }
- $ccache[$shortname] = $course;
- $ccache[$shortname]->groups = null;
- }
- $courseid = $ccache[$shortname]->id;
- $coursecontext = context_course::instance($courseid);
- if (!isset($manualcache[$courseid])) {
- $manualcache[$courseid] = false;
- if ($manual) {
- if ($instances = enrol_get_instances($courseid, false)) {
- foreach ($instances as $instance) {
- if ($instance->enrol === 'manual') {
- $manualcache[$courseid] = $instance;
- break;
- }
- }
- }
- }
- }
-
- if ($courseid == SITEID) {
- // Technically frontpage does not have enrolments, but only role assignments,
- // let's not invent new lang strings here for this rarely used feature.
-
- if (!empty($user->{'role'.$i})) {
- $rolename = $user->{'role'.$i};
- if (array_key_exists($rolename, $rolecache)) {
- $roleid = $rolecache[$rolename]->id;
- } else {
- $upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
- continue;
- }
-
- role_assign($roleid, $user->id, context_course::instance($courseid));
-
- $a = new stdClass();
- $a->course = $shortname;
- $a->role = $rolecache[$roleid]->name;
- $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
- }
-
- } else if ($manual and $manualcache[$courseid]) {
-
- // find role
- $roleid = false;
- if (!empty($user->{'role'.$i})) {
- $rolename = $user->{'role'.$i};
- if (array_key_exists($rolename, $rolecache)) {
- $roleid = $rolecache[$rolename]->id;
- } else {
- $upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
- continue;
- }
-
- } else if (!empty($user->{'type'.$i})) {
- // if no role, then find "old" enrolment type
- $addtype = $user->{'type'.$i};
- if ($addtype < 1 or $addtype > 3) {
- $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
- continue;
- } else if (empty($formdata->{'uulegacy'.$addtype})) {
- continue;
- } else {
- $roleid = $formdata->{'uulegacy'.$addtype};
- }
- } else {
- // no role specified, use the default from manual enrol plugin
- $roleid = $manualcache[$courseid]->roleid;
- }
-
- if ($roleid) {
- // Find duration and/or enrol status.
- $timeend = 0;
- $timestart = $today;
- $status = null;
-
- if (isset($user->{'enrolstatus'.$i})) {
- $enrolstatus = $user->{'enrolstatus'.$i};
- if ($enrolstatus == '') {
- $status = null;
- } else if ($enrolstatus === (string)ENROL_USER_ACTIVE) {
- $status = ENROL_USER_ACTIVE;
- } else if ($enrolstatus === (string)ENROL_USER_SUSPENDED) {
- $status = ENROL_USER_SUSPENDED;
- } else {
- debugging('Unknown enrolment status.');
- }
- }
-
- if (!empty($user->{'enroltimestart'.$i})) {
- $parsedtimestart = strtotime($user->{'enroltimestart'.$i});
- if ($parsedtimestart !== false) {
- $timestart = $parsedtimestart;
- }
- }
-
- if (!empty($user->{'enrolperiod'.$i})) {
- $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
- if ($duration > 0) { // sanity check
- $timeend = $timestart + $duration;
- }
- } else if ($manualcache[$courseid]->enrolperiod > 0) {
- $timeend = $timestart + $manualcache[$courseid]->enrolperiod;
- }
-
- $manual->enrol_user($manualcache[$courseid], $user->id, $roleid, $timestart, $timeend, $status);
-
- $a = new stdClass();
- $a->course = $shortname;
- $a->role = $rolecache[$roleid]->name;
- $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
- }
- }
-
- // find group to add to
- if (!empty($user->{'group'.$i})) {
- // make sure user is enrolled into course before adding into groups
- if (!is_enrolled($coursecontext, $user->id)) {
- $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
- continue;
- }
- //build group cache
- if (is_null($ccache[$shortname]->groups)) {
- $ccache[$shortname]->groups = array();
- if ($groups = groups_get_all_groups($courseid)) {
- foreach ($groups as $gid=>$group) {
- $ccache[$shortname]->groups[$gid] = new stdClass();
- $ccache[$shortname]->groups[$gid]->id = $gid;
- $ccache[$shortname]->groups[$gid]->name = $group->name;
- if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
- $ccache[$shortname]->groups[$group->name] = new stdClass();
- $ccache[$shortname]->groups[$group->name]->id = $gid;
- $ccache[$shortname]->groups[$group->name]->name = $group->name;
- }
- }
- }
- }
- // group exists?
- $addgroup = $user->{'group'.$i};
- if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
- // if group doesn't exist, create it
- $newgroupdata = new stdClass();
- $newgroupdata->name = $addgroup;
- $newgroupdata->courseid = $ccache[$shortname]->id;
- $newgroupdata->description = '';
- $gid = groups_create_group($newgroupdata);
- if ($gid){
- $ccache[$shortname]->groups[$addgroup] = new stdClass();
- $ccache[$shortname]->groups[$addgroup]->id = $gid;
- $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
- } else {
- $upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
- continue;
- }
- }
- $gid = $ccache[$shortname]->groups[$addgroup]->id;
- $gname = $ccache[$shortname]->groups[$addgroup]->name;
-
- try {
- if (groups_add_member($gid, $user->id)) {
- $upt->track('enrolments', get_string('addedtogroup', '', s($gname)));
- } else {
- $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
- }
- } catch (moodle_exception $e) {
- $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
- continue;
- }
- }
- }
- $validation[$user->username] = core_user::validate($user);
- }
- $upt->close(); // close table
- if (!empty($validation)) {
- foreach ($validation as $username => $result) {
- if ($result !== true) {
- \core\notification::warning(get_string('invaliduserdata', 'tool_uploaduser', s($username)));
- }
- }
- }
- $cir->close();
- $cir->cleanup(true);
+ $process->set_form_data($formdata);
+ $process->process();
echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
- echo '
';
- if ($optype != UU_USER_UPDATE) {
- echo get_string('userscreated', 'tool_uploaduser').': '.$usersnew.'
';
- }
- if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
- echo get_string('usersupdated', 'tool_uploaduser').': '.$usersupdated.'
';
- }
- if ($allowdeletes) {
- echo get_string('usersdeleted', 'tool_uploaduser').': '.$deletes.'
';
- echo get_string('deleteerrors', 'tool_uploaduser').': '.$deleteerrors.'
';
- }
- if ($allowrenames) {
- echo get_string('usersrenamed', 'tool_uploaduser').': '.$renames.'
';
- echo get_string('renameerrors', 'tool_uploaduser').': '.$renameerrors.'
';
- }
- if ($usersskipped) {
- echo get_string('usersskipped', 'tool_uploaduser').': '.$usersskipped.'
';
- }
- echo get_string('usersweakpassword', 'tool_uploaduser').': '.$weakpasswords.'
';
- echo get_string('errors', 'tool_uploaduser').': '.$userserrors.'
'.get_string('status').' | '; - echo ''.get_string('uucsvline', 'tool_uploaduser').' | '; - echo 'ID | '; - echo ''.get_string('username').' | '; - echo ''.get_string('firstname').' | '; - echo ''.get_string('lastname').' | '; - echo ''.get_string('email').' | '; - echo ''.get_string('password').' | '; - echo ''.get_string('authentication').' | '; - echo ''.get_string('enrolments', 'enrol').' | '; - echo ''.get_string('suspended', 'auth').' | '; - echo ''.get_string('theme').' | '; - echo ''.get_string('delete').' | '; + foreach ($this->headers as $key => $header) { + echo ''.$header.' | '; + } echo '
---|