Merge branch 'MDL-63806-master' of git://github.com/jleyva/moodle into master
authorEloy Lafuente (stronk7) <stronk7@moodle.org>
Tue, 13 Oct 2020 20:26:27 +0000 (22:26 +0200)
committerEloy Lafuente (stronk7) <stronk7@moodle.org>
Tue, 13 Oct 2020 20:26:27 +0000 (22:26 +0200)
157 files changed:
.travis.yml
admin/classes/local/externalpage/accesscallback.php [new file with mode: 0644]
admin/modules.php
admin/plugins.php
admin/tool/behat/cli/util_single_run.php
admin/tool/customlang/classes/form/export.php [new file with mode: 0644]
admin/tool/customlang/classes/output/renderer.php
admin/tool/customlang/cli/export.php [new file with mode: 0644]
admin/tool/customlang/db/access.php
admin/tool/customlang/export.php [new file with mode: 0644]
admin/tool/customlang/filter_form.php
admin/tool/customlang/index.php
admin/tool/customlang/lang/en/tool_customlang.php
admin/tool/customlang/locallib.php
admin/tool/customlang/templates/translator.mustache
admin/tool/customlang/tests/behat/customisation_create.feature [new file with mode: 0644]
admin/tool/customlang/tests/behat/export.feature [new file with mode: 0644]
admin/tool/customlang/version.php
admin/tool/mobile/classes/api.php
admin/tool/mobile/lang/en/tool_mobile.php
admin/tool/mobile/lib.php
admin/tool/mobile/logout.php [new file with mode: 0644]
admin/tool/mobile/tests/externallib_test.php
admin/tool/replace/classes/form.php
admin/tool/replace/cli/replace.php
admin/tool/replace/index.php
admin/tool/replace/lang/en/tool_replace.php
admin/tool/uploaduser/classes/cli_helper.php [new file with mode: 0644]
admin/tool/uploaduser/classes/local/cli_progress_tracker.php [new file with mode: 0644]
admin/tool/uploaduser/classes/local/text_progress_tracker.php [new file with mode: 0644]
admin/tool/uploaduser/classes/preview.php [new file with mode: 0644]
admin/tool/uploaduser/classes/process.php [new file with mode: 0644]
admin/tool/uploaduser/cli/uploaduser.php [new file with mode: 0644]
admin/tool/uploaduser/index.php
admin/tool/uploaduser/lang/en/tool_uploaduser.php
admin/tool/uploaduser/locallib.php
admin/tool/uploaduser/tests/cli_test.php [new file with mode: 0644]
admin/tool/uploaduser/user_form.php
availability/condition/grade/tests/behat/availability_grade.feature
backup/util/ui/renderer.php
calendar/export_execute.php
completion/tests/behat/restrict_activity_by_grade.feature
completion/tests/behat/restrict_section_availability.feature
composer.json
composer.lock
config-dist.php
course/externallib.php
course/tests/externallib_test.php
files/classes/external/delete/draft.php [new file with mode: 0644]
files/tests/externallib_test.php
grade/grading/form/guide/tests/behat/edit_guide.feature
grade/grading/tests/behat/behat_grading.php
grade/report/singleview/tests/behat/bulk_insert_grades.feature
grade/tests/behat/grade_scales.feature
grade/tests/behat/grade_single_item_scales.feature
h5p/ajax.php
h5p/classes/external.php
h5p/classes/framework.php
install/lang/ar/error.php
install/lang/ar/install.php
install/lang/pt/error.php
install/lang/pt/install.php
lang/en/moodle.php
lib/adminlib.php
lib/amd/build/notification.min.js
lib/amd/build/notification.min.js.map
lib/amd/src/notification.js
lib/behat/classes/util.php
lib/classes/component.php
lib/classes/notification.php
lib/classes/oauth2/api.php
lib/classes/oauth2/client.php
lib/classes/plugininfo/base.php
lib/classes/privacy/provider.php
lib/classes/session/redis.php
lib/db/install.xml
lib/db/services.php
lib/db/upgrade.php
lib/form/templates/element-defaultcustom.mustache
lib/form/tests/behat/modgrade_validation.feature
lib/jabber/XMPP/BOSH.php
lib/jabber/XMPP/Exception.php
lib/jabber/XMPP/Log.php
lib/jabber/XMPP/README.txt [deleted file]
lib/jabber/XMPP/Roster.php
lib/jabber/XMPP/XMLObj.php
lib/jabber/XMPP/XMLStream.php
lib/jabber/XMPP/XMPP.php
lib/jabber/XMPP/XMPP_Old.php [deleted file]
lib/jabber/readme_moodle.txt
lib/moodlelib.php
lib/outputlib.php
lib/outputrenderers.php
lib/setup.php
lib/setuplib.php
lib/tests/adminlib_test.php
lib/tests/notification_test.php
lib/tests/setuplib_test.php
lib/thirdpartylibs.xml
lib/upgrade.txt
login/token.php
message/output/jabber/message_output_jabber.php
mod/assign/amd/build/grading_panel.min.js
mod/assign/amd/build/grading_panel.min.js.map
mod/assign/amd/src/grading_panel.js
mod/assign/feedback/editpdf/lib.php
mod/assign/feedback/editpdf/locallib.php
mod/assign/feedback/editpdf/tests/behat/annotate_pdf.feature
mod/assign/feedback/editpdf/tests/behat/group_annotations.feature
mod/assign/feedback/editpdf/tests/behat/view_previous_annotations.feature
mod/assign/feedback/file/tests/behat/feedback_file.feature
mod/assign/tests/behat/allow_another_attempt.feature
mod/assign/tests/behat/assign_hidden.feature
mod/assign/tests/behat/comment_inline.feature
mod/assign/tests/behat/display_grade.feature
mod/assign/tests/behat/edit_previous_feedback.feature
mod/assign/tests/behat/filter_by_marker.feature
mod/assign/tests/behat/grading_app_filters.feature
mod/assign/tests/behat/grading_status.feature
mod/assign/tests/behat/group_submission.feature
mod/assign/tests/behat/hide_grader.feature
mod/assign/tests/behat/outcome_grading.feature
mod/assign/tests/behat/prevent_submission_changes.feature
mod/assign/tests/behat/quickgrading.feature
mod/assign/tests/behat/relative_dates.feature
mod/assign/tests/behat/rescale_grades.feature
mod/assign/tests/behat/steps_blind_marking.feature
mod/assign/tests/behat/submission_comments.feature
mod/data/mod_form.php
mod/data/tests/behat/create_activity.feature [new file with mode: 0644]
mod/feedback/backup/moodle2/restore_feedback_stepslib.php
mod/feedback/tests/restore_date_test.php
mod/forum/amd/build/discussion_nested_v2.min.js
mod/forum/amd/build/discussion_nested_v2.min.js.map
mod/forum/amd/build/inpage_reply.min.js
mod/forum/amd/build/inpage_reply.min.js.map
mod/forum/amd/build/posts_list.min.js
mod/forum/amd/build/posts_list.min.js.map
mod/forum/amd/src/discussion_nested_v2.js
mod/forum/amd/src/inpage_reply.js
mod/forum/amd/src/posts_list.js
mod/forum/templates/inpage_reply.mustache
mod/forum/templates/inpage_reply_v2.mustache
mod/forum/tests/behat/behat_mod_forum.php
mod/lti/locallib.php
mod/lti/service/memberships/classes/local/service/memberships.php
mod/lti/tests/locallib_test.php
question/format/xml/format.php
question/format/xml/tests/fixtures/html_chars_in_idnumbers.xml [new file with mode: 0644]
question/format/xml/tests/qformat_xml_import_export_test.php
repository/googledocs/lib.php
repository/nextcloud/lib.php
repository/onedrive/lib.php
theme/boost/scss/moodle/admin.scss
theme/boost/style/moodle.css
theme/classic/style/moodle.css
version.php

index 27ee681..7b533fe 100644 (file)
@@ -2,10 +2,9 @@
 # process (which uses our internal CI system) this file is here for the benefit
 # of community developers git clones - see MDL-51458.
 
-# We currently disable Travis notifications entirely until https://github.com/travis-ci/travis-ci/issues/4976
-# is fixed.
 notifications:
-  email: false
+  email:
+    if: env(MOODLE_EMAIL) != no
 
 language: php
 
diff --git a/admin/classes/local/externalpage/accesscallback.php b/admin/classes/local/externalpage/accesscallback.php
new file mode 100644 (file)
index 0000000..05fb07f
--- /dev/null
@@ -0,0 +1,71 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * External admin page class that allows a callback to be provided to determine whether page can be accessed
+ *
+ * @package     core_admin
+ * @copyright   2019 Marina Glancy
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_admin\local\externalpage;
+
+use admin_externalpage;
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once("{$CFG->libdir}/adminlib.php");
+
+/**
+ * Admin externalpage class
+ *
+ * @package     core_admin
+ * @copyright   2019 Marina Glancy
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class accesscallback extends admin_externalpage {
+
+    /** @var callable $accesscheckcallback */
+    protected $accesscheckcallback;
+
+    /**
+     * Class constructor
+     *
+     * @param string $name
+     * @param string $visiblename
+     * @param string $url
+     * @param callable $accesscheckcallback The callback method that will be executed to check whether user has access to
+     *     this page. The setting instance ($this) is passed as an argument to the callback. Should return boolean value
+     * @param bool $hidden
+     */
+    public function __construct(string $name, string $visiblename, string $url, callable $accesscheckcallback,
+            bool $hidden = false) {
+
+        $this->accesscheckcallback = $accesscheckcallback;
+
+        parent::__construct($name, $visiblename, $url, [], $hidden);
+    }
+
+    /**
+     * Determines if the current user has access to this external page based on access callback
+     *
+     * @return bool
+     */
+    public function check_access() {
+        return ($this->accesscheckcallback)($this);
+    }
+}
index 01f67a1..e76a8e1 100644 (file)
@@ -49,6 +49,7 @@
                 array($module->id));
         core_plugin_manager::reset_caches();
         admin_get_root(true, false);  // settings not required - only pages
+        redirect(new moodle_url('/admin/modules.php'));
     }
 
     if (!empty($show) and confirm_sesskey()) {
@@ -66,6 +67,7 @@
                 array($module->id));
         core_plugin_manager::reset_caches();
         admin_get_root(true, false);  // settings not required - only pages
+        redirect(new moodle_url('/admin/modules.php'));
     }
 
     echo $OUTPUT->header();
             $count = -1;
         }
         if ($count>0) {
-            $countlink = "<a href=\"{$CFG->wwwroot}/course/search.php?modulelist=$module->name" .
-                "&amp;sesskey=".sesskey()."\" title=\"$strshowmodulecourse\">$count</a>";
+            $countlink = $OUTPUT->action_link(new moodle_url('/course/search.php', ['modulelist' => $module->name]),
+                $count, null, ['title' => $strshowmodulecourse]);
         } else if ($count < 0) {
             $countlink = get_string('error');
         } else {
index c99ae52..e4867c1 100644 (file)
@@ -53,7 +53,6 @@ $pageurl = new moodle_url('/admin/plugins.php', $pageparams);
 $pluginman = core_plugin_manager::instance();
 
 if ($uninstall) {
-    require_sesskey();
 
     if (!$confirmed) {
         admin_externalpage_setup('pluginsoverview', '', $pageparams);
@@ -92,6 +91,7 @@ if ($uninstall) {
         exit();
 
     } else {
+        require_sesskey();
         $SESSION->pluginuninstallreturn = $pluginfo->get_return_url_after_uninstall($return);
         $progress = new progress_trace_buffer(new text_progress_trace(), false);
         $pluginman->uninstall_plugin($pluginfo->component, $progress);
index 42b335c..868dd84 100644 (file)
@@ -187,10 +187,13 @@ if ($options['install']) {
     behat_config_manager::set_behat_run_config_value('axe', $options['axe']);
 
     // Enable test mode.
+    $timestart = microtime(true);
+    mtrace('Creating Behat configuration ...', '');
     behat_util::start_test_mode($options['add-core-features-to-theme'], $options['optimize-runs'], $parallel, $run);
+    mtrace(' done in ' . round(microtime(true) - $timestart, 2) . ' seconds.');
 
     // Themes are only built in the 'enable' command.
-    behat_util::build_themes();
+    behat_util::build_themes(true);
     mtrace("Testing environment themes built");
 
     // This is only displayed once for parallel install.
diff --git a/admin/tool/customlang/classes/form/export.php b/admin/tool/customlang/classes/form/export.php
new file mode 100644 (file)
index 0000000..843b09a
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Creates Formular for customlang file export
+ *
+ * @package    tool_customlang
+ * @copyright  2020 Thomas Wedekind <Thomas.Wedekind@univie.ac.at>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace tool_customlang\form;
+
+use tool_customlang_utils;
+
+/**
+ * Formular for customlang file export
+ *
+ * @copyright  2020 Thomas Wedekind <Thomas.Wedekind@univie.ac.at>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class export extends \moodleform {
+
+    /**
+     * Add elements to form
+     */
+    public function definition() {
+        $lng = $this->_customdata['lng'];
+        $mform = $this->_form;
+
+        $langdir = tool_customlang_utils::get_localpack_location($lng);
+
+        // The export button only appears if a local lang is present.
+        if (!check_dir_exists($langdir) || !count(glob("$langdir/*"))) {
+            print_error('nolocallang', 'tool_customlang');
+        }
+
+        $langfiles = scandir($langdir);
+        $fileoptions = [];
+        foreach ($langfiles as $file) {
+            if (substr($file, 0, 1) != '.') {
+                $fileoptions[$file] = $file;
+            }
+        }
+
+        $mform->addElement('hidden', 'lng', $lng);
+        $mform->setType('lng', PARAM_LANG);
+
+        $select = $mform->addElement('select', 'files', get_string('exportfilter', 'tool_customlang'), $fileoptions);
+        $select->setMultiple(true);
+        $mform->addRule('files', get_string('required'), 'required', null, 'client');
+        $mform->setDefault('files', $fileoptions);
+
+        $this->add_action_buttons(true, get_string('export', 'tool_customlang'));
+    }
+}
index b183daf..9ad60c5 100644 (file)
@@ -57,8 +57,9 @@ class renderer extends \plugin_renderer_base {
     protected function render_tool_customlang_menu(\tool_customlang_menu $menu) {
         $output = '';
         foreach ($menu->get_items() as $item) {
-            $output .= $this->single_button($item->url, $item->title, $item->method);
+            $button = $this->single_button($item->url, $item->title, $item->method);
+            $output .= $this->box($button, 'menu');
         }
-        return $this->box($output, 'menu');
+        return $output;
     }
 }
diff --git a/admin/tool/customlang/cli/export.php b/admin/tool/customlang/cli/export.php
new file mode 100644 (file)
index 0000000..29655de
--- /dev/null
@@ -0,0 +1,135 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Export custom language strings to zip files.
+ *
+ * @package    tool_customlang
+ * @subpackage customlang
+ * @copyright  2020 Thomas Wedekind <thomas.wedekind@univie.ac.at>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('CLI_SCRIPT', true);
+
+require(__DIR__ . '/../../../../config.php');
+require_once("$CFG->libdir/clilib.php");
+require_once("$CFG->dirroot/$CFG->admin/tool/customlang/locallib.php");
+
+$usage = <<<EOF
+"Export custom language files to a target folder.
+Useful for uploading custom langstrings to AMOS or importing or syncing them to other moodle instances.
+
+Options:
+-l, --lang              Comma seperated language ids to export, default: all
+-c, --components        Comma seperated components to export, default: all
+-t, --target            Target to copy the zip files to, default: $CFG->tempdir/customlang
+-o, --overwrite         Overwrite existing files in the target folder.
+                            Note: If the target is not set, the files are always overwritten!
+-h, --help              Print out this help
+
+Examples:
+Export all custom language files to the default folder:
+\$ sudo -u www-data /usr/bin/php admin/tool/customlang/cli/export.php
+
+Export just the english files of moodle core and the activity 'quiz' in a subfolder in my home folder:
+\$ sudo -u www-data /usr/bin/php admin/tool/customlang/cli/export.php --lang='en' --components='moodle,quiz' --target='~/customdir'
+
+EOF;
+
+$dafaulttarget = "$CFG->tempdir/customlang/";
+
+// Now get cli options.
+list($options, $unrecognized) = cli_get_params(
+    [
+        'lang' => '',
+        'components' => '',
+        'target' => $dafaulttarget,
+        'overwrite' => false,
+        'help' => false,
+    ],
+    ['h' => 'help', 'c' => 'components', 't' => 'target', 'o' => 'overwrite']
+);
+
+if ($unrecognized) {
+    $unrecognized = implode("\n  ", $unrecognized);
+    cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
+}
+
+if ($options['help']) {
+    echo $usage;
+    die;
+}
+if (!file_exists($options['target'])) {
+    mkdir($options['target'], 0777, true);
+}
+
+cli_writeln(get_string('cliexportheading', 'tool_customlang'));
+$langs = [];
+if ($options['lang']) {
+    $langs = explode(',', $options['lang']);
+} else {
+    // No language set. We export all installed languages.
+    $langs = array_keys(get_string_manager()->get_list_of_translations(true));
+}
+
+foreach ($langs as $lang) {
+    $filename = $options['target'] . get_string('exportzipfilename', 'tool_customlang', ['lang' => $lang]);
+    // If the file exists and we are not using the temp folder it requires an ovewrite.
+    if ($options['target'] != $dafaulttarget && file_exists($filename) && !$options['overwrite']) {
+        cli_problem(get_string('cliexportfileexists', 'tool_customlang', $lang));
+        continue;
+    }
+    cli_heading(get_string('cliexportstartexport', 'tool_customlang', $lang));
+    $langdir = tool_customlang_utils::get_localpack_location($lang);
+    if (!file_exists($langdir)) {
+        // No custom files set for this language set.
+        cli_writeln(get_string('cliexportnofilefoundforlang', 'tool_customlang', ['lang' => $lang]));
+        continue;
+    }
+    $zipper = get_file_packer();
+    $tempzip = tempnam($CFG->tempdir . '/', 'tool_customlang_export');
+    $filelist = [];
+    if ($options['components']) {
+        $components = explode(',', $options['components']);
+        foreach ($components as $component) {
+            $filepath = "$langdir/$component.php";
+            if (file_exists($filepath)) {
+                $filelist["$component.php"] = $filepath;
+            } else {
+                cli_problem(
+                    get_string('cliexportfilenotfoundforcomponent', 'tool_customlang', ['lang' => $lang, 'file' => $filepath])
+                );
+            }
+        }
+    } else {
+        $langfiles = scandir($langdir);
+        foreach ($langfiles as $file) {
+            if (substr($file, 0, 1) != '.') {
+                $filelist[$file] = "$langdir/$file";
+            }
+        }
+    }
+    if (empty($filelist)) {
+        cli_problem(get_string('cliexportnofilefoundforlang', 'tool_customlang', ['lang' => $lang]));
+        continue;
+    }
+    if ($zipper->archive_to_pathname($filelist, $filename)) {
+        cli_writeln(get_string('cliexportzipdone', 'tool_customlang', $filename));
+    } else {
+        cli_problem(get_string('cliexportzipfail', 'tool_customlang', $filename));
+    }
+}
index 12f0792..46f3981 100644 (file)
@@ -46,5 +46,14 @@ $capabilities = array(
             'manager' => CAP_ALLOW
         ),
     ),
+    /* allows the user to export the current language customization */
+    'tool/customlang:export' => array(
+        'riskbitmask' => RISK_CONFIG,
+        'captype' => 'read',
+        'contextlevel' => CONTEXT_SYSTEM,
+        'archetypes' => array(
+            'manager' => CAP_ALLOW
+        ),
+    ),
 
 );
diff --git a/admin/tool/customlang/export.php b/admin/tool/customlang/export.php
new file mode 100644 (file)
index 0000000..e649360
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Performs the custom lang export.
+ *
+ * @package    tool_customlang
+ * @subpackage customlang
+ * @copyright  2020 Thomas Wedekind <thomas.wedekind@univie.ac.at>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require(__DIR__ . '/../../../config.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/customlang/locallib.php');
+require_once($CFG->libdir.'/adminlib.php');
+
+global $PAGE, $CFG;
+
+require_login(SITEID, false);
+require_capability('tool/customlang:export', context_system::instance());
+
+$lng = required_param('lng', PARAM_LANG);
+
+admin_externalpage_setup('toolcustomlang', '', null,
+    new moodle_url('/admin/tool/customlang/import.php', ['lng' => $lng]));
+
+$form = new \tool_customlang\form\export(null, ['lng' => $lng]);
+
+if ($form->is_cancelled()) {
+    redirect('index.php');
+    die();
+} else if ($formdata = $form->get_data()) {
+    $tempzip = tempnam($CFG->tempdir . '/', 'tool_customlang_export');
+    $filelist = [];
+    foreach ($formdata->files as $file) {
+        $filepath = tool_customlang_utils::get_localpack_location($lng). '/' . $file;
+        if (file_exists($filepath)) {
+            $filelist[$file] = $filepath;
+        }
+    }
+    $zipper = new zip_packer();
+
+    if (!empty($filelist) && $zipper->archive_to_pathname($filelist, $tempzip)) {
+        // Filename include the lang name so the file can be imported with automatic language detection.
+        send_temp_file($tempzip, "customlang_$lng.zip");
+        die();
+    }
+}
+
+$output = $PAGE->get_renderer('tool_customlang');
+
+echo $output->header();
+echo $output->heading(get_string('pluginname', 'tool_customlang'));
+$form->display();
+echo $OUTPUT->footer();
index 19d74c1..6c92e81 100644 (file)
@@ -32,7 +32,6 @@ class tool_customlang_filter_form extends moodleform {
 
     function definition() {
         $mform = $this->_form;
-        $current = $this->_customdata['current'];
 
         $mform->addElement('header', 'filtersettings', get_string('filter', 'tool_customlang'));
 
index 9031329..d796e8c 100644 (file)
@@ -35,6 +35,7 @@ require_capability('tool/customlang:view', context_system::instance());
 $action  = optional_param('action', '', PARAM_ALPHA);
 $confirm = optional_param('confirm', false, PARAM_BOOL);
 $lng     = optional_param('lng', '', PARAM_LANG);
+$next     = optional_param('next', 'edit', PARAM_ALPHA);
 
 admin_externalpage_setup('toolcustomlang');
 $langs = get_string_manager()->get_list_of_translations();
@@ -59,11 +60,10 @@ if ($action === 'checkout') {
     raise_memory_limit(MEMORY_EXTRA);
     tool_customlang_utils::checkout($lng, $progressbar);
 
-    echo $output->continue_button(new moodle_url('/admin/tool/customlang/edit.php', array('lng' => $lng)), 'get');
+    echo $output->continue_button(new moodle_url("/admin/tool/customlang/{$next}.php", array('lng' => $lng)), 'get');
     echo $output->footer();
     exit;
 }
-
 if ($action === 'checkin') {
     require_sesskey();
     require_capability('tool/customlang:edit', context_system::instance());
@@ -133,6 +133,16 @@ if (has_capability('tool/customlang:edit', context_system::instance())) {
         );
     }
 }
+if (has_capability('tool/customlang:export', context_system::instance())) {
+    $langdir = tool_customlang_utils::get_localpack_location($lng);
+    if (check_dir_exists(dirname($langdir)) && count(glob("$langdir/*"))) {
+        $menu['export'] = [
+            'title'     => get_string('export', 'tool_customlang'),
+            'url'       => new moodle_url("/admin/tool/customlang/export.php", ['lng' => $lng]),
+            'method'    => 'post',
+        ];
+    }
+}
 echo $output->render(new tool_customlang_menu($menu));
 
 echo $output->footer();
index a7375f1..8ac0c2a 100644 (file)
@@ -30,9 +30,19 @@ $string['checkin'] = 'Save strings to language pack';
 $string['checkout'] = 'Open language pack for editing';
 $string['checkoutdone'] = 'Language pack loaded';
 $string['checkoutinprogress'] = 'Loading language pack';
+$string['cliexportfileexists'] = 'File for {$a->lang} already exists, skipping. If you want to overwrite add the --override=true option.';
+$string['cliexportheading'] = 'Starting to export lang files.';
+$string['cliexportnofilefoundforlang'] = 'No file found to export. Skipping export for this language.';
+$string['cliexportfilenotfoundforcomponent'] = 'File {$a->filepath} not found for language {$a->lang}.Skipping this file.';
+$string['cliexportstartexport'] = 'Exporting language "{$a}"';
+$string['cliexportzipdone'] = 'Zip created: {$a}';
+$string['cliexportzipfail'] = 'Cannot create zip {$a}';
 $string['confirmcheckin'] = 'You are about to save modifications to your local language pack. This will export the customised strings from the translator into your site data directory and your site will start using the modified strings. Press \'Continue\' to proceed with saving.';
 $string['customlang:edit'] = 'Edit local translation';
+$string['customlang:export'] = 'Export local translation';
 $string['customlang:view'] = 'View local translation';
+$string['export'] = 'Export custom strings';
+$string['exportfilter'] = 'Select component(s) to export';
 $string['filter'] = 'Filter strings';
 $string['filtercomponent'] = 'Show strings of these components';
 $string['filtercustomized'] = 'Customised only';
@@ -50,6 +60,7 @@ $string['markinguptodate_help'] = 'The customised translation may get outdated i
 $string['markuptodate'] = 'mark as up-to-date';
 $string['modifiedno'] = 'There are no modified strings to save.';
 $string['modifiednum'] = 'There are {$a} modified strings. Do you wish to save these changes to your local language pack?';
+$string['nolocallang'] = 'No local strings found.';
 $string['nostringsfound'] = 'No strings found, please modify the filter settings';
 $string['placeholder'] = 'Placeholders';
 $string['placeholder_help'] = 'Placeholders are special statements like `{$a}` or `{$a->something}` within the string. They are replaced with a value when the string is actually printed.
index 2f02b45..5bbb8c2 100644 (file)
@@ -243,7 +243,7 @@ class tool_customlang_utils {
      * @param string $lang language code
      * @return string full path
      */
-    protected static function get_localpack_location($lang) {
+    public static function get_localpack_location($lang) {
         global $CFG;
 
         return $CFG->langlocalroot.'/'.$lang.'_local';
index 400464c..a756968 100644 (file)
                         <strong>{{#str}}headinglocal, tool_customlang{{/str}}</strong>
                     </div>
                     <div class="py-2 py-md-0 px-md-3">
-                        <textarea class="form-control w-100 border-box" name="cust[{{id}}]" cols="40" rows="3">{{{ local }}}</textarea>
-
+                        <label for="{{id}}" class="sr-only sr-only-focusable">{{{ component }}}/{{{ stringid }}}</label>
+                        <textarea class="form-control w-100 border-box" id="{{id}}" name="cust[{{id}}]" cols="40" rows="3">{{{ local }}}</textarea>
                         {{#checkupdated}}
                         <div class="uptodatewrapper">
                             <div class="form-check">
diff --git a/admin/tool/customlang/tests/behat/customisation_create.feature b/admin/tool/customlang/tests/behat/customisation_create.feature
new file mode 100644 (file)
index 0000000..84f71bb
--- /dev/null
@@ -0,0 +1,30 @@
+@tool @tool_customlang
+Feature: Within a moodle instance, an administrator should be able to modify langstrings for the entire Moodle installation.
+  In order to change langstrings in the adminsettings of the instance,
+  As an admin
+  I need to be able to access and change values in the the language customisation of the language pack.
+
+  Background:
+    Given I log in as "admin"
+    And I navigate to "Language > Language customisation" in site administration
+    And I set the field "lng" to "en"
+    And I press "Open language pack for editing"
+    And I press "Continue"
+    And I set the field "Show strings of these components" to "moodle.php"
+    And I set the field "String identifier" to "administrationsite"
+    And I press "Show strings"
+    And I set the field "core/administrationsite" to "Custom string example"
+
+  @javascript
+  Scenario: Edit an string but don't save it to lang pack.
+    When I press "Apply changes and continue editing"
+    Then I should see "Site administration" in the "page-header" "region"
+    And I should not see "Custom string example" in the "page-header" "region"
+
+  @javascript
+  Scenario: Customize an string as admin and save it to lang pack.
+    Given I press "Save changes to the language pack"
+    And I should see "There are 1 modified strings."
+    When I click on "Continue" "button"
+    Then I should see "Custom string example" in the "page-header" "region"
+    And I should not see "Site administration" in the "page-header" "region"
diff --git a/admin/tool/customlang/tests/behat/export.feature b/admin/tool/customlang/tests/behat/export.feature
new file mode 100644 (file)
index 0000000..a42e672
--- /dev/null
@@ -0,0 +1,49 @@
+@tool @tool_customlang
+Feature: Within a moodle instance, an administrator should be able to export modified langstrings.
+  In order to export modified langstrings in the adminsettings of the instance,
+  As an admin
+  I need to be able to export the php-files of the language customisation of a language.
+
+  @javascript
+  Scenario: Export button should not appear if no customization is made
+    Given I log in as "admin"
+    And I navigate to "Language > Language customisation" in site administration
+    And I set the field "lng" to "en"
+    Then I should see "Open language pack for editing"
+    And I should not see "Export custom strings"
+
+  @javascript
+  Scenario: Export button should not appear if no customization is saved into langpack
+    Given I log in as "admin"
+    And I navigate to "Language > Language customisation" in site administration
+    And I set the field "lng" to "en"
+    And I press "Open language pack for editing"
+    And I press "Continue"
+    And I set the field "Show strings of these components" to "moodle.php"
+    And I set the field "String identifier" to "accept"
+    And I press "Show strings"
+    And I set the field "core/accept" to "Accept-custom_export"
+    When I press "Apply changes and continue editing"
+    And I navigate to "Language > Language customisation" in site administration
+    And I set the field "lng" to "en"
+    Then I should see "Open language pack for editing"
+    And I should see "There are 1 modified strings."
+    And I should not see "Export custom strings"
+
+  @javascript
+  Scenario: Export the php-file including a customised langstring.
+    Given I log in as "admin"
+    And I navigate to "Language > Language customisation" in site administration
+    And I set the field "lng" to "en"
+    And I press "Open language pack for editing"
+    And I press "Continue"
+    And I set the field "Show strings of these components" to "moodle.php"
+    And I set the field "String identifier" to "accept"
+    And I press "Show strings"
+    And I set the field "core/accept" to "Accept-custom_export"
+    When I press "Save changes to the language pack"
+    And I should see "There are 1 modified strings."
+    And I click on "Continue" "button"
+    Then I set the field "lng" to "en"
+    And I click on "Export custom strings" "button"
+    And I set the field "Select component(s) to export" to "moodle.php"
index 508df54..b2afe62 100644 (file)
@@ -25,6 +25,6 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2021052500;
+$plugin->version   = 2021052501;
 $plugin->requires  = 2021052500;
 $plugin->component = 'tool_customlang'; // Full name of the plugin (used for diagnostics)
index 0fd5f72..9ea41b0 100644 (file)
@@ -323,6 +323,12 @@ class api {
             }
         }
 
+        if (empty($section) or $section == 'supportcontact') {
+            $settings->supportname = $CFG->supportname;
+            $settings->supportemail = $CFG->supportemail;
+            $settings->supportpage = $CFG->supportpage;
+        }
+
         return $settings;
     }
 
index 6fafc5f..f3e6d7d 100644 (file)
@@ -83,6 +83,7 @@ $string['iosappid_desc'] = 'This setting may be left as default unless you have
 $string['loginintheapp'] = 'Via the app';
 $string['logininthebrowser'] = 'Via a browser window (for SSO plugins)';
 $string['loginintheembeddedbrowser'] = 'Via an embedded browser (for SSO plugins)';
+$string['logoutconfirmation'] = 'Are you sure you want to log out from the mobile app on your mobile devices? By logging out, you will then need to re-enter your username and password in the mobile app on all devices where you have the app installed.';
 $string['mainmenu'] = 'Main menu';
 $string['managefiletypes'] = 'Manage file types';
 $string['minimumversion'] = 'If an app version is specified (3.8.0 or higher), any users using an older app version will be prompted to upgrade their app before being allowed access to the site.';
index 567af8b..6b9dbf3 100644 (file)
@@ -134,15 +134,11 @@ function tool_mobile_myprofile_navigation(\core_user\output\myprofile\tree $tree
         return;
     }
 
-    if (!$iscurrentuser) {
-        return;
-    }
-
     $newnodes = [];
     $mobilesettings = get_config('tool_mobile');
 
     // Check if we should display a QR code.
-    if (!empty($mobilesettings->qrcodetype)) {
+    if ($iscurrentuser && !empty($mobilesettings->qrcodetype)) {
         $mobileqr = null;
         $qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');
 
@@ -182,6 +178,13 @@ function tool_mobile_myprofile_navigation(\core_user\output\myprofile\tree $tree
         $mobilestrconnected = get_string('lastsiteaccess');
         if ($usertoken->lastaccess) {
             $mobilelastaccess = userdate($usertoken->lastaccess) . "&nbsp; (" . format_time(time() - $usertoken->lastaccess) . ")";
+            // Logout link.
+            $validtoken = empty($usertoken->validuntil) || time() < $usertoken->validuntil;
+            if ($iscurrentuser && $validtoken) {
+                $url = new moodle_url('/'.$CFG->admin.'/tool/mobile/logout.php', ['sesskey' => sesskey()]);
+                $logoutlink = html_writer::link($url, get_string('logout'));
+                $mobilelastaccess .= "&nbsp; ($logoutlink)";
+            }
         } else {
             // We should not reach this point.
             $mobilelastaccess = get_string("never");
diff --git a/admin/tool/mobile/logout.php b/admin/tool/mobile/logout.php
new file mode 100644 (file)
index 0000000..17a768a
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Log out a user from his external mobile devices (phones, tables, Moodle Desktop app, etc..)
+ *
+ * @package tool_mobile
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require(__DIR__ . '/../../../config.php');
+require_once($CFG->dirroot . '/admin/tool/mobile/lib.php');
+require_once($CFG->dirroot . '/webservice/lib.php');
+
+if (!$CFG->enablemobilewebservice) {
+    print_error('enablewsdescription', 'webservice');
+}
+
+require_login(null, false);
+
+// Require an active user: not guest, not suspended.
+core_user::require_active_user($USER);
+
+$redirecturl = new \moodle_url('/user/profile.php');
+
+if (optional_param('confirm', 0, PARAM_INT) && data_submitted()) {
+    require_sesskey();
+
+    // Get the mobile service token to be deleted.
+    $token = tool_mobile_get_token($USER->id);
+
+    if ($token) {
+        $webservicemanager = new webservice();
+        $webservicemanager->delete_user_ws_token($token->id);
+    }
+    redirect($redirecturl);
+}
+
+// Page settings.
+$title = get_string('logout');
+$context = context_system::instance();
+$PAGE->set_url(new \moodle_url('/'.$CFG->admin.'/tool/mobile/logout.php'));
+$PAGE->navbar->add($title);
+$PAGE->set_context($context);
+$PAGE->set_title($SITE->fullname. ': ' . $title);
+
+// Display the page.
+echo $OUTPUT->header();
+
+$message = get_string('logoutconfirmation', 'tool_mobile');
+$confirmurl = new \moodle_url('logout.php', ['confirm' => 1]);
+$yesbutton = new single_button($confirmurl, get_string('yes'), 'post');
+$nobutton = new single_button($redirecturl, get_string('no'));
+echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
+
+echo $OUTPUT->footer();
index 1a16eb7..0909aaf 100644 (file)
@@ -230,6 +230,10 @@ class tool_mobile_external_testcase extends externallib_advanced_testcase {
                 'value' => get_config('core_admin', 'coursecolor' . $number)
             ];
         }
+        $expected[] = ['name' => 'supportname', 'value' => $CFG->supportname];
+        $expected[] = ['name' => 'supportemail', 'value' => $CFG->supportemail];
+        $expected[] = ['name' => 'supportpage', 'value' => $CFG->supportpage];
+
         $this->assertCount(0, $result['warnings']);
         $this->assertEquals($expected, $result['settings']);
 
index 5c60510..d42fbe2 100644 (file)
@@ -46,6 +46,13 @@ class tool_replace_form extends moodleform {
         $mform->addElement('text', 'replace', get_string('replacewith', 'tool_replace'), 'size="50"', PARAM_RAW);
         $mform->addElement('static', 'replacest', '', get_string('replacewithhelp', 'tool_replace'));
         $mform->setType('replace', PARAM_RAW);
+
+        $mform->addElement('textarea', 'additionalskiptables', get_string("additionalskiptables", "tool_replace"),
+            array('rows' => 5, 'cols' => 50));
+        $mform->addElement('static', 'additionalskiptables_desc', '', get_string('additionalskiptables_desc', 'tool_replace'));
+        $mform->setType('additionalskiptables', PARAM_RAW);
+        $mform->setDefault('additionalskiptables', '');
+
         $mform->addElement('checkbox', 'shorten', get_string('shortenoversized', 'tool_replace'));
         $mform->addRule('replace', get_string('required'), 'required', null, 'client');
 
index 1f9e74b..b4244aa 100644 (file)
@@ -34,6 +34,7 @@ $help =
 Options:
 --search=STRING       String to search for.
 --replace=STRING      String to replace with.
+--skiptables=STRING   Skip these tables (comma separated list of tables).
 --shorten             Shorten result if necessary.
 --non-interactive     Perform the replacement without confirming.
 -h, --help            Print out this help.
@@ -46,6 +47,7 @@ list($options, $unrecognized) = cli_get_params(
     array(
         'search'  => null,
         'replace' => null,
+        'skiptables' => '',
         'shorten' => false,
         'non-interactive' => false,
         'help'    => false,
@@ -71,6 +73,7 @@ if (empty($options['shorten']) && core_text::strlen($options['search']) < core_t
 try {
     $search = validate_param($options['search'], PARAM_RAW);
     $replace = validate_param($options['replace'], PARAM_RAW);
+    $skiptables = validate_param($options['skiptables'], PARAM_RAW);
 } catch (invalid_parameter_exception $e) {
     cli_error(get_string('invalidcharacter', 'tool_replace'));
 }
@@ -85,7 +88,7 @@ if (!$options['non-interactive']) {
     }
 }
 
-if (!db_replace($search, $replace)) {
+if (!db_replace($search, $replace, $skiptables)) {
     cli_heading(get_string('error'));
     exit(1);
 }
index b3013d2..e4f2900 100644 (file)
@@ -57,7 +57,7 @@ if (!$data = $form->get_data()) {
 $PAGE->requires->js_init_code("window.scrollTo(0, 5000000);");
 
 echo $OUTPUT->box_start();
-db_replace($data->search, $data->replace);
+db_replace($data->search, $data->replace, $data->additionalskiptables);
 echo $OUTPUT->box_end();
 
 // Course caches are now rebuilt on the fly.
index 6117521..e8dce48 100644 (file)
@@ -22,7 +22,8 @@
  * @copyright  2011 Petr Skoda {@link http://skodak.org}
  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
-
+$string['additionalskiptables'] = 'Additional skip tables';
+$string['additionalskiptables_desc'] = 'Please specify the additional tables (comma separated list) you want to skip while running DB search and replace.';
 $string['cannotfit'] = 'The replacement is longer than the original and shortening is not allowed; cannot continue.';
 $string['disclaimer'] = 'I understand the risks of this operation';
 $string['doit'] = 'Yes, do it!';
diff --git a/admin/tool/uploaduser/classes/cli_helper.php b/admin/tool/uploaduser/classes/cli_helper.php
new file mode 100644 (file)
index 0000000..e258e7d
--- /dev/null
@@ -0,0 +1,402 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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 (file)
index 0000000..39c5529
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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 (file)
index 0000000..9e14640
--- /dev/null
@@ -0,0 +1,124 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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 (file)
index 0000000..a593024
--- /dev/null
@@ -0,0 +1,158 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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('<br />', $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 (file)
index 0000000..12c2101
--- /dev/null
@@ -0,0 +1,1327 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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 (file)
index 0000000..5db9e02
--- /dev/null
@@ -0,0 +1,53 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * 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);
+}
index eb881f6..a0ef7ab 100644 (file)
 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();
+
+$mform2 = new admin_uploaduser_form2(null,
+    ['columns' => $filecolumns, 'data' => ['iid' => $iid, 'previewrows' => $previewrows]]);
 
-// If a file has been uploaded, then process it
+// 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 '<p>';
-    if ($optype != UU_USER_UPDATE) {
-        echo get_string('userscreated', 'tool_uploaduser').': '.$usersnew.'<br />';
-    }
-    if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
-        echo get_string('usersupdated', 'tool_uploaduser').': '.$usersupdated.'<br />';
-    }
-    if ($allowdeletes) {
-        echo get_string('usersdeleted', 'tool_uploaduser').': '.$deletes.'<br />';
-        echo get_string('deleteerrors', 'tool_uploaduser').': '.$deleteerrors.'<br />';
-    }
-    if ($allowrenames) {
-        echo get_string('usersrenamed', 'tool_uploaduser').': '.$renames.'<br />';
-        echo get_string('renameerrors', 'tool_uploaduser').': '.$renameerrors.'<br />';
-    }
-    if ($usersskipped) {
-        echo get_string('usersskipped', 'tool_uploaduser').': '.$usersskipped.'<br />';
-    }
-    echo get_string('usersweakpassword', 'tool_uploaduser').': '.$weakpasswords.'<br />';
-    echo get_string('errors', 'tool_uploaduser').': '.$userserrors.'</p>';
+    echo html_writer::tag('p', join('<br />', $process->get_stats()));
     echo $OUTPUT->box_end();
 
-    if ($bulk) {
+    if ($process->get_bulk()) {
         echo $OUTPUT->continue_button($bulknurl);
     } else {
         echo $OUTPUT->continue_button($returnurl);
@@ -1181,92 +104,22 @@ if ($formdata = $mform2->is_cancelled()) {
     die;
 }
 
-// Print the header
+// Print the header.
 echo $OUTPUT->header();
 
 echo $OUTPUT->heading(get_string('uploaduserspreview', 'tool_uploaduser'));
 
 // NOTE: this is JUST csv processing preview, we must not prevent import from here if there is something in the file!!
-//       this was intended for validation of csv formatting and encoding, not filtering the data!!!!
-//       we definitely must not process the whole file!
+// this was intended for validation of csv formatting and encoding, not filtering the data!!!!
+// we definitely must not process the whole file!
 
-// preview table data
-$data = array();
-$cir->init();
-$linenum = 1; //column header is first line
-$noerror = true; // Keep status of any error.
-while ($linenum <= $previewrows and $fields = $cir->next()) {
-    $linenum++;
-    $rowcols = array();
-    $rowcols['line'] = $linenum;
-    foreach($fields as $key => $field) {
-        $rowcols[$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', array('username'=>$stdusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
-            $rowcols['username'] = html_writer::link(new moodle_url('/user/profile.php', array('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'][] = $stremailduplicate;
-        }
-    }
-
-    if (isset($rowcols['city'])) {
-        $rowcols['city'] = $rowcols['city'];
-    }
-
-    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.
-    $noerror = uu_check_custom_profile_data($rowcols) && $noerror;
-    $rowcols['status'] = implode('<br />', $rowcols['status']);
-    $data[] = $rowcols;
-}
-if ($fields = $cir->next()) {
-    $data[] = array_fill(0, count($fields) + 2, '...');
-}
-$cir->close();
-
-$table = new html_table();
-$table->id = "uupreview";
-$table->attributes['class'] = 'generaltable';
-$table->tablealign = 'center';
-$table->summary = get_string('uploaduserspreview', 'tool_uploaduser');
-$table->head = array();
-$table->data = $data;
-
-$table->head[] = get_string('uucsvline', 'tool_uploaduser');
-foreach ($filecolumns as $column) {
-    $table->head[] = $column;
-}
-$table->head[] = get_string('status');
+// Preview table data.
+$table = new \tool_uploaduser\preview($cir, $filecolumns, $previewrows);
 
-echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
+echo html_writer::tag('div', html_writer::table($table), ['class' => 'flexible-wrap']);
 
-// Print the form if valid values are available
-if ($noerror) {
+// Print the form if valid values are available.
+if ($table->get_no_error()) {
     $mform2->display();
 }
 echo $OUTPUT->footer();
index 6e875e6..9f65fa5 100644 (file)
@@ -27,19 +27,30 @@ $string['allowdeletes'] = 'Allow deletes';
 $string['allowrenames'] = 'Allow renames';
 $string['allowsuspends'] = 'Allow suspending and activating of accounts';
 $string['assignedsysrole'] = 'Assigned system role {$a}';
+$string['clidefault'] = 'Default:';
+$string['clierrorargument'] = 'Value for argument --{$a->name} is not valid. Allowed values: {$a->values}';
+$string['clifile'] = 'Path to CSV file with the user data. Required.';
+$string['clifilenotreadable'] = 'File {$a} does not exist or is not readable';
+$string['clihelp'] = 'Print out this help.';
+$string['climissingargument'] = 'Argument --{$a} is required';
+$string['clititle'] = 'Command line Upload user tool.';
+$string['clivalidationerror'] = 'Validation error:';
 $string['csvdelimiter'] = 'CSV delimiter';
 $string['defaultvalues'] = 'Default values';
 $string['deleteerrors'] = 'Delete errors';
 $string['encoding'] = 'Encoding';
 $string['errormnetadd'] = 'Can not add remote users';
+$string['errorprefix'] = 'Error:';
 $string['errors'] = 'Errors';
 $string['examplecsv'] = 'Example text file';
 $string['examplecsv_help'] = 'To use the example text file, download it then open it with a text or spreadsheet editor. Leave the first line unchanged, then edit the following lines (records) and add your user data, adding more lines as necessary. Save the file as CSV then upload it.
 
 The example text file may also be used for testing, as you are able to preview user data and can choose to cancel the action before user accounts are created.';
+$string['infoprefix'] = 'Info:';
 $string['invalidupdatetype'] = 'This option cannot be selected with the chosen upload type.';
 $string['invaliduserdata'] = 'Invalid data detected for user {$a} and it has been automatically cleaned.';
 $string['invalidtheme'] = 'Theme "{$a}" is not installed and will be ignored.';
+$string['linex'] = 'Line {$a}';
 $string['nochanges'] = 'No changes';
 $string['notheme'] = 'No theme is defined for this user.';
 $string['pluginname'] = 'User upload';
@@ -106,3 +117,4 @@ $string['uuupdatemissing'] = 'Fill in missing from file and defaults';
 $string['uuupdatetype'] = 'Existing user details';
 $string['uuusernametemplate'] = 'Username template';
 $string['privacy:metadata'] = 'The User upload plugin does not store any personal data.';
+$string['warningprefix'] = 'Warning:';
index 46b8bc4..68481c7 100644 (file)
@@ -55,14 +55,38 @@ define('UU_PWRESET_ALL', 2);
  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 class uu_progress_tracker {
-    private $_row;
+    /** @var array */
+    protected $_row;
 
     /**
      * The columns shown on the table.
      * @var array
      */
-    public $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email',
-                            'password', 'auth', 'enrolments', 'suspended', 'theme', 'deleted');
+    public $columns = [];
+    /** @var array column headers */
+    protected $headers = [];
+
+    /**
+     * uu_progress_tracker constructor.
+     */
+    public function __construct() {
+        $this->headers = [
+            'status' => get_string('status'),
+            'line' => get_string('uucsvline', 'tool_uploaduser'),
+            'id' => 'ID',
+            'username' => get_string('username'),
+            'firstname' => get_string('firstname'),
+            'lastname' => get_string('lastname'),
+            'email' => get_string('email'),
+            'password' => get_string('password'),
+            'auth' => get_string('authentication'),
+            'enrolments' => get_string('enrolments', 'enrol'),
+            'suspended' => get_string('suspended', 'auth'),
+            'theme' => get_string('theme'),
+            'deleted' => get_string('delete'),
+        ];
+        $this->columns = array_keys($this->headers);
+    }
 
     /**
      * Print table header.
@@ -72,19 +96,9 @@ class uu_progress_tracker {
         $ci = 0;
         echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'tool_uploaduser').'">';
         echo '<tr class="heading r0">';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'tool_uploaduser').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('suspended', 'auth').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('theme').'</th>';
-        echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
+        foreach ($this->headers as $key => $header) {
+            echo '<th class="header c'.$ci++.'" scope="col">'.$header.'</th>';
+        }
         echo '</tr>';
         $this->_row = null;
     }
diff --git a/admin/tool/uploaduser/tests/cli_test.php b/admin/tool/uploaduser/tests/cli_test.php
new file mode 100644 (file)
index 0000000..a13c047
--- /dev/null
@@ -0,0 +1,295 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Tests for CLI tool_uploaduser.
+ *
+ * @package    tool_uploaduser
+ * @copyright  2020 Marina Glancy
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use \tool_uploaduser\cli_helper;
+
+/**
+ * Tests for CLI tool_uploaduser.
+ *
+ * @package    tool_uploaduser
+ * @copyright  2020 Marina Glancy
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_uploaduser_cli_testcase extends advanced_testcase {
+
+    /**
+     * Generate cli_helper and mock $_SERVER['argv']
+     *
+     * @param array $mockargv
+     * @return \tool_uploaduser\cli_helper
+     */
+    protected function construct_helper(array $mockargv = []) {
+        if (array_key_exists('argv', $_SERVER)) {
+            $oldservervars = $_SERVER['argv'];
+        }
+        $_SERVER['argv'] = array_merge([''], $mockargv);
+        $clihelper = new cli_helper(\tool_uploaduser\local\text_progress_tracker::class);
+        if (isset($oldservervars)) {
+            $_SERVER['argv'] = $oldservervars;
+        } else {
+            unset($_SERVER['argv']);
+        }
+        return $clihelper;
+    }
+
+    /**
+     * Tests simple upload with course enrolment and group allocation
+     */
+    public function test_upload_with_course_enrolment() {
+        global $CFG;
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
+        $g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
+        $g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath"]);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 2 users were created.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(2, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users created: 2', $stats[0]);
+
+        // Tom Jones and Trent Reznor are enrolled into the course, first one to group $g1 and second to group $g2.
+        $enrols = array_values(enrol_get_course_users($course->id));
+        $this->assertEqualsCanonicalizing(['reznor', 'jonest'], [$enrols[0]->username, $enrols[1]->username]);
+        $g1members = groups_get_groups_members($g1->id);
+        $this->assertEquals(1, count($g1members));
+        $this->assertEquals('Jones', $g1members[key($g1members)]->lastname);
+        $g2members = groups_get_groups_members($g2->id);
+        $this->assertEquals(1, count($g2members));
+        $this->assertEquals('Reznor', $g2members[key($g2members)]->lastname);
+    }
+
+    /**
+     * Test applying defaults during the user upload
+     */
+    public function test_upload_with_applying_defaults() {
+        global $CFG;
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
+        $g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
+        $g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath", '--city=Brighton', '--department=Purchasing']);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 2 users were created.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(2, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users created: 2', $stats[0]);
+
+        // Users have default values applied.
+        $user1 = core_user::get_user_by_username('jonest');
+        $this->assertEquals('Brighton', $user1->city);
+        $this->assertEquals('Purchasing', $user1->department);
+    }
+
+    /**
+     * User upload with user profile fields
+     */
+    public function test_upload_with_profile_fields() {
+        global $DB, $CFG;
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $categoryid = $DB->insert_record('user_info_category', ['name' => 'Cat 1', 'sortorder' => 1]);
+        $this->field1 = $DB->insert_record('user_info_field', [
+            'shortname' => 'superfield', 'name' => 'Super field', 'categoryid' => $categoryid,
+            'datatype' => 'text', 'signup' => 1, 'visible' => 1, 'required' => 1, 'sortorder' => 1]);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users_profile.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath"]);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 2 users were created.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(2, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users created: 2', $stats[0]);
+
+        // Created users have data in the profile fields.
+        $user1 = core_user::get_user_by_username('reznort');
+        $profilefields1 = profile_user_record($user1->id);
+        $this->assertEquals((object)['superfield' => 'Loves cats'], $profilefields1);
+    }
+
+    /**
+     * Testing that help for CLI does not throw errors
+     */
+    public function test_cli_help() {
+        $this->resetAfterTest();
+        $this->setAdminUser();
+        $clihelper = $this->construct_helper(["--help"]);
+        ob_start();
+        $clihelper->print_help();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // Basically a test that everything can be parsed and displayed without errors. Check that some options are present.
+        $this->assertEquals(1, preg_match('/--delimiter_name=VALUE/', $output));
+        $this->assertEquals(1, preg_match('/--uutype=VALUE/', $output));
+        $this->assertEquals(1, preg_match('/--auth=VALUE/', $output));
+    }
+
+    /**
+     * Testing skipped user when one exists
+     */
+    public function test_create_when_user_exists() {
+        global $CFG;
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
+        $g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
+        $g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
+
+        // Create a user with username jonest.
+        $user1 = $this->getDataGenerator()->create_user(['username' => 'jonest', 'email' => 'jonest@someplace.edu']);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath"]);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 1 user was created and 1 skipped.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(1, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users created: 1', $stats[0]);
+        $this->assertEquals('Users skipped: 1', $stats[1]);
+
+        // Trent Reznor is enrolled into the course, Tom Jones is not!
+        $enrols = array_values(enrol_get_course_users($course->id));
+        $this->assertEqualsCanonicalizing(['reznor'], [$enrols[0]->username]);
+    }
+
+    /**
+     * Testing update mode - do not update user records but allow enrolments
+     */
+    public function test_enrolments_when_user_exists() {
+        global $CFG;
+        require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
+        $g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
+        $g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
+
+        // Create a user with username jonest.
+        $this->getDataGenerator()->create_user(['username' => 'jonest', 'email' => 'jonest@someplace.edu',
+            'firstname' => 'OLDNAME']);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath", '--uutype='.UU_USER_UPDATE]);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 1 user was created and 1 skipped.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(0, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users updated: 0', $stats[0]);
+        $this->assertEquals('Users skipped: 1', $stats[1]);
+
+        // Tom Jones is enrolled into the course.
+        $enrols = array_values(enrol_get_course_users($course->id));
+        $this->assertEqualsCanonicalizing(['jonest'], [$enrols[0]->username]);
+        // User reznor is not created.
+        $this->assertFalse(core_user::get_user_by_username('reznor'));
+        // User jonest is not updated.
+        $this->assertEquals('OLDNAME', core_user::get_user_by_username('jonest')->firstname);
+    }
+
+    /**
+     * Testing update mode - update user records and perform enrolments.
+     */
+    public function test_udpate_user() {
+        global $CFG;
+        require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/uploaduser/locallib.php');
+
+        $this->resetAfterTest();
+        set_config('passwordpolicy', 0);
+        $this->setAdminUser();
+
+        $course = $this->getDataGenerator()->create_course(['fullname' => 'Maths', 'shortname' => 'math102']);
+        $g1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 1', 'idnumber' => 'S1']);
+        $g2 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Section 3', 'idnumber' => 'S3']);
+
+        // Create a user with username jonest.
+        $this->getDataGenerator()->create_user(['username' => 'jonest',
+            'email' => 'jonest@someplace.edu', 'firstname' => 'OLDNAME']);
+
+        $filepath = $CFG->dirroot.'/lib/tests/fixtures/upload_users.csv';
+
+        $clihelper = $this->construct_helper(["--file=$filepath", '--uutype='.UU_USER_UPDATE,
+            '--uuupdatetype='.UU_UPDATE_FILEOVERRIDE]);
+        ob_start();
+        $clihelper->process();
+        $output = ob_get_contents();
+        ob_end_clean();
+
+        // CLI output suggests that 1 user was created and 1 skipped.
+        $stats = $clihelper->get_stats();
+        $this->assertEquals(0, preg_match_all('/New user/', $output));
+        $this->assertEquals('Users updated: 1', $stats[0]);
+        $this->assertEquals('Users skipped: 1', $stats[1]);
+
+        // Tom Jones is enrolled into the course.
+        $enrols = array_values(enrol_get_course_users($course->id));
+        $this->assertEqualsCanonicalizing(['jonest'], [$enrols[0]->username]);
+        // User reznor is not created.
+        $this->assertFalse(core_user::get_user_by_username('reznor'));
+        // User jonest is updated, new first name is Tom.
+        $this->assertEquals('Tom', core_user::get_user_by_username('jonest')->firstname);
+    }
+}
index 552ea4c..0da4f64 100644 (file)
@@ -68,6 +68,18 @@ class admin_uploaduser_form1 extends moodleform {
 
         $this->add_action_buttons(false, get_string('uploadusers', 'tool_uploaduser'));
     }
+
+    /**
+     * Returns list of elements and their default values, to be used in CLI
+     *
+     * @return array
+     */
+    public function get_form_for_cli() {
+        $elements = array_filter($this->_form->_elements, function($element) {
+            return !in_array($element->getName(), ['buttonar', 'userfile', 'previewrows']);
+        });
+        return [$elements, $this->_form->_defaultValues];
+    }
 }
 
 
@@ -434,4 +446,25 @@ class admin_uploaduser_form2 extends moodleform {
 
         return $data;
     }
+
+    /**
+     * Returns list of elements and their default values, to be used in CLI
+     *
+     * @return array
+     */
+    public function get_form_for_cli() {
+        $elements = array_filter($this->_form->_elements, function($element) {
+            return !in_array($element->getName(), ['buttonar', 'uubulk']);
+        });
+        return [$elements, $this->_form->_defaultValues];
+    }
+
+    /**
+     * Returns validation errors (used in CLI)
+     *
+     * @return array
+     */
+    public function get_validation_errors(): array {
+        return $this->_form->_errors;
+    }
 }
index 622047c..5ec09bd 100644 (file)
@@ -116,7 +116,6 @@ Feature: availability_grade
     And I click on "Grade" "link" in the "s@example.com" "table_row"
     And I set the field "Grade out of 100" to "40"
     And I click on "Save changes" "button"
-    And I press "OK"
     And I click on "Edit settings" "link"
 
     # Log back in as student.
index 4a1f187..d404126 100644 (file)
@@ -126,8 +126,9 @@ class core_backup_renderer extends plugin_renderer_base {
 
         $html  = html_writer::start_tag('div', array('class' => 'backup-restore'));
 
-        $html .= html_writer::start_tag('div', array('class' => 'backup-section'));
-        $html .= $this->output->heading(get_string('backupdetails', 'backup'), 2, array('class' => 'header'));
+        $html .= html_writer::start_tag('div', ['class' => 'backup-section',
+            'role' => 'table', 'aria-labelledby' => 'backupdetailsheader']);
+        $html .= $this->output->heading(get_string('backupdetails', 'backup'), 2, 'header', 'backupdetailsheader');
         $html .= $this->backup_detail_pair(get_string('backuptype', 'backup'), get_string('backuptype'.$details->type, 'backup'));
         $html .= $this->backup_detail_pair(get_string('backupformat', 'backup'), get_string('backupformat'.$details->format, 'backup'));
         $html .= $this->backup_detail_pair(get_string('backupmode', 'backup'), get_string('backupmode'.$details->mode, 'backup'));
@@ -153,8 +154,9 @@ class core_backup_renderer extends plugin_renderer_base {
 
         $html .= html_writer::end_tag('div');
 
-        $html .= html_writer::start_tag('div', array('class' => 'backup-section settings-section'));
-        $html .= $this->output->heading(get_string('backupsettings', 'backup'), 2, array('class' => 'header'));
+        $html .= html_writer::start_tag('div', ['class' => 'backup-section settings-section',
+            'role' => 'table', 'aria-labelledby' => 'backupsettingsheader']);
+        $html .= $this->output->heading(get_string('backupsettings', 'backup'), 2, 'header', 'backupsettingsheader');
         foreach ($details->root_settings as $label => $value) {
             if ($label == 'filename' or $label == 'user_files') {
                 continue;
@@ -164,8 +166,9 @@ class core_backup_renderer extends plugin_renderer_base {
         $html .= html_writer::end_tag('div');
 
         if ($details->type === 'course') {
-            $html .= html_writer::start_tag('div', array('class' => 'backup-section'));
-            $html .= $this->output->heading(get_string('backupcoursedetails', 'backup'), 2, array('class' => 'header'));
+            $html .= html_writer::start_tag('div', ['class' => 'backup-section',
+                    'role' => 'table', 'aria-labelledby' => 'backupcoursedetailsheader']);
+            $html .= $this->output->heading(get_string('backupcoursedetails', 'backup'), 2, 'header', 'backupcoursedetailsheader');
             $html .= $this->backup_detail_pair(get_string('coursetitle', 'backup'), $details->course->title);
             $html .= $this->backup_detail_pair(get_string('courseid', 'backup'), $details->course->courseid);
 
@@ -200,7 +203,7 @@ class core_backup_renderer extends plugin_renderer_base {
                         $table->data = array();
                     }
                     $name = get_string('pluginname', $activity->modulename);
-                    $icon = new image_icon('icon', $name, $activity->modulename, array('class' => 'iconlarge icon-pre'));
+                    $icon = new image_icon('icon', '', $activity->modulename, ['class' => 'iconlarge icon-pre']);
                     $table->data[] = array(
                         $this->output->render($icon).$name,
                         $activity->title,
@@ -424,13 +427,25 @@ class core_backup_renderer extends plugin_renderer_base {
     protected function backup_detail_pair($label, $value) {
         static $count = 0;
         $count ++;
-        $html  = html_writer::start_tag('div', array('class' => 'detail-pair'));
-        $html .= html_writer::tag('label', $label, array('class' => 'detail-pair-label', 'for' => 'detail-pair-value-'.$count));
-        $html .= html_writer::tag('div', $value, array('class' => 'detail-pair-value pl-2', 'name' => 'detail-pair-value-'.$count));
+        $html  = html_writer::start_tag('div', ['class' => 'detail-pair', 'role' => 'row']);
+        $html .= html_writer::tag('div', $label, ['class' => 'detail-pair-label mb-2', 'role' => 'cell']);
+        $html .= html_writer::tag('div', $value, ['class' => 'detail-pair-value pl-2', 'role' => 'cell']);
         $html .= html_writer::end_tag('div');
         return $html;
     }
 
+    /**
+     * Creates a unique id string by appending an incremental number to the prefix.
+     *
+     * @param string $prefix To be used as the left part of the id string.
+     * @return string
+     */
+    protected function make_unique_id(string $prefix): string {
+        static $count = 0;
+
+        return $prefix . '-' . $count++;
+    }
+
     /**
      * Created a detailed pairing with an input
      *
@@ -448,9 +463,11 @@ class core_backup_renderer extends plugin_renderer_base {
         } else {
             $description = '';
         }
+        $id = $this->make_unique_id('detail-pair-value');
         return $this->backup_detail_pair(
-            $label,
-            html_writer::empty_tag('input', $attributes + array('name' => $name, 'type' => $type, 'value' => $value)) . $description
+            html_writer::label($label, $id),
+            html_writer::empty_tag('input', $attributes + ['id' => $id, 'name' => $name, 'type' => $type, 'value' => $value]) .
+                $description
         );
     }
 
@@ -718,8 +735,6 @@ class core_backup_renderer extends plugin_renderer_base {
      * @return string
      */
     public function render_restore_course_search(restore_course_search $component) {
-        $url = $component->get_url();
-
         $output = html_writer::start_tag('div', array('class' => 'restore-course-search mb-1'));
         $output .= html_writer::start_tag('div', array('class' => 'rcs-results table-sm w-75'));
 
@@ -733,11 +748,18 @@ class core_backup_renderer extends plugin_renderer_base {
                 if (!$course->visible) {
                     $row->attributes['class'] .= ' dimmed';
                 }
-                $row->cells = array(
-                    html_writer::empty_tag('input', array('type' => 'radio', 'name' => 'targetid', 'value' => $course->id)),
-                    format_string($course->shortname, true, array('context' => context_course::instance($course->id))),
-                    format_string($course->fullname, true, array('context' => context_course::instance($course->id)))
-                );
+                $id = $this->make_unique_id('restore-course');
+                $row->cells = [
+                    html_writer::empty_tag('input', ['type' => 'radio', 'name' => 'targetid', 'value' => $course->id,
+                        'id' => $id]),
+                    html_writer::label(
+                        format_string($course->shortname, true, ['context' => context_course::instance($course->id)]),
+                        $id,
+                        true,
+                        ['class' => 'd-block']
+                    ),
+                    format_string($course->fullname, true, ['context' => context_course::instance($course->id)])
+                ];
                 $table->data[] = $row;
             }
             if ($component->has_more_results()) {
@@ -779,8 +801,6 @@ class core_backup_renderer extends plugin_renderer_base {
      * @return string
      */
     public function render_import_course_search(import_course_search $component) {
-        $url = $component->get_url();
-
         $output = html_writer::start_tag('div', array('class' => 'import-course-search'));
         if ($component->get_count() === 0) {
             $output .= $this->output->notification(get_string('nomatchingcourses', 'backup'));
@@ -790,6 +810,8 @@ class core_backup_renderer extends plugin_renderer_base {
                 'type' => 'text',
                 'name' => restore_course_search::$VAR_SEARCH,
                 'value' => $component->get_search(),
+                'aria-label' => get_string('searchcourses'),
+                'placeholder' => get_string('searchcourses'),
                 'class' => 'form-control'
             );
             $output .= html_writer::empty_tag('input', $attrs);
@@ -825,11 +847,18 @@ class core_backup_renderer extends plugin_renderer_base {
             if (!$course->visible) {
                 $row->attributes['class'] .= ' dimmed';
             }
-            $row->cells = array(
-                html_writer::empty_tag('input', array('type' => 'radio', 'name' => 'importid', 'value' => $course->id)),
-                format_string($course->shortname, true, array('context' => context_course::instance($course->id))),
-                format_string($course->fullname, true, array('context' => context_course::instance($course->id)))
-            );
+            $id = $this->make_unique_id('import-course');
+            $row->cells = [
+                html_writer::empty_tag('input', ['type' => 'radio', 'name' => 'importid', 'value' => $course->id,
+                    'id' => $id]),
+                html_writer::label(
+                    format_string($course->shortname, true, ['context' => context_course::instance($course->id)]),
+                    $id,
+                    true,
+                    ['class' => 'd-block']
+                ),
+                format_string($course->fullname, true, ['context' => context_course::instance($course->id)])
+            ];
             $table->data[] = $row;
         }
         if ($component->has_more_results()) {
@@ -848,6 +877,8 @@ class core_backup_renderer extends plugin_renderer_base {
             'type' => 'text',
             'name' => restore_course_search::$VAR_SEARCH,
             'value' => $component->get_search(),
+            'aria-label' => get_string('searchcourses'),
+            'placeholder' => get_string('searchcourses'),
             'class' => 'form-control');
         $output .= html_writer::empty_tag('input', $attrs);
         $attrs = array(
@@ -870,8 +901,6 @@ class core_backup_renderer extends plugin_renderer_base {
      * @return string
      */
     public function render_restore_category_search(restore_category_search $component) {
-        $url = $component->get_url();
-
         $output = html_writer::start_tag('div', array('class' => 'restore-course-search mb-1'));
         $output .= html_writer::start_tag('div', array('class' => 'rcs-results table-sm w-75'));
 
@@ -887,12 +916,19 @@ class core_backup_renderer extends plugin_renderer_base {
                     $row->attributes['class'] .= ' dimmed';
                 }
                 $context = context_coursecat::instance($category->id);
-                $row->cells = array(
-                    html_writer::empty_tag('input', array('type' => 'radio', 'name' => 'targetid', 'value' => $category->id)),
-                    format_string($category->name, true, array('context' => context_coursecat::instance($category->id))),
+                $id = $this->make_unique_id('restore-category');
+                $row->cells = [
+                    html_writer::empty_tag('input', ['type' => 'radio', 'name' => 'targetid', 'value' => $category->id,
+                        'id' => $id]),
+                    html_writer::label(
+                        format_string($category->name, true, ['context' => context_coursecat::instance($category->id)]),
+                        $id,
+                        true,
+                        ['class' => 'd-block']
+                    ),
                     format_text(file_rewrite_pluginfile_urls($category->description, 'pluginfile.php', $context->id,
-                        'coursecat', 'description', null), $category->descriptionformat, array('overflowdiv' => true))
-                );
+                        'coursecat', 'description', null), $category->descriptionformat, ['overflowdiv' => true])
+                ];
                 $table->data[] = $row;
             }
             if ($component->has_more_results()) {
@@ -918,7 +954,7 @@ class core_backup_renderer extends plugin_renderer_base {
             'inform' => true,
             'extraclasses' => 'rcs-search mb-3 w-25',
             'inputname' => restore_category_search::$VAR_SEARCH,
-            'searchstring' => get_string('search'),
+            'searchstring' => get_string('searchcoursecategories'),
             'query' => $component->get_search(),
         ];
         $output .= $this->output->render_from_template('core/search_input', $data);
index 66c348e..5a53e7e 100644 (file)
@@ -18,7 +18,7 @@ if (empty($CFG->enablecalendarexport)) {
 $checkuserid = !empty($userid) && $user = $DB->get_record('user', array('id' => $userid), 'id,password');
 //allowing for fallback check of old url - MDL-27542
 $checkusername = !empty($username) && $user = $DB->get_record('user', array('username' => $username), 'id,password');
-if (!$checkuserid && !$checkusername) {
+if ((!$checkuserid && !$checkusername) || !$user) {
     //No such user
     die('Invalid authentication');
 }
index 2cd824c..f7cd860 100644 (file)
@@ -58,7 +58,6 @@ Feature: Restrict activity availability through grade conditions
     And I set the following fields to these values:
       | Grade | 21 |
     And I press "Save changes"
-    And I press "OK"
     And I follow "Edit settings"
     And I log out
     And I log in as "student1"
index 6785e90..f65c9fa 100644 (file)
@@ -91,7 +91,6 @@ Feature: Restrict sections availability through completion or grade conditions
     And I set the following fields to these values:
       | Grade | 21 |
     And I press "Save changes"
-    And I press "OK"
     And I follow "Edit settings"
     And I log out
     And I log in as "student1"
index 3b08693..c267d2a 100644 (file)
@@ -13,7 +13,7 @@
     "require-dev": {
         "phpunit/phpunit": "7.5.*",
         "phpunit/dbunit": "4.0.*",
-        "moodlehq/behat-extension": "3.39.3",
+        "moodlehq/behat-extension": "3.400.0",
         "mikey179/vfsstream": "^1.6",
         "instaclick/php-webdriver": "dev-local as 1.x-dev"
     }
index 11dbff6..f6c97d5 100644 (file)
@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "b1953ceec577434625a7aee12f650daa",
+    "content-hash": "0716ef75702afddcf37c7abef09fbcd1",
     "packages": [],
     "packages-dev": [
         {
         },
         {
             "name": "doctrine/instantiator",
-            "version": "1.3.0",
+            "version": "1.3.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/doctrine/instantiator.git",
-                "reference": "ae466f726242e637cebdd526a7d991b9433bacf1"
+                "reference": "f350df0268e904597e3bd9c4685c53e0e333feea"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/doctrine/instantiator/zipball/ae466f726242e637cebdd526a7d991b9433bacf1",
-                "reference": "ae466f726242e637cebdd526a7d991b9433bacf1",
+                "url": "https://api.github.com/repos/doctrine/instantiator/zipball/f350df0268e904597e3bd9c4685c53e0e333feea",
+                "reference": "f350df0268e904597e3bd9c4685c53e0e333feea",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1"
+                "php": "^7.1 || ^8.0"
             },
             "require-dev": {
                 "doctrine/coding-standard": "^6.0",
                 "constructor",
                 "instantiate"
             ],
-            "time": "2019-10-21T16:45:58+00:00"
+            "funding": [
+                {
+                    "url": "https://www.doctrine-project.org/sponsorship.html",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://www.patreon.com/phpdoctrine",
+                    "type": "patreon"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finstantiator",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-05-29T17:27:14+00:00"
         },
         {
             "name": "fabpot/goutte",
         },
         {
             "name": "guzzlehttp/guzzle",
-            "version": "6.5.3",
+            "version": "6.5.5",
             "source": {
                 "type": "git",
                 "url": "https://github.com/guzzle/guzzle.git",
-                "reference": "aab4ebd862aa7d04f01a4b51849d657db56d882e"
+                "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/guzzle/zipball/aab4ebd862aa7d04f01a4b51849d657db56d882e",
-                "reference": "aab4ebd862aa7d04f01a4b51849d657db56d882e",
+                "url": "https://api.github.com/repos/guzzle/guzzle/zipball/9d4290de1cfd701f38099ef7e183b64b4b7b0c5e",
+                "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e",
                 "shasum": ""
             },
             "require": {
                 "guzzlehttp/promises": "^1.0",
                 "guzzlehttp/psr7": "^1.6.1",
                 "php": ">=5.5",
-                "symfony/polyfill-intl-idn": "^1.11"
+                "symfony/polyfill-intl-idn": "^1.17.0"
             },
             "require-dev": {
                 "ext-curl": "*",
                 "rest",
                 "web service"
             ],
-            "time": "2020-04-18T10:38:46+00:00"
+            "time": "2020-06-16T21:01:06+00:00"
         },
         {
             "name": "guzzlehttp/promises",
         },
         {
             "name": "moodlehq/behat-extension",
-            "version": "v3.39.3",
+            "version": "v3.400.0",
             "source": {
                 "type": "git",
                 "url": "https://github.com/moodlehq/moodle-behat-extension.git",
         },
         {
             "name": "myclabs/deep-copy",
-            "version": "1.9.5",
+            "version": "1.10.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/myclabs/DeepCopy.git",
-                "reference": "b2c28789e80a97badd14145fda39b545d83ca3ef"
+                "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/b2c28789e80a97badd14145fda39b545d83ca3ef",
-                "reference": "b2c28789e80a97badd14145fda39b545d83ca3ef",
+                "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/969b211f9a51aa1f6c01d1d2aef56d3bd91598e5",
+                "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1"
+                "php": "^7.1 || ^8.0"
             },
             "replace": {
                 "myclabs/deep-copy": "self.version"
                 "object",
                 "object graph"
             ],
-            "time": "2020-01-17T21:11:47+00:00"
+            "funding": [
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-06-29T13:22:24+00:00"
+        },
+        {
+            "name": "paragonie/random_compat",
+            "version": "v9.99.99",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/paragonie/random_compat.git",
+                "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95",
+                "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95",
+                "shasum": ""
+            },
+            "require": {
+                "php": "^7"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "4.*|5.*",
+                "vimeo/psalm": "^1"
+            },
+            "suggest": {
+                "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
+            },
+            "type": "library",
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Paragon Initiative Enterprises",
+                    "email": "security@paragonie.com",
+                    "homepage": "https://paragonie.com"
+                }
+            ],
+            "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
+            "keywords": [
+                "csprng",
+                "polyfill",
+                "pseudorandom",
+                "random"
+            ],
+            "time": "2018-07-02T15:55:56+00:00"
         },
         {
             "name": "phar-io/manifest",
         },
         {
             "name": "phpdocumentor/reflection-common",
-            "version": "2.0.0",
+            "version": "2.2.0",
             "source": {
                 "type": "git",
                 "url": "https://github.com/phpDocumentor/ReflectionCommon.git",
-                "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a"
+                "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/63a995caa1ca9e5590304cd845c15ad6d482a62a",
-                "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a",
+                "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b",
+                "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b",
                 "shasum": ""
             },
             "require": {
-                "php": ">=7.1"
-            },
-            "require-dev": {
-                "phpunit/phpunit": "~6"
+                "php": "^7.2 || ^8.0"
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.x-dev"
+                    "dev-2.x": "2.x-dev"
                 }
             },
             "autoload": {
                 "reflection",
                 "static analysis"
             ],
-            "time": "2018-08-07T13:53:10+00:00"
+            "time": "2020-06-27T09:03:43+00:00"
         },
         {
             "name": "phpdocumentor/reflection-docblock",
-            "version": "5.1.0",
+            "version": "5.2.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
-                "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e"
+                "reference": "d870572532cd70bc3fab58f2e23ad423c8404c44"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e",
-                "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e",
+                "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/d870572532cd70bc3fab58f2e23ad423c8404c44",
+                "reference": "d870572532cd70bc3fab58f2e23ad423c8404c44",
                 "shasum": ""
             },
             "require": {
-                "ext-filter": "^7.1",
-                "php": "^7.2",
-                "phpdocumentor/reflection-common": "^2.0",
-                "phpdocumentor/type-resolver": "^1.0",
-                "webmozart/assert": "^1"
+                "ext-filter": "*",
+                "php": "^7.2 || ^8.0",
+                "phpdocumentor/reflection-common": "^2.2",
+                "phpdocumentor/type-resolver": "^1.3",
+                "webmozart/assert": "^1.9.1"
             },
             "require-dev": {
-                "doctrine/instantiator": "^1",
-                "mockery/mockery": "^1"
+                "mockery/mockery": "~1.3.2"
             },
             "type": "library",
             "extra": {
                 }
             ],
             "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
-            "time": "2020-02-22T12:28:44+00:00"
+            "time": "2020-08-15T11:14:08+00:00"
         },
         {
             "name": "phpdocumentor/type-resolver",
-            "version": "1.1.0",
+            "version": "1.3.0",
             "source": {
                 "type": "git",
                 "url": "https://github.com/phpDocumentor/TypeResolver.git",
-                "reference": "7462d5f123dfc080dfdf26897032a6513644fc95"
+                "reference": "e878a14a65245fbe78f8080eba03b47c3b705651"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/7462d5f123dfc080dfdf26897032a6513644fc95",
-                "reference": "7462d5f123dfc080dfdf26897032a6513644fc95",
+                "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/e878a14a65245fbe78f8080eba03b47c3b705651",
+                "reference": "e878a14a65245fbe78f8080eba03b47c3b705651",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2",
+                "php": "^7.2 || ^8.0",
                 "phpdocumentor/reflection-common": "^2.0"
             },
             "require-dev": {
-                "ext-tokenizer": "^7.2",
-                "mockery/mockery": "~1"
+                "ext-tokenizer": "*"
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "1.x-dev"
+                    "dev-1.x": "1.x-dev"
                 }
             },
             "autoload": {
                 }
             ],
             "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
-            "time": "2020-02-18T18:59:58+00:00"
+            "time": "2020-06-27T10:12:23+00:00"
         },
         {
             "name": "phpspec/prophecy",
-            "version": "v1.10.3",
+            "version": "1.11.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/phpspec/prophecy.git",
-                "reference": "451c3cd1418cf640de218914901e51b064abb093"
+                "reference": "b20034be5efcdab4fb60ca3a29cba2949aead160"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/451c3cd1418cf640de218914901e51b064abb093",
-                "reference": "451c3cd1418cf640de218914901e51b064abb093",
+                "url": "https://api.github.com/repos/phpspec/prophecy/zipball/b20034be5efcdab4fb60ca3a29cba2949aead160",
+                "reference": "b20034be5efcdab4fb60ca3a29cba2949aead160",
                 "shasum": ""
             },
             "require": {
-                "doctrine/instantiator": "^1.0.2",
-                "php": "^5.3|^7.0",
-                "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0|^5.0",
-                "sebastian/comparator": "^1.2.3|^2.0|^3.0|^4.0",
-                "sebastian/recursion-context": "^1.0|^2.0|^3.0|^4.0"
+                "doctrine/instantiator": "^1.2",
+                "php": "^7.2",
+                "phpdocumentor/reflection-docblock": "^5.0",
+                "sebastian/comparator": "^3.0 || ^4.0",
+                "sebastian/recursion-context": "^3.0 || ^4.0"
             },
             "require-dev": {
-                "phpspec/phpspec": "^2.5 || ^3.2",
-                "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5 || ^7.1"
+                "phpspec/phpspec": "^6.0",
+                "phpunit/phpunit": "^8.0"
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "1.10.x-dev"
+                    "dev-master": "1.11.x-dev"
                 }
             },
             "autoload": {
                 "spy",
                 "stub"
             ],
-            "time": "2020-03-05T15:02:03+00:00"
+            "time": "2020-07-08T12:44:21+00:00"
         },
         {
             "name": "phpunit/dbunit",
             "keywords": [
                 "tokenizer"
             ],
+            "abandoned": true,
             "time": "2019-09-17T06:23:10+00:00"
         },
         {
         },
         {
             "name": "symfony/browser-kit",
-            "version": "v4.4.7",
+            "version": "v4.4.13",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/browser-kit.git",
-                "reference": "e4b0dc1b100bf75b5717c5b451397f230a618a42"
+                "reference": "f53310646af9901292488b2ff36e26ea10f545f5"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/browser-kit/zipball/e4b0dc1b100bf75b5717c5b451397f230a618a42",
-                "reference": "e4b0dc1b100bf75b5717c5b451397f230a618a42",
+                "url": "https://api.github.com/repos/symfony/browser-kit/zipball/f53310646af9901292488b2ff36e26ea10f545f5",
+                "reference": "f53310646af9901292488b2ff36e26ea10f545f5",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1.3",
+                "php": ">=7.1.3",
                 "symfony/dom-crawler": "^3.4|^4.0|^5.0"
             },
             "require-dev": {
                     "type": "tidelift"
                 }
             ],
-            "time": "2020-03-28T10:15:50+00:00"
+            "time": "2020-05-22T17:28:00+00:00"
         },
         {
             "name": "symfony/config",
-            "version": "v4.4.7",
+            "version": "v4.4.13",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/config.git",
-                "reference": "3f4a3de1af498ed0ea653d4dc2317794144e6ca4"
+                "reference": "043bf8652c307ebc23ce44047d215eec889d8850"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/config/zipball/3f4a3de1af498ed0ea653d4dc2317794144e6ca4",
-                "reference": "3f4a3de1af498ed0ea653d4dc2317794144e6ca4",
+                "url": "https://api.github.com/repos/symfony/config/zipball/043bf8652c307ebc23ce44047d215eec889d8850",
+                "reference": "043bf8652c307ebc23ce44047d215eec889d8850",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1.3",
+                "php": ">=7.1.3",
                 "symfony/filesystem": "^3.4|^4.0|^5.0",
                 "symfony/polyfill-ctype": "~1.8"
             },
             ],
             "description": "Symfony Config Component",
             "homepage": "https://symfony.com",
-            "time": "2020-03-27T16:54:36+00:00"
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-08-10T07:27:51+00:00"
         },
         {
             "name": "symfony/console",
-            "version": "v5.0.7",
+            "version": "v5.1.5",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/console.git",
-                "reference": "5fa1caadc8cdaa17bcfb25219f3b53fe294a9935"
+                "reference": "186f395b256065ba9b890c0a4e48a91d598fa2cf"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/console/zipball/5fa1caadc8cdaa17bcfb25219f3b53fe294a9935",
-                "reference": "5fa1caadc8cdaa17bcfb25219f3b53fe294a9935",
+                "url": "https://api.github.com/repos/symfony/console/zipball/186f395b256065ba9b890c0a4e48a91d598fa2cf",
+                "reference": "186f395b256065ba9b890c0a4e48a91d598fa2cf",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2.5",
+                "php": ">=7.2.5",
                 "symfony/polyfill-mbstring": "~1.0",
                 "symfony/polyfill-php73": "^1.8",
-                "symfony/service-contracts": "^1.1|^2"
+                "symfony/polyfill-php80": "^1.15",
+                "symfony/service-contracts": "^1.1|^2",
+                "symfony/string": "^5.1"
             },
             "conflict": {
                 "symfony/dependency-injection": "<4.4",
+                "symfony/dotenv": "<5.1",
                 "symfony/event-dispatcher": "<4.4",
                 "symfony/lock": "<4.4",
                 "symfony/process": "<4.4"
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "5.0-dev"
+                    "dev-master": "5.1-dev"
                 }
             },
             "autoload": {
             ],
             "description": "Symfony Console Component",
             "homepage": "https://symfony.com",
-            "time": "2020-03-30T11:42:42+00:00"
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-09-02T07:07:40+00:00"
         },
         {
             "name": "symfony/css-selector",
-            "version": "v5.0.7",
+            "version": "v5.1.5",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/css-selector.git",
-                "reference": "5f8d5271303dad260692ba73dfa21777d38e124e"
+                "reference": "e544e24472d4c97b2d11ade7caacd446727c6bf9"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/css-selector/zipball/5f8d5271303dad260692ba73dfa21777d38e124e",
-                "reference": "5f8d5271303dad260692ba73dfa21777d38e124e",
+                "url": "https://api.github.com/repos/symfony/css-selector/zipball/e544e24472d4c97b2d11ade7caacd446727c6bf9",
+                "reference": "e544e24472d4c97b2d11ade7caacd446727c6bf9",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2.5"
+                "php": ">=7.2.5"
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "5.0-dev"
+                    "dev-master": "5.1-dev"
                 }
             },
             "autoload": {
                     "type": "tidelift"
                 }
             ],
-            "time": "2020-03-27T16:56:45+00:00"
+            "time": "2020-05-20T17:43:50+00:00"
         },
         {
             "name": "symfony/dependency-injection",
-            "version": "v4.4.7",
+            "version": "v4.4.13",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/dependency-injection.git",
-                "reference": "755b18859be26b90f4bf63753432d3387458bf31"
+                "reference": "384c2601e5a6228d60b041911d63f010e0885ffb"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/755b18859be26b90f4bf63753432d3387458bf31",
-                "reference": "755b18859be26b90f4bf63753432d3387458bf31",
+                "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/384c2601e5a6228d60b041911d63f010e0885ffb",
+                "reference": "384c2601e5a6228d60b041911d63f010e0885ffb",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1.3",
+                "php": ">=7.1.3",
                 "psr/container": "^1.0",
                 "symfony/service-contracts": "^1.1.6|^2"
             },
             ],
             "description": "Symfony DependencyInjection Component",
             "homepage": "https://symfony.com",
-            "time": "2020-03-30T10:09:30+00:00"
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-09-01T17:42:15+00:00"
+        },
+        {
+            "name": "symfony/deprecation-contracts",
+            "version": "v2.1.3",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/deprecation-contracts.git",
+                "reference": "5e20b83385a77593259c9f8beb2c43cd03b2ac14"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5e20b83385a77593259c9f8beb2c43cd03b2ac14",
+                "reference": "5e20b83385a77593259c9f8beb2c43cd03b2ac14",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=7.1"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.1-dev"
+                },
+                "thanks": {
+                    "name": "symfony/contracts",
+                    "url": "https://github.com/symfony/contracts"
+                }
+            },
+            "autoload": {
+                "files": [
+                    "function.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Nicolas Grekas",
+                    "email": "p@tchwork.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "https://symfony.com/contributors"
+                }
+            ],
+            "description": "A generic function and convention to trigger deprecation notices",
+            "homepage": "https://symfony.com",
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-06-06T08:49:21+00:00"
         },
         {
             "name": "symfony/dom-crawler",
-            "version": "v4.4.7",
+            "version": "v4.4.13",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/dom-crawler.git",
-                "reference": "4d0fb3374324071ecdd94898367a3fa4b5563162"
+                "reference": "6dd1e7adef4b7efeeb9691fd619279027d4dcf85"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/4d0fb3374324071ecdd94898367a3fa4b5563162",
-                "reference": "4d0fb3374324071ecdd94898367a3fa4b5563162",
+                "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/6dd1e7adef4b7efeeb9691fd619279027d4dcf85",
+                "reference": "6dd1e7adef4b7efeeb9691fd619279027d4dcf85",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.1.3",
+                "php": ">=7.1.3",
                 "symfony/polyfill-ctype": "~1.8",
                 "symfony/polyfill-mbstring": "~1.0"
             },
                     "type": "tidelift"
                 }
             ],
-            "time": "2020-03-29T19:12:22+00:00"
+            "time": "2020-08-12T06:20:35+00:00"
         },
         {
             "name": "symfony/event-dispatcher",
-            "version": "v5.0.7",
+            "version": "v5.1.5",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/event-dispatcher.git",
-                "reference": "24f40d95385774ed5c71dbf014edd047e2f2f3dc"
+                "reference": "94871fc0a69c3c5da57764187724cdce0755899c"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/24f40d95385774ed5c71dbf014edd047e2f2f3dc",
-                "reference": "24f40d95385774ed5c71dbf014edd047e2f2f3dc",
+                "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/94871fc0a69c3c5da57764187724cdce0755899c",
+                "reference": "94871fc0a69c3c5da57764187724cdce0755899c",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2.5",
-                "symfony/event-dispatcher-contracts": "^2"
+                "php": ">=7.2.5",
+                "symfony/deprecation-contracts": "^2.1",
+                "symfony/event-dispatcher-contracts": "^2",
+                "symfony/polyfill-php80": "^1.15"
             },
             "conflict": {
                 "symfony/dependency-injection": "<4.4"
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "5.0-dev"
+                    "dev-master": "5.1-dev"
                 }
             },
             "autoload": {
                     "type": "tidelift"
                 }
             ],
-            "time": "2020-03-27T16:56:45+00:00"
+            "time": "2020-08-13T14:19:42+00:00"
         },
         {
             "name": "symfony/event-dispatcher-contracts",
-            "version": "v2.0.1",
+            "version": "v2.1.3",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/event-dispatcher-contracts.git",
-                "reference": "af23c2584d4577d54661c434446fb8fbed6025dd"
+                "reference": "f6f613d74cfc5a623fc36294d3451eb7fa5a042b"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/af23c2584d4577d54661c434446fb8fbed6025dd",
-                "reference": "af23c2584d4577d54661c434446fb8fbed6025dd",
+                "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/f6f613d74cfc5a623fc36294d3451eb7fa5a042b",
+                "reference": "f6f613d74cfc5a623fc36294d3451eb7fa5a042b",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2.5",
+                "php": ">=7.2.5",
                 "psr/event-dispatcher": "^1"
             },
             "suggest": {
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "2.0-dev"
+                    "dev-master": "2.1-dev"
+                },
+                "thanks": {
+                    "name": "symfony/contracts",
+                    "url": "https://github.com/symfony/contracts"
                 }
             },
             "autoload": {
                 "interoperability",
                 "standards"
             ],
-            "time": "2019-11-18T17:27:11+00:00"
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-07-06T13:23:11+00:00"
         },
         {
             "name": "symfony/filesystem",
-            "version": "v5.0.7",
+            "version": "v5.1.5",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/filesystem.git",
-                "reference": "ca3b87dd09fff9b771731637f5379965fbfab420"
+                "reference": "f7b9ed6142a34252d219801d9767dedbd711da1a"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/symfony/filesystem/zipball/ca3b87dd09fff9b771731637f5379965fbfab420",
-                "reference": "ca3b87dd09fff9b771731637f5379965fbfab420",
+                "url": "https://api.github.com/repos/symfony/filesystem/zipball/f7b9ed6142a34252d219801d9767dedbd711da1a",
+                "reference": "f7b9ed6142a34252d219801d9767dedbd711da1a",
                 "shasum": ""
             },
             "require": {
-                "php": "^7.2.5",
+                "php": ">=7.2.5",
                 "symfony/polyfill-ctype": "~1.8"
             },
             "type": "library",
             "extra": {
                 "branch-alias": {
-                    "dev-master": "5.0-dev"
+                    "dev-master": "5.1-dev"
                 }
             },
             "autoload": {
             ],
             "description": "Symfony Filesystem Component",
             "homepage": "https://symfony.com",
-            "time": "2020-03-27T16:56:45+00:00"
+            "funding": [
+                {
+                    "url": "https://symfony.com/sponsor",
+                    "type": "custom"
+                },
+                {
+                    "url": "https://github.com/fabpot",
+                    "type": "github"
+                },
+                {
+                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+                    "type": "tidelift"
+                }
+            ],
+            "time": "2020-08-21T17:19:47+00:00"
         },
         {
             "name": "symfony/polyfill-ctype",
-            "version": "v1.15.0",
+            "version": "v1.18.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/symfony/polyfill-ctype.git",
-                "reference": "4719fa9c18b0464d399f1a63bf624b42b6fa8d14"
+                "reference": "1c302646f6efc070cd46856e600e5e0684d6b454"
       &nb