MDL-69401 book: Limit character length in chapter title
[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 $mform_post = new groups_import_form(null, array('id'=>$id));
54 // If a file has been uploaded, then process it
55 if ($mform_post->is_cancelled()) {
56     redirect($returnurl);
58 } else if ($mform_post->get_data()) {
59     echo $OUTPUT->header();
61     $csv_encode = '/\&\#44/';
62     if (isset($CFG->CSV_DELIMITER)) {
63         $csv_delimiter = $CFG->CSV_DELIMITER;
65         if (isset($CFG->CSV_ENCODE)) {
66             $csv_encode = '/\&\#' . $CFG->CSV_ENCODE . '/';
67         }
68     } else {
69         $csv_delimiter = ",";
70     }
72     $text = $mform_post->get_file_content('userfile');
73     $text = preg_replace('!\r\n?!',"\n",$text);
75     $rawlines = explode("\n", $text);
76     unset($text);
78     // make arrays of valid fields for error checking
79     $required = array("groupname" => 1);
80     $optionalDefaults = array("lang" => 1);
81     $optional = array("coursename" => 1,
82             "idnumber" => 1,
83             "groupidnumber" => 1,
84             "description" => 1,
85             "enrolmentkey" => 1,
86             "groupingname" => 1,
87             "enablemessaging" => 1,
88         );
90     // --- get header (field names) ---
91     $header = explode($csv_delimiter, array_shift($rawlines));
92     // check for valid field names
93     foreach ($header as $i => $h) {
94         $h = trim($h); $header[$i] = $h; // remove whitespace
95         if (!(isset($required[$h]) or isset($optionalDefaults[$h]) or isset($optional[$h]))) {
96                 print_error('invalidfieldname', 'error', 'import.php?id='.$id, $h);
97             }
98         if (isset($required[$h])) {
99             $required[$h] = 2;
100         }
101     }
102     // check for required fields
103     foreach ($required as $key => $value) {
104         if ($value < 2) {
105             print_error('fieldrequired', 'error', 'import.php?id='.$id, $key);
106         }
107     }
108     $linenum = 2; // since header is line 1
110     foreach ($rawlines as $rawline) {
112         $newgroup = new stdClass();//to make Martin happy
113         foreach ($optionalDefaults as $key => $value) {
114             $newgroup->$key = current_language(); //defaults to current language
115         }
116         //Note: commas within a field should be encoded as &#44 (for comma separated csv files)
117         //Note: semicolon within a field should be encoded as &#59 (for semicolon separated csv files)
118         $line = explode($csv_delimiter, $rawline);
119         foreach ($line as $key => $value) {
120             //decode encoded commas
121             $record[$header[$key]] = preg_replace($csv_encode, $csv_delimiter, trim($value));
122         }
123         if (trim($rawline) !== '') {
124             // add a new group to the database
126             // add fields to object $user
127             foreach ($record as $name => $value) {
128                 // check for required values
129                 if (isset($required[$name]) and !$value) {
130                     print_error('missingfield', 'error', 'import.php?id='.$id, $name);
131                 } else if ($name == "groupname") {
132                     $newgroup->name = $value;
133                 } else {
134                 // normal entry
135                     $newgroup->{$name} = $value;
136                 }
137             }
139             if (isset($newgroup->idnumber) && strlen($newgroup->idnumber)) {
140                 //if idnumber is set, we use that.
141                 //unset invalid courseid
142                 if (!$mycourse = $DB->get_record('course', array('idnumber'=>$newgroup->idnumber))) {
143                     echo $OUTPUT->notification(get_string('unknowncourseidnumber', 'error', $newgroup->idnumber));
144                     unset($newgroup->courseid);//unset so 0 doesn't get written to database
145                 } else {
146                     $newgroup->courseid = $mycourse->id;
147                 }
149             } else if (isset($newgroup->coursename) && strlen($newgroup->coursename)) {
150                 //else use course short name to look up
151                 //unset invalid coursename (if no id)
152                 if (!$mycourse = $DB->get_record('course', array('shortname' => $newgroup->coursename))) {
153                     echo $OUTPUT->notification(get_string('unknowncourse', 'error', $newgroup->coursename));
154                     unset($newgroup->courseid);//unset so 0 doesn't get written to database
155                 } else {
156                     $newgroup->courseid = $mycourse->id;
157                 }
159             } else {
160                 //else use use current id
161                 $newgroup->courseid = $id;
162             }
163             unset($newgroup->idnumber);
164             unset($newgroup->coursename);
166             //if courseid is set
167             if (isset($newgroup->courseid)) {
168                 $linenum++;
169                 $groupname = $newgroup->name;
170                 $newgrpcoursecontext = context_course::instance($newgroup->courseid);
172                 ///Users cannot upload groups in courses they cannot update.
173                 if (!has_capability('moodle/course:managegroups', $newgrpcoursecontext) or (!is_enrolled($newgrpcoursecontext) and !has_capability('moodle/course:view', $newgrpcoursecontext))) {
174                     echo $OUTPUT->notification(get_string('nopermissionforcreation', 'group', $groupname));
176                 } else {
177                     if (isset($newgroup->groupidnumber)) {
178                         // The CSV field for the group idnumber is groupidnumber rather than
179                         // idnumber as that field is already in use for the course idnumber.
180                         $newgroup->groupidnumber = trim($newgroup->groupidnumber);
181                         if (has_capability('moodle/course:changeidnumber', $newgrpcoursecontext)) {
182                             $newgroup->idnumber = $newgroup->groupidnumber;
183                             if ($existing = groups_get_group_by_idnumber($newgroup->courseid, $newgroup->idnumber)) {
184                                 // idnumbers must be unique to a course but we shouldn't ignore group creation for duplicates
185                                 $existing->name = s($existing->name);
186                                 $existing->idnumber = s($existing->idnumber);
187                                 $existing->problemgroup = $groupname;
188                                 echo $OUTPUT->notification(get_string('groupexistforcoursewithidnumber', 'error', $existing));
189                                 unset($newgroup->idnumber);
190                             }
191                         }
192                         // Always drop the groupidnumber key. It's not a valid database field
193                         unset($newgroup->groupidnumber);
194                     }
195                     if ($groupid = groups_get_group_by_name($newgroup->courseid, $groupname)) {
196                         echo $OUTPUT->notification("$groupname :".get_string('groupexistforcourse', 'error', $groupname));
197                     } else if ($groupid = groups_create_group($newgroup)) {
198                         echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname), 'notifysuccess');
199                     } else {
200                         echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname));
201                         continue;
202                     }
204                     // Add group to grouping
205                     if (isset($newgroup->groupingname) && strlen($newgroup->groupingname)) {
206                         $groupingname = $newgroup->groupingname;
207                         if (! $groupingid = groups_get_grouping_by_name($newgroup->courseid, $groupingname)) {
208                             $data = new stdClass();
209                             $data->courseid = $newgroup->courseid;
210                             $data->name = $groupingname;
211                             if ($groupingid = groups_create_grouping($data)) {
212                                 echo $OUTPUT->notification(get_string('groupingaddedsuccesfully', 'group', $groupingname), 'notifysuccess');
213                             } else {
214                                 echo $OUTPUT->notification(get_string('groupingnotaddederror', 'error', $groupingname));
215                                 continue;
216                             }
217                         }
219                         // if we have reached here we definitely have a groupingid
220                         $a = array('groupname' => $groupname, 'groupingname' => $groupingname);
221                         try {
222                             groups_assign_grouping($groupingid, $groupid);
223                             echo $OUTPUT->notification(get_string('groupaddedtogroupingsuccesfully', 'group', $a), 'notifysuccess');
224                         } catch (Exception $e) {
225                             echo $OUTPUT->notification(get_string('groupnotaddedtogroupingerror', 'error', $a));
226                         }
228                     }
229                 }
230             }
231             unset ($newgroup);
232         }
233     }
235     echo $OUTPUT->single_button($returnurl, get_string('continue'), 'get');
236     echo $OUTPUT->footer();
237     die;
240 /// Print the form
241 echo $OUTPUT->header();
242 echo $OUTPUT->heading_with_help($strimportgroups, 'importgroups', 'core_group');
243 $mform_post ->display();
244 echo $OUTPUT->footer();