2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Import attendance sessions class.
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
26 namespace mod_attendance\import
;
28 defined('MOODLE_INTERNAL') ||
die();
30 use csv_import_reader
;
31 use mod_attendance_notifyqueue
;
32 use mod_attendance_structure
;
36 * Import attendance sessions.
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
45 /** @var string $error The errors message from reading the xml */
46 protected $error = '';
48 /** @var array $sessions The sessions info */
49 protected $sessions = array();
51 /** @var array $mappings The mappings info */
52 protected $mappings = array();
54 /** @var int The id of the csv import */
55 protected $importid = 0;
57 /** @var csv_import_reader|null $importer */
58 protected $importer = null
;
60 /** @var array $foundheaders */
61 protected $foundheaders = array();
63 /** @var bool $useprogressbar Control whether importing should use progress bars or not. */
64 protected $useprogressbar = false
;
66 /** @var \core\progress\display_if_slow|null $progress The progress bar instance. */
67 protected $progress = null
;
70 * Store an error message for display later
74 public function fail($msg) {
80 * Get the CSV import id
82 * @return string The import id.
84 public function get_importid() {
85 return $this->importid
;
89 * Get the list of headers required for import.
91 * @return array The headers (lang strings)
93 public static function list_required_headers() {
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')
115 * Get the list of headers found in the import.
117 * @return array The found headers (names from import)
119 public function list_found_headers() {
120 return $this->foundheaders
;
124 * Read the data from the mapping form.
126 * @param array $data The mapping data.
128 protected function read_mapping_data($data) {
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
153 'studentscanmark' => 6,
155 'randompassword' => 8,
158 'autoassignstatus' => 11,
159 'absenteereport' => 12
165 * Get the a column from the imported data.
167 * @param array $row The imported raw row
168 * @param int $index The column index we want
169 * @return string The column data.
171 protected function get_column_data($row, $index) {
175 return isset($row[$index]) ?
$row[$index] : '';
179 * Constructor - parses the raw text for sanity.
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.
188 public function __construct($text = null
, $encoding = null
, $delimiter = null
, $importid = 0,
189 $mappingdata = null
, $useprogressbar = false
) {
192 require_once($CFG->libdir
. '/csvlib.class.php');
194 $pluginconfig = get_config('attendance');
199 if ($text === null
) {
202 $this->importid
= csv_import_reader
::get_new_iid($type);
204 $this->importer
= new csv_import_reader($this->importid
, $type);
206 if (! $this->importer
->load_csv_content($text, $encoding, $delimiter)) {
207 $this->fail(get_string('invalidimportfile', 'attendance'));
208 $this->importer
->cleanup();
212 $this->importid
= $importid;
214 $this->importer
= new csv_import_reader($this->importid
, $type);
217 if (! $this->importer
->init()) {
218 $this->fail(get_string('invalidimportfile', 'attendance'));
219 $this->importer
->cleanup();
223 $this->foundheaders
= $this->importer
->get_columns();
224 $this->useprogressbar
= $useprogressbar;
229 while ($row = $this->importer
->next()) {
230 // This structure mimics what the UI form returns.
231 $mapping = $this->read_mapping_data($mappingdata);
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'));
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
;
246 $session->sessiontype
= \mod_attendance_structure
::SESSION_COMMON
;
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'));
255 $session->sessiondate
= $sessiondate;
257 // Expect standardised time format, eg HH:MM.
258 $from = $this->get_column_data($row, $mapping['from']);
260 \mod_attendance_notifyqueue
::notify_problem(get_string('error:sessionstartinvalid', 'attendance'));
263 $from = explode(':', $from);
264 $session->sestime
['starthour'] = $from[0];
265 $session->sestime
['startminute'] = $from[1];
267 $to = $this->get_column_data($row, $mapping['to']);
269 \mod_attendance_notifyqueue
::notify_problem(get_string('error:sessionendinvalid', 'attendance'));
272 $to = explode(':', $to);
273 $session->sestime
['endhour'] = $to[0];
274 $session->sestime
['endminute'] = $to[1];
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';
286 $session->usedefaultsubnet
= '';
289 if ($mapping['studentscanmark'] == -1) {
290 $session->studentscanmark
= $pluginconfig->studentscanmark_default
;
292 $session->studentscanmark
= $this->get_column_data($row, $mapping['studentscanmark']);
294 if ($mapping['randompassword'] == -1) {
295 $session->randompassword
= $pluginconfig->randompassword_default
;
297 $session->randompassword
= $this->get_column_data($row, $mapping['randompassword']);
299 if ($mapping['automark'] == -1) {
300 $session->automark
= $pluginconfig->automark_default
;
302 $session->automark
= $this->get_column_data($row, $mapping['automark']);
304 if ($mapping['autoassignstatus'] == -1) {
305 $session->autoassignstatus
= $pluginconfig->autoassignstatus
;
307 $session->autoassignstatus
= $this->get_column_data($row, $mapping['autoassignstatus']);
309 if ($mapping['absenteereport'] == -1) {
310 $session->absenteereport
= $pluginconfig->absenteereport_default
;
312 $session->absenteereport
= $this->get_column_data($row, $mapping['absenteereport']);
314 $session->statusset
= 0;
316 $sessions[] = $session;
318 $this->sessions
= $sessions;
320 $this->importer
->close();
321 if ($this->sessions
== null
) {
322 $this->fail(get_string('invalidimportfile', 'attendance'));
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();
330 // Avoid html output on CLI scripts.
331 $this->progress
= new \core\progress
\none
();
333 $this->progress
->start_progress('', count($this->sessions
));
334 raise_memory_limit(MEMORY_EXTRA
);
335 $this->progress
->end_progress();
342 * @return array of errors from parsing the xml.
344 public function get_error() {
349 * Create sessions using the CSV data.
353 public function import() {
356 // Count of sessions added.
359 foreach ($this->sessions
as $session) {
361 // Check course shortname matches.
362 if ($DB->record_exists('course', array(
363 'shortname' => $session->course
366 $course = $DB->get_record('course', array(
367 'shortname' => $session->course
370 // Check course has activities.
371 if ($DB->record_exists('attendance', array(
372 'course' => $course->id
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));
385 $session->groups
= $groupids;
388 // Get activities in course.
389 $activities = $DB->get_recordset('attendance', array(
390 'course' => $course->id
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.
400 $att = new mod_attendance_structure($activity, $cm, $course);
401 $sessions = attendance_construct_sessions_data_for_add($session, $att);
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
410 unset($sessions[$index]);
415 if (! empty($sessions)) {
416 $att->add_sessions($sessions);
419 $activities->close();
421 mod_attendance_notifyqueue
::notify_problem(get_string('error:coursehasnoattendance',
422 'attendance', $session->course
));
425 mod_attendance_notifyqueue
::notify_problem(get_string('error:coursenotfound', 'attendance', $session->course
));
429 $message = get_string('sessionsgenerated', 'attendance', $okcount);
431 mod_attendance_notifyqueue
::notify_message($message);
433 mod_attendance_notifyqueue
::notify_success($message);
436 // Trigger a sessions imported event.
437 $event = \mod_attendance\event\sessions_imported
::create(array(
439 'context' => \context_system
::instance(),
449 * Check if an identical session exists.
451 * @param stdClass $session
454 private function session_exists(stdClass
$session) {
457 $check = clone $session;
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;
465 if ($DB->record_exists('attendance_sessions', $check)) {