MDL-26401 group: change import to use csv_import_reader class
[moodle.git] / group / import.php
1 <?php
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/>.
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  */
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');
31 $id = required_param('id', PARAM_INT);    // Course id
33 $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
35 $PAGE->set_url('/group/import.php', array('id'=>$id));
37 require_login($course);
38 $context = context_course::instance($id);
40 require_capability('moodle/course:managegroups', $context);
42 $strimportgroups = get_string('importgroups', 'core_group');
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');
50 $returnurl = new moodle_url('/group/index.php', array('id'=>$id));
52 $importform = new groups_import_form(null, ['id' => $id]);
54 // If a file has been uploaded, then process it
55 if ($importform->is_cancelled()) {
56     redirect($returnurl);
58 } else if ($formdata = $importform->get_data()) {
59     echo $OUTPUT->header();
61     $text = $importform->get_file_content('userfile');
62     $text = preg_replace('!\r\n?!', "\n", $text);
64     $rawlines = explode("\n", $text);
66     require_once($CFG->libdir . '/csvlib.class.php');
67     $importid = csv_import_reader::get_new_iid('groupimport');
68     $csvimport = new csv_import_reader($importid, 'groupimport');
69     $delimiter = $formdata->delimiter_name;
70     $encoding = $formdata->encoding;
71     $readcount = $csvimport->load_csv_content($text, $encoding, $delimiter);
73     if ($readcount === false) {
74         print_error('csvfileerror', 'error', $PAGE->url, $csvimport->get_error());
75     } else if ($readcount == 0) {
76         print_error('csvemptyfile', 'error', $PAGE->url, $csvimport->get_error());
77     } else if ($readcount == 1) {
78         print_error('csvnodata', 'error', $PAGE->url);
79     }
81     $csvimport->init();
83     unset($text);
85     // make arrays of valid fields for error checking
86     $required = array("groupname" => 1);
87     $optionalDefaults = array("lang" => 1);
88     $optional = array("coursename" => 1,
89             "idnumber" => 1,
90             "groupidnumber" => 1,
91             "description" => 1,
92             "enrolmentkey" => 1,
93             "groupingname" => 1,
94             "enablemessaging" => 1,
95         );
97     // --- get header (field names) ---
98     $header = explode($csvimport::get_delimiter($delimiter), array_shift($rawlines));
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
117     while ($line = $csvimport->next()) {
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
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             }
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                 }
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                 }
162             } else {
163                 //else use use current id
164                 $newgroup->courseid = $id;
165             }
166             unset($newgroup->idnumber);
167             unset($newgroup->coursename);
169             //if courseid is set
170             if (isset($newgroup->courseid)) {
171                 $linenum++;
172                 $groupname = $newgroup->name;
173                 $newgrpcoursecontext = context_course::instance($newgroup->courseid);
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));
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                     }
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                         }
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                         }
231                     }
232                 }
233             }
234             unset ($newgroup);
235         }
236     }
238     $csvimport->close();
239     echo $OUTPUT->single_button($returnurl, get_string('continue'), 'get');
240     echo $OUTPUT->footer();
241     die;
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();