Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/group/ -> import.php (source)

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

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Bulk group creation registration script from a comma separated file
  20   *
  21   * @copyright 1999 Martin Dougiamas  http://dougiamas.com
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   * @package core_group
  24   */
  25  
  26  require_once('../config.php');
  27  require_once($CFG->dirroot.'/course/lib.php');
  28  require_once($CFG->dirroot.'/group/lib.php');
  29  include_once ('import_form.php');
  30  
  31  $id = required_param('id', PARAM_INT);    // Course id
  32  
  33  $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
  34  
  35  $PAGE->set_url('/group/import.php', array('id'=>$id));
  36  
  37  require_login($course);
  38  $context = context_course::instance($id);
  39  
  40  require_capability('moodle/course:managegroups', $context);
  41  
  42  $strimportgroups = get_string('importgroups', 'core_group');
  43  
  44  $PAGE->navbar->add($strimportgroups);
  45  navigation_node::override_active_url(new moodle_url('/group/index.php', array('id' => $course->id)));
  46  $PAGE->set_title("$course->shortname: $strimportgroups");
  47  $PAGE->set_heading($course->fullname);
  48  $PAGE->set_pagelayout('admin');
  49  
  50  $returnurl = new moodle_url('/group/index.php', array('id'=>$id));
  51  
  52  $importform = new groups_import_form(null, ['id' => $id]);
  53  
  54  // If a file has been uploaded, then process it
  55  if ($importform->is_cancelled()) {
  56      redirect($returnurl);
  57  
  58  } else if ($formdata = $importform->get_data()) {
  59      echo $OUTPUT->header();
  60  
  61      $text = $importform->get_file_content('userfile');
  62      $text = preg_replace('!\r\n?!', "\n", $text);
  63  
  64      require_once($CFG->libdir . '/csvlib.class.php');
  65      $importid = csv_import_reader::get_new_iid('groupimport');
  66      $csvimport = new csv_import_reader($importid, 'groupimport');
  67      $delimiter = $formdata->delimiter_name;
  68      $encoding = $formdata->encoding;
  69      $readcount = $csvimport->load_csv_content($text, $encoding, $delimiter);
  70  
  71      if ($readcount === false) {
  72          print_error('csvfileerror', 'error', $PAGE->url, $csvimport->get_error());
  73      } else if ($readcount == 0) {
  74          print_error('csvemptyfile', 'error', $PAGE->url, $csvimport->get_error());
  75      } else if ($readcount == 1) {
  76          print_error('csvnodata', 'error', $PAGE->url);
  77      }
  78  
  79      $csvimport->init();
  80  
  81      unset($text);
  82  
  83      // make arrays of valid fields for error checking
  84      $required = array("groupname" => 1);
  85      $optionalDefaults = array("lang" => 1);
  86      $optional = array("coursename" => 1,
  87              "idnumber" => 1,
  88              "groupidnumber" => 1,
  89              "description" => 1,
  90              "enrolmentkey" => 1,
  91              "groupingname" => 1,
  92              "enablemessaging" => 1,
  93          );
  94  
  95      // --- get header (field names) ---
  96      // Using get_columns() ensures the Byte Order Mark is removed.
  97      $header = $csvimport->get_columns();
  98  
  99      // check for valid field names
 100      foreach ($header as $i => $h) {
 101          $h = trim($h); $header[$i] = $h; // remove whitespace
 102          if (!(isset($required[$h]) or isset($optionalDefaults[$h]) or isset($optional[$h]))) {
 103                  print_error('invalidfieldname', 'error', $PAGE->url, $h);
 104              }
 105          if (isset($required[$h])) {
 106              $required[$h] = 2;
 107          }
 108      }
 109      // check for required fields
 110      foreach ($required as $key => $value) {
 111          if ($value < 2) {
 112              print_error('fieldrequired', 'error', $PAGE->url, $key);
 113          }
 114      }
 115      $linenum = 2; // since header is line 1
 116  
 117      while ($line = $csvimport->next()) {
 118  
 119          $newgroup = new stdClass();//to make Martin happy
 120          foreach ($optionalDefaults as $key => $value) {
 121              $newgroup->$key = current_language(); //defaults to current language
 122          }
 123          foreach ($line as $key => $value) {
 124              $record[$header[$key]] = trim($value);
 125          }
 126          if (trim(implode($line)) !== '') {
 127              // add a new group to the database
 128  
 129              // add fields to object $user
 130              foreach ($record as $name => $value) {
 131                  // check for required values
 132                  if (isset($required[$name]) and !$value) {
 133                      print_error('missingfield', 'error', $PAGE->url, $name);
 134                  } else if ($name == "groupname") {
 135                      $newgroup->name = $value;
 136                  } else {
 137                  // normal entry
 138                      $newgroup->{$name} = $value;
 139                  }
 140              }
 141  
 142              if (isset($newgroup->idnumber) && strlen($newgroup->idnumber)) {
 143                  //if idnumber is set, we use that.
 144                  //unset invalid courseid
 145                  if (!$mycourse = $DB->get_record('course', array('idnumber'=>$newgroup->idnumber))) {
 146                      echo $OUTPUT->notification(get_string('unknowncourseidnumber', 'error', $newgroup->idnumber));
 147                      unset($newgroup->courseid);//unset so 0 doesn't get written to database
 148                  } else {
 149                      $newgroup->courseid = $mycourse->id;
 150                  }
 151  
 152              } else if (isset($newgroup->coursename) && strlen($newgroup->coursename)) {
 153                  //else use course short name to look up
 154                  //unset invalid coursename (if no id)
 155                  if (!$mycourse = $DB->get_record('course', array('shortname' => $newgroup->coursename))) {
 156                      echo $OUTPUT->notification(get_string('unknowncourse', 'error', $newgroup->coursename));
 157                      unset($newgroup->courseid);//unset so 0 doesn't get written to database
 158                  } else {
 159                      $newgroup->courseid = $mycourse->id;
 160                  }
 161  
 162              } else {
 163                  //else use use current id
 164                  $newgroup->courseid = $id;
 165              }
 166              unset($newgroup->idnumber);
 167              unset($newgroup->coursename);
 168  
 169              //if courseid is set
 170              if (isset($newgroup->courseid)) {
 171                  $linenum++;
 172                  $groupname = $newgroup->name;
 173                  $newgrpcoursecontext = context_course::instance($newgroup->courseid);
 174  
 175                  ///Users cannot upload groups in courses they cannot update.
 176                  if (!has_capability('moodle/course:managegroups', $newgrpcoursecontext) or (!is_enrolled($newgrpcoursecontext) and !has_capability('moodle/course:view', $newgrpcoursecontext))) {
 177                      echo $OUTPUT->notification(get_string('nopermissionforcreation', 'group', $groupname));
 178  
 179                  } else {
 180                      if (isset($newgroup->groupidnumber)) {
 181                          // The CSV field for the group idnumber is groupidnumber rather than
 182                          // idnumber as that field is already in use for the course idnumber.
 183                          $newgroup->groupidnumber = trim($newgroup->groupidnumber);
 184                          if (has_capability('moodle/course:changeidnumber', $newgrpcoursecontext)) {
 185                              $newgroup->idnumber = $newgroup->groupidnumber;
 186                              if ($existing = groups_get_group_by_idnumber($newgroup->courseid, $newgroup->idnumber)) {
 187                                  // idnumbers must be unique to a course but we shouldn't ignore group creation for duplicates
 188                                  $existing->name = s($existing->name);
 189                                  $existing->idnumber = s($existing->idnumber);
 190                                  $existing->problemgroup = $groupname;
 191                                  echo $OUTPUT->notification(get_string('groupexistforcoursewithidnumber', 'error', $existing));
 192                                  unset($newgroup->idnumber);
 193                              }
 194                          }
 195                          // Always drop the groupidnumber key. It's not a valid database field
 196                          unset($newgroup->groupidnumber);
 197                      }
 198                      if ($groupid = groups_get_group_by_name($newgroup->courseid, $groupname)) {
 199                          echo $OUTPUT->notification("$groupname :".get_string('groupexistforcourse', 'error', $groupname));
 200                      } else if ($groupid = groups_create_group($newgroup)) {
 201                          echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname), 'notifysuccess');
 202                      } else {
 203                          echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname));
 204                          continue;
 205                      }
 206  
 207                      // Add group to grouping
 208                      if (isset($newgroup->groupingname) && strlen($newgroup->groupingname)) {
 209                          $groupingname = $newgroup->groupingname;
 210                          if (! $groupingid = groups_get_grouping_by_name($newgroup->courseid, $groupingname)) {
 211                              $data = new stdClass();
 212                              $data->courseid = $newgroup->courseid;
 213                              $data->name = $groupingname;
 214                              if ($groupingid = groups_create_grouping($data)) {
 215                                  echo $OUTPUT->notification(get_string('groupingaddedsuccesfully', 'group', $groupingname), 'notifysuccess');
 216                              } else {
 217                                  echo $OUTPUT->notification(get_string('groupingnotaddederror', 'error', $groupingname));
 218                                  continue;
 219                              }
 220                          }
 221  
 222                          // if we have reached here we definitely have a groupingid
 223                          $a = array('groupname' => $groupname, 'groupingname' => $groupingname);
 224                          try {
 225                              groups_assign_grouping($groupingid, $groupid);
 226                              echo $OUTPUT->notification(get_string('groupaddedtogroupingsuccesfully', 'group', $a), 'notifysuccess');
 227                          } catch (Exception $e) {
 228                              echo $OUTPUT->notification(get_string('groupnotaddedtogroupingerror', 'error', $a));
 229                          }
 230  
 231                      }
 232                  }
 233              }
 234              unset ($newgroup);
 235          }
 236      }
 237  
 238      $csvimport->close();
 239      echo $OUTPUT->single_button($returnurl, get_string('continue'), 'get');
 240      echo $OUTPUT->footer();
 241      die;
 242  }
 243  
 244  /// Print the form
 245  echo $OUTPUT->header();
 246  echo $OUTPUT->heading_with_help($strimportgroups, 'importgroups', 'core_group');
 247  $importform->display();
 248  echo $OUTPUT->footer();