a0e000abcbe35574a982152906b4721df04dd4d0
[moodle-mod_attendance.git] / classes / import / sessions.php
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 * Import attendance sessions class.
19 *
20 * @package mod_attendance
21 * @author Chris Wharton <chriswharton@catalyst.net.nz>
22 * @copyright 2017 Catalyst IT
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26 namespace mod_attendance\import;
27
28 defined('MOODLE_INTERNAL') || die();
29
30 use csv_import_reader;
31 use mod_attendance_notifyqueue;
32 use mod_attendance_structure;
33 use stdClass;
34
35 /**
36 * Import attendance sessions.
37 *
38 * @package mod_attendance
39 * @author Chris Wharton <chriswharton@catalyst.net.nz>
40 * @copyright 2017 Catalyst IT
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 */
43 class sessions {
44
45 /** @var string $error The errors message from reading the xml */
46 protected $error = '';
47
48 /** @var array $sessions The sessions info */
49 protected $sessions = array();
50
51 /** @var array $mappings The mappings info */
52 protected $mappings = array();
53
54 /** @var int The id of the csv import */
55 protected $importid = 0;
56
57 /** @var csv_import_reader|null $importer */
58 protected $importer = null;
59
60 /** @var array $foundheaders */
61 protected $foundheaders = array();
62
63 /** @var bool $useprogressbar Control whether importing should use progress bars or not. */
64 protected $useprogressbar = false;
65
66 /** @var \core\progress\display_if_slow|null $progress The progress bar instance. */
67 protected $progress = null;
68
69 /**
70 * Store an error message for display later
71 *
72 * @param string $msg
73 */
74 public function fail($msg) {
75 $this->error = $msg;
76 return false;
77 }
78
79 /**
80 * Get the CSV import id
81 *
82 * @return string The import id.
83 */
84 public function get_importid() {
85 return $this->importid;
86 }
87
88 /**
89 * Get the list of headers required for import.
90 *
91 * @return array The headers (lang strings)
92 */
93 public static function list_required_headers() {
94 return array(
95 get_string('course', 'attendance'),
96 get_string('groups', 'attendance'),
97 get_string('sessiondate', 'attendance'),
98 get_string('from', 'attendance'),
99 get_string('to', 'attendance'),
100 get_string('description', 'attendance'),
101 get_string('repeaton', 'attendance'),
102 get_string('repeatevery', 'attendance'),
103 get_string('repeatuntil', 'attendance'),
104 get_string('studentscanmark', 'attendance'),
105 get_string('passwordgrp', 'attendance'),
106 get_string('randompassword', 'attendance'),
107 get_string('subnet', 'attendance'),
108 get_string('automark', 'attendance'),
109 get_string('autoassignstatus', 'attendance'),
110 get_string('absenteereport', 'attendance')
111 );
112 }
113
114 /**
115 * Get the list of headers found in the import.
116 *
117 * @return array The found headers (names from import)
118 */
119 public function list_found_headers() {
120 return $this->foundheaders;
121 }
122
123 /**
124 * Read the data from the mapping form.
125 *
126 * @param array $data The mapping data.
127 */
128 protected function read_mapping_data($data) {
129 if ($data) {
130 return array(
131 'course' => $data->header0,
132 'groups' => $data->header1,
133 'sessiondate' => $data->header2,
134 'from' => $data->header3,
135 'to' => $data->header4,
136 'description' => $data->header5,
137 'studentscanmark' => $data->header6,
138 'passwordgrp' => $data->header7,
139 'randompassword' => $data->header8,
140 'subnet' => $data->header9,
141 'automark' => $data->header10,
142 'autoassignstatus' => $data->header11,
143 'absenteereport' => $data->header12
144 );
145 } else {
146 return array(
147 'course' => 0,
148 'groups' => 1,
149 'sessiondate' => 2,
150 'from' => 3,
151 'to' => 4,
152 'description' => 5,
153 'studentscanmark' => 6,
154 'passwordgrp' => 7,
155 'randompassword' => 8,
156 'subnet' => 9,
157 'automark' => 10,
158 'autoassignstatus' => 11,
159 'absenteereport' => 12
160 );
161 }
162 }
163
164 /**
165 * Get the a column from the imported data.
166 *
167 * @param array $row The imported raw row
168 * @param int $index The column index we want
169 * @return string The column data.
170 */
171 protected function get_column_data($row, $index) {
172 if ($index < 0) {
173 return '';
174 }
175 return isset($row[$index]) ? $row[$index] : '';
176 }
177
178 /**
179 * Constructor - parses the raw text for sanity.
180 *
181 * @param string $text The raw csv text.
182 * @param string $encoding The encoding of the csv file.
183 * @param string $delimiter The specified delimiter for the file.
184 * @param string $importid The id of the csv import.
185 * @param array $mappingdata The mapping data from the import form.
186 * @param bool $useprogressbar Whether progress bar should be displayed, to avoid html output on CLI.
187 */
188 public function __construct($text = null, $encoding = null, $delimiter = null, $importid = 0,
189 $mappingdata = null, $useprogressbar = false) {
190 global $CFG;
191
192 require_once($CFG->libdir . '/csvlib.class.php');
193
194 $pluginconfig = get_config('attendance');
195
196 $type = 'sessions';
197
198 if (! $importid) {
199 if ($text === null) {
200 return;
201 }
202 $this->importid = csv_import_reader::get_new_iid($type);
203
204 $this->importer = new csv_import_reader($this->importid, $type);
205
206 if (! $this->importer->load_csv_content($text, $encoding, $delimiter)) {
207 $this->fail(get_string('invalidimportfile', 'attendance'));
208 $this->importer->cleanup();
209 return;
210 }
211 } else {
212 $this->importid = $importid;
213
214 $this->importer = new csv_import_reader($this->importid, $type);
215 }
216
217 if (! $this->importer->init()) {
218 $this->fail(get_string('invalidimportfile', 'attendance'));
219 $this->importer->cleanup();
220 return;
221 }
222
223 $this->foundheaders = $this->importer->get_columns();
224 $this->useprogressbar = $useprogressbar;
225 $domainid = 1;
226
227 $sessions = array();
228
229 while ($row = $this->importer->next()) {
230 // This structure mimics what the UI form returns.
231 $mapping = $this->read_mapping_data($mappingdata);
232
233 $session = new stdClass();
234 $session->course = $this->get_column_data($row, $mapping['course']);
235 if (empty($session->course)) {
236 \mod_attendance_notifyqueue::notify_problem(get_string('error:sessioncourseinvalid', 'attendance'));
237 continue;
238 }
239
240 // Handle multiple group assignments per session. Expect semicolon separated group names.
241 $groups = $this->get_column_data($row, $mapping['groups']);
242 if (! empty($groups)) {
243 $session->groups = explode(';', $groups);
244 $session->sessiontype = \mod_attendance_structure::SESSION_GROUP;
245 } else {
246 $session->sessiontype = \mod_attendance_structure::SESSION_COMMON;
247 }
248
249 // Expect standardised date format, eg YYYY-MM-DD.
250 $sessiondate = strtotime($this->get_column_data($row, $mapping['sessiondate']));
251 if ($sessiondate === false) {
252 \mod_attendance_notifyqueue::notify_problem(get_string('error:sessiondateinvalid', 'attendance'));
253 continue;
254 }
255 $session->sessiondate = $sessiondate;
256
257 // Expect standardised time format, eg HH:MM.
258 $from = $this->get_column_data($row, $mapping['from']);
259 if (empty($from)) {
260 \mod_attendance_notifyqueue::notify_problem(get_string('error:sessionstartinvalid', 'attendance'));
261 continue;
262 }
263 $from = explode(':', $from);
264 $session->sestime['starthour'] = $from[0];
265 $session->sestime['startminute'] = $from[1];
266
267 $to = $this->get_column_data($row, $mapping['to']);
268 if (empty($to)) {
269 \mod_attendance_notifyqueue::notify_problem(get_string('error:sessionendinvalid', 'attendance'));
270 continue;
271 }
272 $to = explode(':', $to);
273 $session->sestime['endhour'] = $to[0];
274 $session->sestime['endminute'] = $to[1];
275
276 // Wrap the plain text description in html tags.
277 $session->sdescription['text'] = '<p>' . $this->get_column_data($row, $mapping['description']) . '</p>';
278 $session->sdescription['format'] = FORMAT_HTML;
279 $session->sdescription['itemid'] = 0;
280 $session->passwordgrp = $this->get_column_data($row, $mapping['passwordgrp']);
281 $session->subnet = $this->get_column_data($row, $mapping['subnet']);
282 // Set session subnet restriction. Use the default activity level subnet if there isn't one set for this session.
283 if (empty($session->subnet)) {
284 $session->usedefaultsubnet = '1';
285 } else {
286 $session->usedefaultsubnet = '';
287 }
288
289 if ($mapping['studentscanmark'] == -1) {
290 $session->studentscanmark = $pluginconfig->studentscanmark_default;
291 } else {
292 $session->studentscanmark = $this->get_column_data($row, $mapping['studentscanmark']);
293 }
294 if ($mapping['randompassword'] == -1) {
295 $session->randompassword = $pluginconfig->randompassword_default;
296 } else {
297 $session->randompassword = $this->get_column_data($row, $mapping['randompassword']);
298 }
299 if ($mapping['automark'] == -1) {
300 $session->automark = $pluginconfig->automark_default;
301 } else {
302 $session->automark = $this->get_column_data($row, $mapping['automark']);
303 }
304 if ($mapping['autoassignstatus'] == -1) {
305 $session->autoassignstatus = $pluginconfig->autoassignstatus;
306 } else {
307 $session->autoassignstatus = $this->get_column_data($row, $mapping['autoassignstatus']);
308 }
309 if ($mapping['absenteereport'] == -1) {
310 $session->absenteereport = $pluginconfig->absenteereport_default;
311 } else {
312 $session->absenteereport = $this->get_column_data($row, $mapping['absenteereport']);
313 }
314 $session->statusset = 0;
315
316 $sessions[] = $session;
317 }
318 $this->sessions = $sessions;
319
320 $this->importer->close();
321 if ($this->sessions == null) {
322 $this->fail(get_string('invalidimportfile', 'attendance'));
323 return;
324 } else {
325 // We are calling from browser, display progress bar.
326 if ($this->useprogressbar === true) {
327 $this->progress = new \core\progress\display_if_slow(get_string('processingfile', 'attendance'));
328 $this->progress->start_html();
329 } else {
330 // Avoid html output on CLI scripts.
331 $this->progress = new \core\progress\none();
332 }
333 $this->progress->start_progress('', count($this->sessions));
334 raise_memory_limit(MEMORY_EXTRA);
335 $this->progress->end_progress();
336 }
337 }
338
339 /**
340 * Get parse errors.
341 *
342 * @return array of errors from parsing the xml.
343 */
344 public function get_error() {
345 return $this->error;
346 }
347
348 /**
349 * Create sessions using the CSV data.
350 *
351 * @return void
352 */
353 public function import() {
354 global $DB;
355
356 // Count of sessions added.
357 $okcount = 0;
358
359 foreach ($this->sessions as $session) {
360 $groupids = array();
361 // Check course shortname matches.
362 if ($DB->record_exists('course', array(
363 'shortname' => $session->course
364 ))) {
365 // Get course.
366 $course = $DB->get_record('course', array(
367 'shortname' => $session->course
368 ), '*', MUST_EXIST);
369
370 // Check course has activities.
371 if ($DB->record_exists('attendance', array(
372 'course' => $course->id
373 ))) {
374 // Translate group names to group IDs. They are unique per course.
375 if ($session->sessiontype === \mod_attendance_structure::SESSION_GROUP) {
376 foreach ($session->groups as $groupname) {
377 $gid = groups_get_group_by_name($course->id, $groupname);
378 if ($gid === false) {
379 \mod_attendance_notifyqueue::notify_problem(get_string('sessionunknowngroup',
380 'attendance', $groupname));
381 } else {
382 $groupids[] = $gid;
383 }
384 }
385 $session->groups = $groupids;
386 }
387
388 // Get activities in course.
389 $activities = $DB->get_recordset('attendance', array(
390 'course' => $course->id
391 ), 'id', 'id');
392
393 foreach ($activities as $activity) {
394 // Build the session data.
395 $cm = get_coursemodule_from_instance('attendance', $activity->id, $course->id);
396 if (!empty($cm->deletioninprogress)) {
397 // Don't do anything if this attendance is in recycle bin.
398 continue;
399 }
400 $att = new mod_attendance_structure($activity, $cm, $course);
401 $sessions = attendance_construct_sessions_data_for_add($session, $att);
402
403 foreach ($sessions as $index => $sess) {
404 // Check for duplicate sessions.
405 if ($this->session_exists($sess)) {
406 mod_attendance_notifyqueue::notify_message(get_string('sessionduplicate', 'attendance', (array(
407 'course' => $session->course,
408 'activity' => $cm->name
409 ))));
410 unset($sessions[$index]);
411 } else {
412 $okcount ++;
413 }
414 }
415 if (! empty($sessions)) {
416 $att->add_sessions($sessions);
417 }
418 }
419 $activities->close();
420 } else {
421 mod_attendance_notifyqueue::notify_problem(get_string('error:coursehasnoattendance',
422 'attendance', $session->course));
423 }
424 } else {
425 mod_attendance_notifyqueue::notify_problem(get_string('error:coursenotfound', 'attendance', $session->course));
426 }
427 }
428
429 $message = get_string('sessionsgenerated', 'attendance', $okcount);
430 if ($okcount < 1) {
431 mod_attendance_notifyqueue::notify_message($message);
432 } else {
433 mod_attendance_notifyqueue::notify_success($message);
434 }
435
436 // Trigger a sessions imported event.
437 $event = \mod_attendance\event\sessions_imported::create(array(
438 'objectid' => 0,
439 'context' => \context_system::instance(),
440 'other' => array(
441 'count' => $okcount
442 )
443 ));
444
445 $event->trigger();
446 }
447
448 /**
449 * Check if an identical session exists.
450 *
451 * @param stdClass $session
452 * @return boolean
453 */
454 private function session_exists(stdClass $session) {
455 global $DB;
456
457 $check = clone $session;
458
459 // Remove the properties that aren't useful to check.
460 unset($check->description);
461 unset($check->descriptionitemid);
462 unset($check->timemodified);
463 $check = (array) $check;
464
465 if ($DB->record_exists('attendance_sessions', $check)) {
466 return true;
467 }
468 return false;
469 }
470 }