Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Bulk user upload forms
  19   *
  20   * @package    tool
  21   * @subpackage uploaduser
  22   * @copyright  2007 Dan Poltawski
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  require_once $CFG->libdir.'/formslib.php';
  29  require_once($CFG->dirroot . '/user/editlib.php');
  30  
  31  /**
  32   * Upload a file CVS file with user information.
  33   *
  34   * @copyright  2007 Petr Skoda  {@link http://skodak.org}
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class admin_uploaduser_form1 extends moodleform {
  38      function definition () {
  39          $mform = $this->_form;
  40  
  41          $mform->addElement('header', 'settingsheader', get_string('upload'));
  42  
  43          $url = new moodle_url('example.csv');
  44          $link = html_writer::link($url, 'example.csv');
  45          $mform->addElement('static', 'examplecsv', get_string('examplecsv', 'tool_uploaduser'), $link);
  46          $mform->addHelpButton('examplecsv', 'examplecsv', 'tool_uploaduser');
  47  
  48          $mform->addElement('filepicker', 'userfile', get_string('file'));
  49          $mform->addRule('userfile', null, 'required');
  50  
  51          $choices = csv_import_reader::get_delimiter_list();
  52          $mform->addElement('select', 'delimiter_name', get_string('csvdelimiter', 'tool_uploaduser'), $choices);
  53          if (array_key_exists('cfg', $choices)) {
  54              $mform->setDefault('delimiter_name', 'cfg');
  55          } else if (get_string('listsep', 'langconfig') == ';') {
  56              $mform->setDefault('delimiter_name', 'semicolon');
  57          } else {
  58              $mform->setDefault('delimiter_name', 'comma');
  59          }
  60  
  61          $choices = core_text::get_encodings();
  62          $mform->addElement('select', 'encoding', get_string('encoding', 'tool_uploaduser'), $choices);
  63          $mform->setDefault('encoding', 'UTF-8');
  64  
  65          $choices = array('10'=>10, '20'=>20, '100'=>100, '1000'=>1000, '100000'=>100000);
  66          $mform->addElement('select', 'previewrows', get_string('rowpreviewnum', 'tool_uploaduser'), $choices);
  67          $mform->setType('previewrows', PARAM_INT);
  68  
  69          $this->add_action_buttons(false, get_string('uploadusers', 'tool_uploaduser'));
  70      }
  71  
  72      /**
  73       * Returns list of elements and their default values, to be used in CLI
  74       *
  75       * @return array
  76       */
  77      public function get_form_for_cli() {
  78          $elements = array_filter($this->_form->_elements, function($element) {
  79              return !in_array($element->getName(), ['buttonar', 'userfile', 'previewrows']);
  80          });
  81          return [$elements, $this->_form->_defaultValues];
  82      }
  83  }
  84  
  85  
  86  /**
  87   * Specify user upload details
  88   *
  89   * @copyright  2007 Petr Skoda  {@link http://skodak.org}
  90   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  91   */
  92  class admin_uploaduser_form2 extends moodleform {
  93      function definition () {
  94          global $CFG, $USER;
  95  
  96          $mform   = $this->_form;
  97          $columns = $this->_customdata['columns'];
  98          $data    = $this->_customdata['data'];
  99  
 100          // I am the template user, why should it be the administrator? we have roles now, other ppl may use this script ;-)
 101          $templateuser = $USER;
 102  
 103          // upload settings and file
 104          $mform->addElement('header', 'settingsheader', get_string('settings'));
 105  
 106          $choices = array(UU_USER_ADDNEW     => get_string('uuoptype_addnew', 'tool_uploaduser'),
 107                           UU_USER_ADDINC     => get_string('uuoptype_addinc', 'tool_uploaduser'),
 108                           UU_USER_ADD_UPDATE => get_string('uuoptype_addupdate', 'tool_uploaduser'),
 109                           UU_USER_UPDATE     => get_string('uuoptype_update', 'tool_uploaduser'));
 110          $mform->addElement('select', 'uutype', get_string('uuoptype', 'tool_uploaduser'), $choices);
 111  
 112          $choices = array(0 => get_string('infilefield', 'auth'), 1 => get_string('createpasswordifneeded', 'auth'));
 113          $mform->addElement('select', 'uupasswordnew', get_string('uupasswordnew', 'tool_uploaduser'), $choices);
 114          $mform->setDefault('uupasswordnew', 1);
 115          $mform->hideIf('uupasswordnew', 'uutype', 'eq', UU_USER_UPDATE);
 116  
 117          $choices = array(UU_UPDATE_NOCHANGES    => get_string('nochanges', 'tool_uploaduser'),
 118                           UU_UPDATE_FILEOVERRIDE => get_string('uuupdatefromfile', 'tool_uploaduser'),
 119                           UU_UPDATE_ALLOVERRIDE  => get_string('uuupdateall', 'tool_uploaduser'),
 120                           UU_UPDATE_MISSING      => get_string('uuupdatemissing', 'tool_uploaduser'));
 121          $mform->addElement('select', 'uuupdatetype', get_string('uuupdatetype', 'tool_uploaduser'), $choices);
 122          $mform->setDefault('uuupdatetype', UU_UPDATE_NOCHANGES);
 123          $mform->hideIf('uuupdatetype', 'uutype', 'eq', UU_USER_ADDNEW);
 124          $mform->hideIf('uuupdatetype', 'uutype', 'eq', UU_USER_ADDINC);
 125  
 126          $choices = array(0 => get_string('nochanges', 'tool_uploaduser'), 1 => get_string('update'));
 127          $mform->addElement('select', 'uupasswordold', get_string('uupasswordold', 'tool_uploaduser'), $choices);
 128          $mform->setDefault('uupasswordold', 0);
 129          $mform->hideIf('uupasswordold', 'uutype', 'eq', UU_USER_ADDNEW);
 130          $mform->hideIf('uupasswordold', 'uutype', 'eq', UU_USER_ADDINC);
 131          $mform->hideIf('uupasswordold', 'uuupdatetype', 'eq', 0);
 132          $mform->hideIf('uupasswordold', 'uuupdatetype', 'eq', 3);
 133  
 134          $choices = array(UU_PWRESET_WEAK => get_string('usersweakpassword', 'tool_uploaduser'),
 135                           UU_PWRESET_NONE => get_string('none'),
 136                           UU_PWRESET_ALL  => get_string('all'));
 137          if (empty($CFG->passwordpolicy)) {
 138              unset($choices[UU_PWRESET_WEAK]);
 139          }
 140          $mform->addElement('select', 'uuforcepasswordchange', get_string('forcepasswordchange', 'core'), $choices);
 141  
 142  
 143          $mform->addElement('selectyesno', 'uuallowrenames', get_string('allowrenames', 'tool_uploaduser'));
 144          $mform->setDefault('uuallowrenames', 0);
 145          $mform->hideIf('uuallowrenames', 'uutype', 'eq', UU_USER_ADDNEW);
 146          $mform->hideIf('uuallowrenames', 'uutype', 'eq', UU_USER_ADDINC);
 147  
 148          $mform->addElement('selectyesno', 'uuallowdeletes', get_string('allowdeletes', 'tool_uploaduser'));
 149          $mform->setDefault('uuallowdeletes', 0);
 150          // Ensure user is able to perform user deletion.
 151          if (!has_capability('moodle/user:delete', context_system::instance())) {
 152              $mform->hardFreeze('uuallowdeletes');
 153              $mform->setConstant('uuallowdeletes', 0);
 154          }
 155          $mform->hideIf('uuallowdeletes', 'uutype', 'eq', UU_USER_ADDNEW);
 156          $mform->hideIf('uuallowdeletes', 'uutype', 'eq', UU_USER_ADDINC);
 157  
 158          $mform->addElement('selectyesno', 'uuallowsuspends', get_string('allowsuspends', 'tool_uploaduser'));
 159          $mform->setDefault('uuallowsuspends', 1);
 160          $mform->hideIf('uuallowsuspends', 'uutype', 'eq', UU_USER_ADDNEW);
 161          $mform->hideIf('uuallowsuspends', 'uutype', 'eq', UU_USER_ADDINC);
 162  
 163          if (!empty($CFG->allowaccountssameemail)) {
 164              $mform->addElement('selectyesno', 'uunoemailduplicates', get_string('uunoemailduplicates', 'tool_uploaduser'));
 165              $mform->setDefault('uunoemailduplicates', 1);
 166          } else {
 167              $mform->addElement('hidden', 'uunoemailduplicates', 1);
 168          }
 169          $mform->setType('uunoemailduplicates', PARAM_BOOL);
 170  
 171          $mform->addElement('selectyesno', 'uustandardusernames', get_string('uustandardusernames', 'tool_uploaduser'));
 172          $mform->setDefault('uustandardusernames', 1);
 173  
 174          $choices = array(UU_BULK_NONE    => get_string('no'),
 175                           UU_BULK_NEW     => get_string('uubulknew', 'tool_uploaduser'),
 176                           UU_BULK_UPDATED => get_string('uubulkupdated', 'tool_uploaduser'),
 177                           UU_BULK_ALL     => get_string('uubulkall', 'tool_uploaduser'));
 178          $mform->addElement('select', 'uubulk', get_string('uubulk', 'tool_uploaduser'), $choices);
 179          $mform->setDefault('uubulk', 0);
 180  
 181          // roles selection
 182          $showroles = false;
 183          foreach ($columns as $column) {
 184              if (preg_match('/^type\d+$/', $column)) {
 185                  $showroles = true;
 186                  break;
 187              }
 188          }
 189          if ($showroles) {
 190              $mform->addElement('header', 'rolesheader', get_string('roles'));
 191  
 192              $choices = uu_allowed_roles(true);
 193  
 194              $mform->addElement('select', 'uulegacy1', get_string('uulegacy1role', 'tool_uploaduser'), $choices);
 195              if ($studentroles = get_archetype_roles('student')) {
 196                  foreach ($studentroles as $role) {
 197                      if (isset($choices[$role->id])) {
 198                          $mform->setDefault('uulegacy1', $role->id);
 199                          break;
 200                      }
 201                  }
 202                  unset($studentroles);
 203              }
 204  
 205              $mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'tool_uploaduser'), $choices);
 206              if ($editteacherroles = get_archetype_roles('editingteacher')) {
 207                  foreach ($editteacherroles as $role) {
 208                      if (isset($choices[$role->id])) {
 209                          $mform->setDefault('uulegacy2', $role->id);
 210                          break;
 211                      }
 212                  }
 213                  unset($editteacherroles);
 214              }
 215  
 216              $mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'tool_uploaduser'), $choices);
 217              if ($teacherroles = get_archetype_roles('teacher')) {
 218                  foreach ($teacherroles as $role) {
 219                      if (isset($choices[$role->id])) {
 220                          $mform->setDefault('uulegacy3', $role->id);
 221                          break;
 222                      }
 223                  }
 224                  unset($teacherroles);
 225              }
 226          }
 227  
 228          // default values
 229          $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'tool_uploaduser'));
 230  
 231          $mform->addElement('text', 'username', get_string('uuusernametemplate', 'tool_uploaduser'), 'size="20"');
 232          $mform->setType('username', PARAM_RAW); // No cleaning here. The process verifies it later.
 233          $mform->addRule('username', get_string('requiredtemplate', 'tool_uploaduser'), 'required', null, 'client');
 234          $mform->hideIf('username', 'uutype', 'eq', UU_USER_ADD_UPDATE);
 235          $mform->hideIf('username', 'uutype', 'eq', UU_USER_UPDATE);
 236          $mform->setForceLtr('username');
 237  
 238          $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
 239          $mform->setType('email', PARAM_RAW); // No cleaning here. The process verifies it later.
 240          $mform->hideIf('email', 'uutype', 'eq', UU_USER_ADD_UPDATE);
 241          $mform->hideIf('email', 'uutype', 'eq', UU_USER_UPDATE);
 242          $mform->setForceLtr('email');
 243  
 244          // only enabled and known to work plugins
 245          $choices = uu_supported_auths();
 246          $mform->addElement('select', 'auth', get_string('chooseauthmethod','auth'), $choices);
 247          $mform->setDefault('auth', 'manual'); // manual is a sensible backwards compatible default
 248          $mform->addHelpButton('auth', 'chooseauthmethod', 'auth');
 249          $mform->setAdvanced('auth');
 250  
 251          $choices = array(0 => get_string('emaildisplayno'), 1 => get_string('emaildisplayyes'), 2 => get_string('emaildisplaycourse'));
 252          $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
 253          $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
 254          $mform->addHelpButton('maildisplay', 'emaildisplay');
 255  
 256          $choices = array(0 => get_string('emailenable'), 1 => get_string('emaildisable'));
 257          $mform->addElement('select', 'emailstop', get_string('emailstop'), $choices);
 258          $mform->setDefault('emailstop', core_user::get_property_default('emailstop'));
 259          $mform->setAdvanced('emailstop');
 260  
 261          $choices = array(0 => get_string('textformat'), 1 => get_string('htmlformat'));
 262          $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
 263          $mform->setDefault('mailformat', core_user::get_property_default('mailformat'));
 264          $mform->setAdvanced('mailformat');
 265  
 266          $choices = array(0 => get_string('emaildigestoff'), 1 => get_string('emaildigestcomplete'), 2 => get_string('emaildigestsubjects'));
 267          $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
 268          $mform->setDefault('maildigest', core_user::get_property_default('maildigest'));
 269          $mform->setAdvanced('maildigest');
 270  
 271          $choices = array(1 => get_string('autosubscribeyes'), 0 => get_string('autosubscribeno'));
 272          $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
 273          $mform->setDefault('autosubscribe', core_user::get_property_default('autosubscribe'));
 274  
 275          $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="25"');
 276          $mform->setType('city', PARAM_TEXT);
 277          if (empty($CFG->defaultcity)) {
 278              $mform->setDefault('city', $templateuser->city);
 279          } else {
 280              $mform->setDefault('city', core_user::get_property_default('city'));
 281          }
 282  
 283          $choices = get_string_manager()->get_list_of_countries();
 284          $choices = array(''=>get_string('selectacountry').'...') + $choices;
 285          $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
 286          if (empty($CFG->country)) {
 287              $mform->setDefault('country', $templateuser->country);
 288          } else {
 289              $mform->setDefault('country', core_user::get_property_default('country'));
 290          }
 291          $mform->setAdvanced('country');
 292  
 293          $choices = core_date::get_list_of_timezones($templateuser->timezone, true);
 294          $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
 295          $mform->setDefault('timezone', $templateuser->timezone);
 296          $mform->setAdvanced('timezone');
 297  
 298          $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
 299          $mform->setDefault('lang', $templateuser->lang);
 300          $mform->setAdvanced('lang');
 301  
 302          $editoroptions = array('maxfiles'=>0, 'maxbytes'=>0, 'trusttext'=>false, 'forcehttps'=>false);
 303          $mform->addElement('editor', 'description', get_string('userdescription'), null, $editoroptions);
 304          $mform->setType('description', PARAM_CLEANHTML);
 305          $mform->addHelpButton('description', 'userdescription');
 306          $mform->setAdvanced('description');
 307  
 308          $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
 309          $mform->setType('idnumber', core_user::get_property_type('idnumber'));
 310          $mform->setForceLtr('idnumber');
 311  
 312          $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
 313          $mform->setType('institution', PARAM_TEXT);
 314          $mform->setDefault('institution', $templateuser->institution);
 315  
 316          $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
 317          $mform->setType('department', PARAM_TEXT);
 318          $mform->setDefault('department', $templateuser->department);
 319  
 320          $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
 321          $mform->setType('phone1', PARAM_NOTAGS);
 322          $mform->setAdvanced('phone1');
 323          $mform->setForceLtr('phone1');
 324  
 325          $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
 326          $mform->setType('phone2', PARAM_NOTAGS);
 327          $mform->setAdvanced('phone2');
 328          $mform->setForceLtr('phone2');
 329  
 330          $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
 331          $mform->setType('address', PARAM_TEXT);
 332          $mform->setAdvanced('address');
 333  
 334          // Next the profile defaults
 335          profile_definition($mform);
 336  
 337          // hidden fields
 338          $mform->addElement('hidden', 'iid');
 339          $mform->setType('iid', PARAM_INT);
 340  
 341          $mform->addElement('hidden', 'previewrows');
 342          $mform->setType('previewrows', PARAM_INT);
 343  
 344          $this->add_action_buttons(true, get_string('uploadusers', 'tool_uploaduser'));
 345  
 346          $this->set_data($data);
 347      }
 348  
 349      /**
 350       * Form tweaks that depend on current data.
 351       */
 352      function definition_after_data() {
 353          $mform   = $this->_form;
 354          $columns = $this->_customdata['columns'];
 355  
 356          foreach ($columns as $column) {
 357              if ($mform->elementExists($column)) {
 358                  $mform->removeElement($column);
 359              }
 360          }
 361  
 362          if (!in_array('password', $columns)) {
 363              // password resetting makes sense only if password specified in csv file
 364              if ($mform->elementExists('uuforcepasswordchange')) {
 365                  $mform->removeElement('uuforcepasswordchange');
 366              }
 367          }
 368      }
 369  
 370      /**
 371       * Server side validation.
 372       */
 373      function validation($data, $files) {
 374          $errors = parent::validation($data, $files);
 375          $columns = $this->_customdata['columns'];
 376          $optype  = $data['uutype'];
 377          $updatetype = $data['uuupdatetype'];
 378  
 379          // detect if password column needed in file
 380          if (!in_array('password', $columns)) {
 381              switch ($optype) {
 382                  case UU_USER_UPDATE:
 383                      if (!empty($data['uupasswordold'])) {
 384                          $errors['uupasswordold'] = get_string('missingfield', 'error', 'password');
 385                      }
 386                      break;
 387  
 388                  case UU_USER_ADD_UPDATE:
 389                      if (empty($data['uupasswordnew'])) {
 390                          $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
 391                      }
 392                      if  (!empty($data['uupasswordold'])) {
 393                          $errors['uupasswordold'] = get_string('missingfield', 'error', 'password');
 394                      }
 395                      break;
 396  
 397                  case UU_USER_ADDNEW:
 398                      if (empty($data['uupasswordnew'])) {
 399                          $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
 400                      }
 401                      break;
 402                  case UU_USER_ADDINC:
 403                      if (empty($data['uupasswordnew'])) {
 404                          $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
 405                      }
 406                      break;
 407               }
 408          }
 409  
 410          // If the 'Existing user details' value is set we need to ensure that the
 411          // 'Upload type' is not set to something invalid.
 412          if (!empty($updatetype) && ($optype == UU_USER_ADDNEW || $optype == UU_USER_ADDINC)) {
 413              $errors['uuupdatetype'] = get_string('invalidupdatetype', 'tool_uploaduser');
 414          }
 415  
 416          // look for other required data
 417          if ($optype != UU_USER_UPDATE) {
 418              $requiredusernames = useredit_get_required_name_fields();
 419              $missing = array();
 420              foreach ($requiredusernames as $requiredusername) {
 421                  if (!in_array($requiredusername, $columns)) {
 422                      $missing[] = get_string('missingfield', 'error', $requiredusername);;
 423                  }
 424              }
 425              if ($missing) {
 426                  $errors['uutype'] = implode('<br />',  $missing);
 427              }
 428              if (!in_array('email', $columns) and empty($data['email'])) {
 429                  $errors['email'] = get_string('requiredtemplate', 'tool_uploaduser');
 430              }
 431          }
 432          return $errors;
 433      }
 434  
 435      /**
 436       * Used to reformat the data from the editor component
 437       *
 438       * @return stdClass
 439       */
 440      function get_data() {
 441          $data = parent::get_data();
 442  
 443          if ($data !== null and isset($data->description)) {
 444              $data->descriptionformat = $data->description['format'];
 445              $data->description = $data->description['text'];
 446          }
 447  
 448          return $data;
 449      }
 450  
 451      /**
 452       * Returns list of elements and their default values, to be used in CLI
 453       *
 454       * @return array
 455       */
 456      public function get_form_for_cli() {
 457          $elements = array_filter($this->_form->_elements, function($element) {
 458              return !in_array($element->getName(), ['buttonar', 'uubulk']);
 459          });
 460          return [$elements, $this->_form->_defaultValues];
 461      }
 462  
 463      /**
 464       * Returns validation errors (used in CLI)
 465       *
 466       * @return array
 467       */
 468      public function get_validation_errors(): array {
 469          return $this->_form->_errors;
 470      }
 471  }