Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 * @package   mod_scorm
19
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
20
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21
 */
22
defined('MOODLE_INTERNAL') || die();
23
 
24
/** SCORM_TYPE_LOCAL = local */
25
define('SCORM_TYPE_LOCAL', 'local');
26
/** SCORM_TYPE_LOCALSYNC = localsync */
27
define('SCORM_TYPE_LOCALSYNC', 'localsync');
28
/** SCORM_TYPE_EXTERNAL = external */
29
define('SCORM_TYPE_EXTERNAL', 'external');
30
/** SCORM_TYPE_AICCURL = external AICC url */
31
define('SCORM_TYPE_AICCURL', 'aiccurl');
32
 
33
define('SCORM_TOC_SIDE', 0);
34
define('SCORM_TOC_HIDDEN', 1);
35
define('SCORM_TOC_POPUP', 2);
36
define('SCORM_TOC_DISABLED', 3);
37
 
38
// Used to show/hide navigation buttons and set their position.
39
define('SCORM_NAV_DISABLED', 0);
40
define('SCORM_NAV_UNDER_CONTENT', 1);
41
define('SCORM_NAV_FLOATING', 2);
42
 
43
// Used to check what SCORM version is being used.
44
define('SCORM_12', 1);
45
define('SCORM_13', 2);
46
define('SCORM_AICC', 3);
47
 
48
// List of possible attemptstatusdisplay options.
49
define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
50
define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
51
define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
52
define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
53
 
54
define('SCORM_EVENT_TYPE_OPEN', 'open');
55
define('SCORM_EVENT_TYPE_CLOSE', 'close');
56
 
57
/**
58
 * Return an array of status options
59
 *
60
 * Optionally with translated strings
61
 *
62
 * @param   bool    $with_strings   (optional)
63
 * @return  array
64
 */
65
function scorm_status_options($withstrings = false) {
66
    // Id's are important as they are bits.
67
    $options = array(
68
        2 => 'passed',
69
        4 => 'completed'
70
    );
71
 
72
    if ($withstrings) {
73
        foreach ($options as $key => $value) {
74
            $options[$key] = get_string('completionstatus_'.$value, 'scorm');
75
        }
76
    }
77
 
78
    return $options;
79
}
80
 
81
 
82
/**
83
 * Given an object containing all the necessary data,
84
 * (defined by the form in mod_form.php) this function
85
 * will create a new instance and return the id number
86
 * of the new instance.
87
 *
88
 * @global stdClass
89
 * @global object
90
 * @uses CONTEXT_MODULE
91
 * @uses SCORM_TYPE_LOCAL
92
 * @uses SCORM_TYPE_LOCALSYNC
93
 * @uses SCORM_TYPE_EXTERNAL
94
 * @param object $scorm Form data
95
 * @param object $mform
96
 * @return int new instance id
97
 */
98
function scorm_add_instance($scorm, $mform=null) {
99
    global $CFG, $DB;
100
 
101
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
102
 
103
    if (empty($scorm->timeopen)) {
104
        $scorm->timeopen = 0;
105
    }
106
    if (empty($scorm->timeclose)) {
107
        $scorm->timeclose = 0;
108
    }
109
    if (empty($scorm->completionstatusallscos)) {
110
        $scorm->completionstatusallscos = 0;
111
    }
112
    $cmid       = $scorm->coursemodule;
113
    $cmidnumber = $scorm->cmidnumber;
114
    $courseid   = $scorm->course;
115
 
116
    $context = context_module::instance($cmid);
117
 
118
    $scorm = scorm_option2text($scorm);
119
    $scorm->width  = (int)str_replace('%', '', $scorm->width);
120
    $scorm->height = (int)str_replace('%', '', $scorm->height);
121
 
122
    if (!isset($scorm->whatgrade)) {
123
        $scorm->whatgrade = 0;
124
    }
125
 
126
    $id = $DB->insert_record('scorm', $scorm);
127
 
128
    // Update course module record - from now on this instance properly exists and all function may be used.
129
    $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
130
 
131
    // Reload scorm instance.
132
    $record = $DB->get_record('scorm', array('id' => $id));
133
 
134
    // Store the package and verify.
135
    if ($record->scormtype === SCORM_TYPE_LOCAL) {
136
        if (!empty($scorm->packagefile)) {
137
            $fs = get_file_storage();
138
            $fs->delete_area_files($context->id, 'mod_scorm', 'package');
139
            file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
140
                0, array('subdirs' => 0, 'maxfiles' => 1));
141
            // Get filename of zip that was uploaded.
142
            $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
143
            $file = reset($files);
144
            $filename = $file->get_filename();
145
            if ($filename !== false) {
146
                $record->reference = $filename;
147
            }
148
        }
149
 
150
    } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
151
        $record->reference = $scorm->packageurl;
152
    } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
153
        $record->reference = $scorm->packageurl;
154
    } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
155
        $record->reference = $scorm->packageurl;
156
        $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
157
    } else {
158
        return false;
159
    }
160
 
161
    // Save reference.
162
    $DB->update_record('scorm', $record);
163
 
164
    // Extra fields required in grade related functions.
165
    $record->course     = $courseid;
166
    $record->cmidnumber = $cmidnumber;
167
    $record->cmid       = $cmid;
168
 
169
    scorm_parse($record, true);
170
 
171
    scorm_grade_item_update($record);
172
    scorm_update_calendar($record, $cmid);
173
    if (!empty($scorm->completionexpected)) {
174
        \core_completion\api::update_completion_date_event($cmid, 'scorm', $record, $scorm->completionexpected);
175
    }
176
 
177
    return $record->id;
178
}
179
 
180
/**
181
 * Given an object containing all the necessary data,
182
 * (defined by the form in mod_form.php) this function
183
 * will update an existing instance with new data.
184
 *
185
 * @global stdClass
186
 * @global object
187
 * @uses CONTEXT_MODULE
188
 * @uses SCORM_TYPE_LOCAL
189
 * @uses SCORM_TYPE_LOCALSYNC
190
 * @uses SCORM_TYPE_EXTERNAL
191
 * @param object $scorm Form data
192
 * @param object $mform
193
 * @return bool
194
 */
195
function scorm_update_instance($scorm, $mform=null) {
196
    global $CFG, $DB;
197
 
198
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
199
 
200
    if (empty($scorm->timeopen)) {
201
        $scorm->timeopen = 0;
202
    }
203
    if (empty($scorm->timeclose)) {
204
        $scorm->timeclose = 0;
205
    }
206
    if (empty($scorm->completionstatusallscos)) {
207
        $scorm->completionstatusallscos = 0;
208
    }
209
 
210
    $cmid       = $scorm->coursemodule;
211
    $cmidnumber = $scorm->cmidnumber;
212
    $courseid   = $scorm->course;
213
 
214
    $scorm->id = $scorm->instance;
215
 
216
    $context = context_module::instance($cmid);
217
 
218
    if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
219
        if (!empty($scorm->packagefile)) {
220
            $fs = get_file_storage();
221
            $fs->delete_area_files($context->id, 'mod_scorm', 'package');
222
            file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
223
                0, array('subdirs' => 0, 'maxfiles' => 1));
224
            // Get filename of zip that was uploaded.
225
            $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
226
            $file = reset($files);
227
            $filename = $file->get_filename();
228
            if ($filename !== false) {
229
                $scorm->reference = $filename;
230
            }
231
        }
232
 
233
    } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
234
        $scorm->reference = $scorm->packageurl;
235
    } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
236
        $scorm->reference = $scorm->packageurl;
237
    } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
238
        $scorm->reference = $scorm->packageurl;
239
        $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
240
    } else {
241
        return false;
242
    }
243
 
244
    $scorm = scorm_option2text($scorm);
245
    $scorm->width        = (int)str_replace('%', '', $scorm->width);
246
    $scorm->height       = (int)str_replace('%', '', $scorm->height);
247
    $scorm->timemodified = time();
248
 
249
    if (!isset($scorm->whatgrade)) {
250
        $scorm->whatgrade = 0;
251
    }
252
 
253
    $DB->update_record('scorm', $scorm);
254
    // We need to find this out before we blow away the form data.
255
    $completionexpected = (!empty($scorm->completionexpected)) ? $scorm->completionexpected : null;
256
 
257
    $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
258
 
259
    // Extra fields required in grade related functions.
260
    $scorm->course   = $courseid;
261
    $scorm->idnumber = $cmidnumber;
262
    $scorm->cmid     = $cmid;
263
 
264
    scorm_parse($scorm, (bool)$scorm->updatefreq);
265
 
266
    scorm_grade_item_update($scorm);
267
    scorm_update_grades($scorm);
268
    scorm_update_calendar($scorm, $cmid);
269
    \core_completion\api::update_completion_date_event($cmid, 'scorm', $scorm, $completionexpected);
270
 
271
    return true;
272
}
273
 
274
/**
275
 * Given an ID of an instance of this module,
276
 * this function will permanently delete the instance
277
 * and any data that depends on it.
278
 *
279
 * @global stdClass
280
 * @global object
281
 * @param int $id Scorm instance id
282
 * @return boolean
283
 */
284
function scorm_delete_instance($id) {
285
    global $CFG, $DB;
286
 
287
    if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
288
        return false;
289
    }
290
 
291
    $result = true;
292
 
293
    require_once($CFG->dirroot . '/mod/scorm/locallib.php');
294
    // Delete any dependent records.
295
    scorm_delete_tracks($scorm->id);
296
    if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
297
        foreach ($scoes as $sco) {
298
            if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
299
                $result = false;
300
            }
301
        }
302
        $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
303
    }
304
 
305
    scorm_grade_item_delete($scorm);
306
 
307
    // We must delete the module record after we delete the grade item.
308
    if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
309
        $result = false;
310
    }
311
 
312
    /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
313
        $result = false;
314
    }
315
    if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
316
        $result = false;
317
    }
318
    if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
319
        $result = false;
320
    }
321
    if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
322
        $result = false;
323
    }
324
    if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
325
        $result = false;
326
    }
327
    if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
328
        $result = false;
329
    }
330
    if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
331
        $result = false;
332
    }*/
333
 
334
    return $result;
335
}
336
 
337
/**
338
 * Return a small object with summary information about what a
339
 * user has done with a given particular instance of this module
340
 * Used for user activity reports.
341
 *
342
 * @param stdClass $course Course object
343
 * @param stdClass $user User
344
 * @param stdClass $mod
345
 * @param stdClass $scorm The scorm
346
 * @return mixed
347
 */
348
function scorm_user_outline($course, $user, $mod, $scorm) {
349
    global $CFG;
350
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
351
 
352
    require_once("$CFG->libdir/gradelib.php");
353
    $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
354
    if (!empty($grades->items[0]->grades)) {
355
        $grade = reset($grades->items[0]->grades);
356
        $result = (object) [
357
            'time' => grade_get_date_for_user_grade($grade, $user),
358
        ];
359
        if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
360
            $result->info = get_string('gradenoun') . ': '. $grade->str_long_grade;
361
        } else {
362
            $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
363
        }
364
 
365
        return $result;
366
    }
367
    return null;
368
}
369
 
370
/**
371
 * Print a detailed representation of what a user has done with
372
 * a given particular instance of this module, for user activity reports.
373
 *
374
 * @global stdClass
375
 * @global object
376
 * @param object $course
377
 * @param object $user
378
 * @param object $mod
379
 * @param object $scorm
380
 * @return boolean
381
 */
382
function scorm_user_complete($course, $user, $mod, $scorm) {
383
    global $CFG, $DB, $OUTPUT;
384
    require_once("$CFG->libdir/gradelib.php");
385
 
386
    $liststyle = 'structlist';
387
    $now = time();
388
    $firstmodify = $now;
389
    $lastmodify = 0;
390
    $sometoreport = false;
391
    $report = '';
392
 
393
    // First Access and Last Access dates for SCOs.
394
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
395
    $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
396
    $firstmodify = $timetracks->start;
397
    $lastmodify = $timetracks->finish;
398
 
399
    $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
400
    if (!empty($grades->items[0]->grades)) {
401
        $grade = reset($grades->items[0]->grades);
402
        if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
403
            echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
404
            if ($grade->str_feedback) {
405
                echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
406
            }
407
        } else {
408
            echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
409
        }
410
    }
411
 
412
    if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
413
                                         $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
414
                                         $DB->sql_isempty('scorm_scoes', 'organization', false, false),
415
                                         array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
416
        if (count($orgs) <= 1) {
417
            unset($orgs);
418
            $orgs = array();
419
            $org = new stdClass();
420
            $org->identifier = '';
421
            $orgs[] = $org;
422
        }
423
        $report .= html_writer::start_div('mod-scorm');
424
        foreach ($orgs as $org) {
425
            $conditions = array();
426
            $currentorg = '';
427
            if (!empty($org->identifier)) {
428
                $report .= html_writer::div($org->title, 'orgtitle');
429
                $currentorg = $org->identifier;
430
                $conditions['organization'] = $currentorg;
431
            }
432
            $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
433
                $conditions['scorm'] = $scorm->id;
434
            if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
435
                // Drop keys so that we can access array sequentially.
436
                $scoes = array_values($scoes);
437
                $level = 0;
438
                $sublist = 1;
439
                $parents[$level] = '/';
440
                foreach ($scoes as $pos => $sco) {
441
                    if ($parents[$level] != $sco->parent) {
442
                        if ($level > 0 && $parents[$level - 1] == $sco->parent) {
443
                            $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
444
                            $level--;
445
                        } else {
446
                            $i = $level;
447
                            $closelist = '';
448
                            while (($i > 0) && ($parents[$level] != $sco->parent)) {
449
                                $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
450
                                $i--;
451
                            }
452
                            if (($i == 0) && ($sco->parent != $currentorg)) {
453
                                $report .= html_writer::start_tag('li');
454
                                $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
455
                                $level++;
456
                            } else {
457
                                $report .= $closelist;
458
                                $level = $i;
459
                            }
460
                            $parents[$level] = $sco->parent;
461
                        }
462
                    }
463
                    $report .= html_writer::start_tag('li');
464
                    if (isset($scoes[$pos + 1])) {
465
                        $nextsco = $scoes[$pos + 1];
466
                    } else {
467
                        $nextsco = false;
468
                    }
469
                    if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
470
                            (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
471
                        $sublist++;
472
                    } else {
473
                        $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
474
                    }
475
 
476
                    if ($sco->launch) {
477
                        $score = '';
478
                        $totaltime = '';
479
                        if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
480
                            if ($usertrack->status == '') {
481
                                $usertrack->status = 'notattempted';
482
                            }
483
                            $strstatus = get_string($usertrack->status, 'scorm');
484
                            $report .= $OUTPUT->pix_icon($usertrack->status, $strstatus, 'scorm');
485
                        } else {
486
                            if ($sco->scormtype == 'sco') {
487
                                $report .= $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
488
                            } else {
489
                                $report .= $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
490
                            }
491
                        }
492
                        $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
493
                        if ($usertrack !== false) {
494
                            $sometoreport = true;
495
                            $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
496
                            foreach ($usertrack as $element => $value) {
497
                                if (substr($element, 0, 3) == 'cmi') {
498
                                    $report .= html_writer::tag('li', s($element) . ' => ' . s($value));
499
                                }
500
                            }
501
                            $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
502
                        }
503
                    } else {
504
                        $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
505
                    }
506
                }
507
                for ($i = 0; $i < $level; $i++) {
508
                    $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
509
                }
510
            }
511
            $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
512
        }
513
        $report .= html_writer::end_div();
514
    }
515
    if ($sometoreport) {
516
        if ($firstmodify < $now) {
517
            $timeago = format_time($now - $firstmodify);
518
            echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
519
        }
520
        if ($lastmodify > 0) {
521
            $timeago = format_time($now - $lastmodify);
522
            echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
523
        }
524
        echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
525
        echo $report;
526
    } else {
527
        print_string('noactivity', 'scorm');
528
    }
529
 
530
    return true;
531
}
532
 
533
/**
534
 * Function to be run periodically according to the moodle Tasks API
535
 * This function searches for things that need to be done, such
536
 * as sending out mail, toggling flags etc ...
537
 *
538
 * @global stdClass
539
 * @global object
540
 * @return boolean
541
 */
542
function scorm_cron_scheduled_task () {
543
    global $CFG, $DB;
544
 
545
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
546
 
547
    $sitetimezone = core_date::get_server_timezone();
548
    // Now see if there are any scorm updates to be done.
549
 
550
    if (!isset($CFG->scorm_updatetimelast)) {    // To catch the first time.
551
        set_config('scorm_updatetimelast', 0);
552
    }
553
 
554
    $timenow = time();
555
    $updatetime = usergetmidnight($timenow, $sitetimezone);
556
 
557
    if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
558
 
559
        set_config('scorm_updatetimelast', $timenow);
560
 
561
        mtrace('Updating scorm packages which require daily update');// We are updating.
562
 
563
        $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
564
        foreach ($scormsupdate as $scormupdate) {
565
            scorm_parse($scormupdate, true);
566
        }
567
 
568
        // Now clear out AICC session table with old session data.
569
        $cfgscorm = get_config('scorm');
570
        if (!empty($cfgscorm->allowaicchacp)) {
571
            $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
572
            $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
573
        }
574
    }
575
 
576
    return true;
577
}
578
 
579
/**
580
 * Return grade for given user or all users.
581
 *
582
 * @global stdClass
583
 * @global object
584
 * @param int $scormid id of scorm
585
 * @param int $userid optional user id, 0 means all users
586
 * @return array array of grades, false if none
587
 */
588
function scorm_get_user_grades($scorm, $userid=0) {
589
    global $CFG, $DB;
590
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
591
 
592
    $grades = array();
593
    if (empty($userid)) {
594
        $sql = "SELECT DISTINCT userid
595
                  FROM {scorm_attempt}
596
                 WHERE scormid = ?";
597
        $scousers = $DB->get_recordset_sql($sql, [$scorm->id]);
598
 
599
        foreach ($scousers as $scouser) {
600
            $grades[$scouser->userid] = new stdClass();
601
            $grades[$scouser->userid]->id = $scouser->userid;
602
            $grades[$scouser->userid]->userid = $scouser->userid;
603
            $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
604
        }
605
        $scousers->close();
606
    } else {
607
        $preattempt = $DB->record_exists('scorm_attempt', ['scormid' => $scorm->id, 'userid' => $userid]);
608
        if (!$preattempt) {
609
            return false; // No attempt yet.
610
        }
611
        $grades[$userid] = new stdClass();
612
        $grades[$userid]->id = $userid;
613
        $grades[$userid]->userid = $userid;
614
        $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
615
    }
616
 
617
    if (empty($grades)) {
618
        return false;
619
    }
620
 
621
    return $grades;
622
}
623
 
624
/**
625
 * Update grades in central gradebook
626
 *
627
 * @category grade
628
 * @param object $scorm
629
 * @param int $userid specific user only, 0 mean all
630
 * @param bool $nullifnone
631
 */
632
function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
633
    global $CFG;
634
    require_once($CFG->libdir.'/gradelib.php');
635
    require_once($CFG->libdir.'/completionlib.php');
636
 
637
    if ($grades = scorm_get_user_grades($scorm, $userid)) {
638
        scorm_grade_item_update($scorm, $grades);
639
        // Set complete.
640
        scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
641
    } else if ($userid and $nullifnone) {
642
        $grade = new stdClass();
643
        $grade->userid   = $userid;
644
        $grade->rawgrade = null;
645
        scorm_grade_item_update($scorm, $grade);
646
        // Set incomplete.
647
        scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
648
    } else {
649
        scorm_grade_item_update($scorm);
650
    }
651
}
652
 
653
/**
654
 * Update/create grade item for given scorm
655
 *
656
 * @category grade
657
 * @uses GRADE_TYPE_VALUE
658
 * @uses GRADE_TYPE_NONE
659
 * @param object $scorm object with extra cmidnumber
660
 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
661
 * @return object grade_item
662
 */
663
function scorm_grade_item_update($scorm, $grades=null) {
664
    global $CFG, $DB;
665
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
666
    if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
667
        require_once($CFG->libdir.'/gradelib.php');
668
    }
669
 
670
    $params = array('itemname' => $scorm->name);
671
    if (isset($scorm->cmidnumber)) {
672
        $params['idnumber'] = $scorm->cmidnumber;
673
    }
674
 
675
    if ($scorm->grademethod == GRADESCOES) {
676
        $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
677
                                                $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
678
        if ($maxgrade) {
679
            $params['gradetype'] = GRADE_TYPE_VALUE;
680
            $params['grademax']  = $maxgrade;
681
            $params['grademin']  = 0;
682
        } else {
683
            $params['gradetype'] = GRADE_TYPE_NONE;
684
        }
685
    } else {
686
        $params['gradetype'] = GRADE_TYPE_VALUE;
687
        $params['grademax']  = $scorm->maxgrade;
688
        $params['grademin']  = 0;
689
    }
690
 
691
    if ($grades === 'reset') {
692
        $params['reset'] = true;
693
        $grades = null;
694
    }
695
 
696
    return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
697
}
698
 
699
/**
700
 * Delete grade item for given scorm
701
 *
702
 * @category grade
703
 * @param object $scorm object
704
 * @return object grade_item
705
 */
706
function scorm_grade_item_delete($scorm) {
707
    global $CFG;
708
    require_once($CFG->libdir.'/gradelib.php');
709
 
710
    return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
711
}
712
 
713
/**
714
 * List the actions that correspond to a view of this module.
715
 * This is used by the participation report.
716
 *
717
 * Note: This is not used by new logging system. Event with
718
 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
719
 *       be considered as view action.
720
 *
721
 * @return array
722
 */
723
function scorm_get_view_actions() {
724
    return array('pre-view', 'view', 'view all', 'report');
725
}
726
 
727
/**
728
 * List the actions that correspond to a post of this module.
729
 * This is used by the participation report.
730
 *
731
 * Note: This is not used by new logging system. Event with
732
 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
733
 *       will be considered as post action.
734
 *
735
 * @return array
736
 */
737
function scorm_get_post_actions() {
738
    return array();
739
}
740
 
741
/**
742
 * @param object $scorm
743
 * @return object $scorm
744
 */
745
function scorm_option2text($scorm) {
746
    $scormpopoupoptions = scorm_get_popup_options_array();
747
 
748
    if (isset($scorm->popup)) {
749
        if ($scorm->popup == 1) {
750
            $optionlist = array();
751
            foreach ($scormpopoupoptions as $name => $option) {
752
                if (isset($scorm->$name)) {
753
                    $optionlist[] = $name.'='.$scorm->$name;
754
                } else {
755
                    $optionlist[] = $name.'=0';
756
                }
757
            }
758
            $scorm->options = implode(',', $optionlist);
759
        } else {
760
            $scorm->options = '';
761
        }
762
    } else {
763
        $scorm->popup = 0;
764
        $scorm->options = '';
765
    }
766
    return $scorm;
767
}
768
 
769
/**
770
 * Implementation of the function for printing the form elements that control
771
 * whether the course reset functionality affects the scorm.
772
 *
773
 * @param MoodleQuickForm $mform form passed by reference
774
 */
775
function scorm_reset_course_form_definition(&$mform) {
776
    $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
1441 ariadna 777
    $mform->addElement('static', 'scormdelete', get_string('delete'));
1 efrain 778
    $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
779
}
780
 
781
/**
782
 * Course reset form defaults.
783
 *
784
 * @return array
785
 */
786
function scorm_reset_course_form_defaults($course) {
787
    return array('reset_scorm' => 1);
788
}
789
 
790
/**
791
 * Removes all grades from gradebook
792
 *
793
 * @global stdClass
794
 * @global object
795
 * @param int $courseid
796
 * @param string optional type
797
 */
798
function scorm_reset_gradebook($courseid, $type='') {
799
    global $CFG, $DB;
800
 
801
    $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
802
              FROM {scorm} s, {course_modules} cm, {modules} m
803
             WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
804
 
805
    if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
806
        foreach ($scorms as $scorm) {
807
            scorm_grade_item_update($scorm, 'reset');
808
        }
809
    }
810
}
811
 
812
/**
813
 * Actual implementation of the reset course functionality, delete all the
814
 * scorm attempts for course $data->courseid.
815
 *
816
 * @global stdClass
817
 * @global object
818
 * @param object $data the data submitted from the reset course.
819
 * @return array status array
820
 */
821
function scorm_reset_userdata($data) {
822
    global $DB, $CFG;
823
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
824
 
825
    $componentstr = get_string('modulenameplural', 'scorm');
826
    $status = [];
827
 
828
    if (!empty($data->reset_scorm)) {
829
 
830
        $scorms = $DB->get_recordset('scorm', ['course' => $data->courseid]);
831
        foreach ($scorms as $scorm) {
832
            scorm_delete_tracks($scorm->id);
833
        }
834
        $scorms->close();
835
 
836
        // Remove all grades from gradebook.
837
        if (empty($data->reset_gradebook_grades)) {
838
            scorm_reset_gradebook($data->courseid);
839
        }
840
 
841
        $status[] = ['component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false];
842
    }
843
 
844
    // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
845
    // See MDL-9367.
846
    shift_course_mod_dates('scorm', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
1441 ariadna 847
    $status[] = ['component' => $componentstr, 'item' => get_string('date'), 'error' => false];
1 efrain 848
 
849
    return $status;
850
}
851
 
852
/**
853
 * Lists all file areas current user may browse
854
 *
855
 * @param object $course
856
 * @param object $cm
857
 * @param object $context
858
 * @return array
859
 */
860
function scorm_get_file_areas($course, $cm, $context) {
861
    $areas = array();
862
    $areas['content'] = get_string('areacontent', 'scorm');
863
    $areas['package'] = get_string('areapackage', 'scorm');
864
    return $areas;
865
}
866
 
867
/**
868
 * File browsing support for SCORM file areas
869
 *
870
 * @package  mod_scorm
871
 * @category files
872
 * @param file_browser $browser file browser instance
873
 * @param array $areas file areas
874
 * @param stdClass $course course object
875
 * @param stdClass $cm course module object
876
 * @param stdClass $context context object
877
 * @param string $filearea file area
878
 * @param int $itemid item ID
879
 * @param string $filepath file path
880
 * @param string $filename file name
881
 * @return file_info instance or null if not found
882
 */
883
function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
884
    global $CFG;
885
 
886
    if (!has_capability('moodle/course:managefiles', $context)) {
887
        return null;
888
    }
889
 
890
    // No writing for now!
891
 
892
    $fs = get_file_storage();
893
 
894
    if ($filearea === 'content') {
895
 
896
        $filepath = is_null($filepath) ? '/' : $filepath;
897
        $filename = is_null($filename) ? '.' : $filename;
898
 
899
        $urlbase = $CFG->wwwroot.'/pluginfile.php';
900
        if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
901
            if ($filepath === '/' and $filename === '.') {
902
                $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
903
            } else {
904
                // Not found.
905
                return null;
906
            }
907
        }
908
        require_once("$CFG->dirroot/mod/scorm/locallib.php");
909
        return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
910
 
911
    } else if ($filearea === 'package') {
912
        $filepath = is_null($filepath) ? '/' : $filepath;
913
        $filename = is_null($filename) ? '.' : $filename;
914
 
915
        $urlbase = $CFG->wwwroot.'/pluginfile.php';
916
        if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
917
            if ($filepath === '/' and $filename === '.') {
918
                $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
919
            } else {
920
                // Not found.
921
                return null;
922
            }
923
        }
924
        return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
925
    }
926
 
927
    // Scorm_intro handled in file_browser.
928
 
929
    return false;
930
}
931
 
932
/**
933
 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
934
 *
935
 * @package  mod_scorm
936
 * @category files
937
 * @param stdClass $course course object
938
 * @param stdClass $cm course module object
939
 * @param stdClass $context context object
940
 * @param string $filearea file area
941
 * @param array $args extra arguments
942
 * @param bool $forcedownload whether or not force download
943
 * @param array $options additional options affecting the file serving
944
 * @return bool false if file not found, does not return if found - just send the file
945
 */
946
function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
947
    global $CFG, $DB;
948
 
949
    if ($context->contextlevel != CONTEXT_MODULE) {
950
        return false;
951
    }
952
 
953
    require_login($course, true, $cm);
954
 
955
    $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
956
    $lifetime = null;
957
 
958
    // Check SCORM availability.
959
    if (!$canmanageactivity) {
960
        require_once($CFG->dirroot.'/mod/scorm/locallib.php');
961
 
962
        $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
963
        list($available, $warnings) = scorm_get_availability_status($scorm);
964
        if (!$available) {
965
            return false;
966
        }
967
    }
968
 
969
    if ($filearea === 'content') {
970
        $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
971
        $relativepath = implode('/', $args);
972
        $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
973
        $options['immutable'] = true; // Add immutable option, $relativepath changes on file update.
974
 
975
    } else if ($filearea === 'package') {
976
        // Check if the global setting for disabling package downloads is enabled.
977
        $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
978
        if ($protectpackagedownloads and !$canmanageactivity) {
979
            return false;
980
        }
981
        $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
982
        $relativepath = implode('/', $args);
983
        $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
984
        $lifetime = 0; // No caching here.
985
 
986
    } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
987
        $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
988
        $relativepath = implode('/', $args);
989
 
990
        // Get imsmanifest file.
991
        $fs = get_file_storage();
992
        $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
993
        $file = reset($files);
994
 
995
        // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
996
        $packagefilename = $file->get_filename();
997
        if (strtolower($packagefilename) !== 'imsmanifest.xml') {
998
            return false;
999
        }
1000
 
1001
        $file->send_relative_file($relativepath);
1002
    } else {
1003
        return false;
1004
    }
1005
 
1006
    $fs = get_file_storage();
1007
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1008
        if ($filearea === 'content') { // Return file not found straight away to improve performance.
1009
            send_header_404();
1010
            die;
1011
        }
1012
        return false;
1013
    }
1014
 
1015
    // Allow SVG files to be loaded within SCORM content, instead of forcing download.
1016
    $options['dontforcesvgdownload'] = true;
1017
 
1018
    // Finally send the file.
1019
    send_stored_file($file, $lifetime, 0, false, $options);
1020
}
1021
 
1022
/**
1023
 * @uses FEATURE_GROUPS
1024
 * @uses FEATURE_GROUPINGS
1025
 * @uses FEATURE_MOD_INTRO
1026
 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1027
 * @uses FEATURE_COMPLETION_HAS_RULES
1028
 * @uses FEATURE_GRADE_HAS_GRADE
1029
 * @uses FEATURE_GRADE_OUTCOMES
1030
 * @param string $feature FEATURE_xx constant for requested feature
1031
 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1032
 */
1033
function scorm_supports($feature) {
1034
    switch($feature) {
1035
        case FEATURE_GROUPS:                  return true;
1036
        case FEATURE_GROUPINGS:               return true;
1037
        case FEATURE_MOD_INTRO:               return true;
1038
        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1039
        case FEATURE_COMPLETION_HAS_RULES:    return true;
1040
        case FEATURE_GRADE_HAS_GRADE:         return true;
1041
        case FEATURE_GRADE_OUTCOMES:          return true;
1042
        case FEATURE_BACKUP_MOODLE2:          return true;
1043
        case FEATURE_SHOW_DESCRIPTION:        return true;
1044
        case FEATURE_MOD_PURPOSE:
1045
            return MOD_PURPOSE_INTERACTIVECONTENT;
1046
 
1047
        default: return null;
1048
    }
1049
}
1050
 
1051
/**
1052
 * Get the filename for a temp log file
1053
 *
1054
 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1055
 * @param integer $scoid - scoid of object this log entry is for
1056
 * @return string The filename as an absolute path
1057
 */
1058
function scorm_debug_log_filename($type, $scoid) {
1059
    global $CFG, $USER;
1060
 
1061
    $logpath = $CFG->tempdir.'/scormlogs';
1062
    $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1063
    return $logfile;
1064
}
1065
 
1066
/**
1067
 * writes log output to a temp log file
1068
 *
1069
 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1070
 * @param string $text - text to be written to file.
1071
 * @param integer $scoid - scoid of object this log entry is for.
1072
 */
1073
function scorm_debug_log_write($type, $text, $scoid) {
1074
    global $CFG;
1075
 
1076
    $debugenablelog = get_config('scorm', 'allowapidebug');
1077
    if (!$debugenablelog || empty($text)) {
1078
        return;
1079
    }
1080
    if (make_temp_directory('scormlogs/')) {
1081
        $logfile = scorm_debug_log_filename($type, $scoid);
1082
        @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1083
        @chmod($logfile, $CFG->filepermissions);
1084
    }
1085
}
1086
 
1087
/**
1088
 * Remove debug log file
1089
 *
1090
 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1091
 * @param integer $scoid - scoid of object this log entry is for
1092
 * @return boolean True if the file is successfully deleted, false otherwise
1093
 */
1094
function scorm_debug_log_remove($type, $scoid) {
1095
 
1096
    $debugenablelog = get_config('scorm', 'allowapidebug');
1097
    $logfile = scorm_debug_log_filename($type, $scoid);
1098
    if (!$debugenablelog || !file_exists($logfile)) {
1099
        return false;
1100
    }
1101
 
1102
    return @unlink($logfile);
1103
}
1104
 
1105
/**
1106
 * Return a list of page types
1107
 * @param string $pagetype current page type
1108
 * @param stdClass $parentcontext Block's parent context
1109
 * @param stdClass $currentcontext Current context of block
1110
 */
1111
function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1112
    $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1113
    return $modulepagetype;
1114
}
1115
 
1116
/**
1117
 * Returns the SCORM version used.
1118
 * @param string $scormversion comes from $scorm->version
1119
 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1120
 * @return Scorm version.
1121
 */
1122
function scorm_version_check($scormversion, $version='') {
1123
    $scormversion = trim(strtolower($scormversion));
1124
    if (empty($version) || $version == SCORM_12) {
1125
        if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1126
            return SCORM_12;
1127
        }
1128
        if (!empty($version)) {
1129
            return false;
1130
        }
1131
    }
1132
    if (empty($version) || $version == SCORM_13) {
1133
        if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1134
            return SCORM_13;
1135
        }
1136
        if (!empty($version)) {
1137
            return false;
1138
        }
1139
    }
1140
    if (empty($version) || $version == SCORM_AICC) {
1141
        if (strpos($scormversion, 'aicc')) {
1142
            return SCORM_AICC;
1143
        }
1144
        if (!empty($version)) {
1145
            return false;
1146
        }
1147
    }
1148
    return false;
1149
}
1150
 
1151
/**
1152
 * Register the ability to handle drag and drop file uploads
1153
 * @return array containing details of the files / types the mod can handle
1154
 */
1155
function scorm_dndupload_register() {
1156
    return array('files' => array(
1157
        array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1158
    ));
1159
}
1160
 
1161
/**
1162
 * Handle a file that has been uploaded
1163
 * @param object $uploadinfo details of the file / content that has been uploaded
1164
 * @return int instance id of the newly created mod
1165
 */
1166
function scorm_dndupload_handle($uploadinfo) {
1167
 
1168
    $context = context_module::instance($uploadinfo->coursemodule);
1169
    file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1170
    $fs = get_file_storage();
1171
    $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1172
    $file = reset($files);
1173
 
1174
    // Validate the file, make sure it's a valid SCORM package!
1175
    $errors = scorm_validate_package($file);
1176
    if (!empty($errors)) {
1177
        return false;
1178
    }
1179
    // Create a default scorm object to pass to scorm_add_instance()!
1180
    $scorm = get_config('scorm');
1181
    $scorm->course = $uploadinfo->course->id;
1182
    $scorm->coursemodule = $uploadinfo->coursemodule;
1183
    $scorm->cmidnumber = '';
1184
    $scorm->name = $uploadinfo->displayname;
1185
    $scorm->scormtype = SCORM_TYPE_LOCAL;
1186
    $scorm->reference = $file->get_filename();
1187
    $scorm->intro = '';
1188
    $scorm->width = $scorm->framewidth;
1189
    $scorm->height = $scorm->frameheight;
1190
 
1191
    return scorm_add_instance($scorm, null);
1192
}
1193
 
1194
/**
1195
 * Sets activity completion state
1196
 *
1197
 * @param object $scorm object
1198
 * @param int $userid User ID
1199
 * @param int $completionstate Completion state
1200
 * @param array $grades grades array of users with grades - used when $userid = 0
1201
 */
1202
function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1203
    $course = new stdClass();
1204
    $course->id = $scorm->course;
1205
    $completion = new completion_info($course);
1206
 
1207
    // Check if completion is enabled site-wide, or for the course.
1208
    if (!$completion->is_enabled()) {
1209
        return;
1210
    }
1211
 
1212
    $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1213
    if (empty($cm) || !$completion->is_enabled($cm)) {
1214
            return;
1215
    }
1216
 
1217
    if (empty($userid)) { // We need to get all the relevant users from $grades param.
1218
        foreach ($grades as $grade) {
1219
            $completion->update_state($cm, $completionstate, $grade->userid);
1220
        }
1221
    } else {
1222
        $completion->update_state($cm, $completionstate, $userid);
1223
    }
1224
}
1225
 
1226
/**
1227
 * Check that a Zip file contains a valid SCORM package
1228
 *
1229
 * @param $file stored_file a Zip file.
1230
 * @return array empty if no issue is found. Array of error message otherwise
1231
 */
1232
function scorm_validate_package($file) {
1233
    $packer = get_file_packer('application/zip');
1234
    $errors = array();
1235
    if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1236
        $file->import_external_file_contents();
1237
    }
1238
    $filelist = $file->list_files($packer);
1239
 
1240
    if (!is_array($filelist)) {
1241
        $errors['packagefile'] = get_string('badarchive', 'scorm');
1242
    } else {
1243
        $aiccfound = false;
1244
        $badmanifestpresent = false;
1245
        foreach ($filelist as $info) {
1246
            if ($info->pathname == 'imsmanifest.xml') {
1247
                return array();
1248
            } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1249
                // This package has an imsmanifest file inside a folder of the package.
1250
                $badmanifestpresent = true;
1251
            }
1252
            if (preg_match('/\.cst$/', $info->pathname)) {
1253
                return array();
1254
            }
1255
        }
1256
        if (!$aiccfound) {
1257
            if ($badmanifestpresent) {
1258
                $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1259
            } else {
1260
                $errors['packagefile'] = get_string('nomanifest', 'scorm');
1261
            }
1262
        }
1263
    }
1264
    return $errors;
1265
}
1266
 
1267
/**
1268
 * Check and set the correct mode and attempt when entering a SCORM package.
1269
 *
1270
 * @param object $scorm object
1271
 * @param string $newattempt should a new attempt be generated here.
1272
 * @param int $attempt the attempt number this is for.
1273
 * @param int $userid the userid of the user.
1274
 * @param string $mode the current mode that has been selected.
1275
 */
1276
function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1277
    global $DB;
1278
 
1279
    if (($mode == 'browse')) {
1280
        if ($scorm->hidebrowse == 1) {
1281
            // Prevent Browse mode if hidebrowse is set.
1282
            $mode = 'normal';
1283
        } else {
1284
            // We don't need to check attempts as browse mode is set.
1285
            return;
1286
        }
1287
    }
1288
 
1289
    if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS) {
1290
        // This SCORM is configured to force a new attempt on every re-entry.
1291
        $newattempt = 'on';
1292
        $mode = 'normal';
1293
        if ($attempt == 1) {
1294
            // Check if the user has any existing data or if this is really the first attempt.
1295
            $exists = $DB->record_exists('scorm_attempt', ['userid' => $userid, 'scormid' => $scorm->id]);
1296
            if (!$exists) {
1297
                // No records yet - Attempt should == 1.
1298
                return;
1299
            }
1300
        }
1301
        $attempt++;
1302
 
1303
        return;
1304
    }
1305
    // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1306
    $incomplete = true;
1307
 
1308
    // Note - in SCORM_13 the cmi-core.lesson_status field was split into
1309
    // 'cmi.completion_status' and 'cmi.success_status'.
1310
    // 'cmi.completion_status' can only contain values 'completed', 'incomplete', 'not attempted' or 'unknown'.
1311
    // This means the values 'passed' or 'failed' will never be reported for a track in SCORM_13 and
1312
    // the only status that will be treated as complete is 'completed'.
1313
 
1314
    $completionelements = array(
1315
        SCORM_12 => 'cmi.core.lesson_status',
1316
        SCORM_13 => 'cmi.completion_status',
1317
        SCORM_AICC => 'cmi.core.lesson_status'
1318
    );
1319
    $scormversion = scorm_version_check($scorm->version);
1320
    if($scormversion===false) {
1321
        $scormversion = SCORM_12;
1322
    }
1323
    $completionelement = $completionelements[$scormversion];
1324
 
1325
    $sql = "SELECT sc.id, sub.value
1326
              FROM {scorm_scoes} sc
1327
         LEFT JOIN (SELECT v.scoid, v.value
1328
                      FROM {scorm_attempt} a
1329
                      JOIN {scorm_scoes_value} v ON a.id = v.attemptid
1330
                      JOIN {scorm_element} e on e.id = v.elementid AND e.element = :element
1331
                     WHERE a.userid = :userid AND a.attempt = :attempt AND a.scormid = :scormid) sub ON sub.scoid = sc.id
1332
             WHERE sc.scormtype = 'sco' AND sc.scorm = :scormid2";
1333
    $tracks = $DB->get_recordset_sql($sql, ['userid' => $userid, 'attempt' => $attempt,
1334
                                            'element' => $completionelement, 'scormid' => $scorm->id,
1335
                                            'scormid2' => $scorm->id]);
1336
 
1337
    foreach ($tracks as $track) {
1338
        if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1339
            $incomplete = false;
1340
        } else {
1341
            $incomplete = true;
1342
            break; // Found an incomplete sco, so the result as a whole is incomplete.
1343
        }
1344
    }
1345
    $tracks->close();
1346
 
1347
    // Validate user request to start a new attempt.
1348
    if ($incomplete === true) {
1349
        // The option to start a new attempt should never have been presented. Force false.
1350
        $newattempt = 'off';
1351
    } else if (!empty($scorm->forcenewattempt)) {
1352
        // A new attempt should be forced for already completed attempts.
1353
        $newattempt = 'on';
1354
    }
1355
 
1356
    if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1357
        $attempt++;
1358
        $mode = 'normal';
1359
    } else { // Check if review mode should be set.
1360
        if ($incomplete === true) {
1361
            $mode = 'normal';
1362
        } else {
1363
            $mode = 'review';
1364
        }
1365
    }
1366
}
1367
 
1368
/**
1369
 * Trigger the course_module_viewed event.
1370
 *
1371
 * @param  stdClass $scorm        scorm object
1372
 * @param  stdClass $course     course object
1373
 * @param  stdClass $cm         course module object
1374
 * @param  stdClass $context    context object
1375
 * @since Moodle 3.0
1376
 */
1377
function scorm_view($scorm, $course, $cm, $context) {
1378
 
1379
    // Trigger course_module_viewed event.
1380
    $params = array(
1381
        'context' => $context,
1382
        'objectid' => $scorm->id
1383
    );
1384
 
1385
    $event = \mod_scorm\event\course_module_viewed::create($params);
1386
    $event->add_record_snapshot('course_modules', $cm);
1387
    $event->add_record_snapshot('course', $course);
1388
    $event->add_record_snapshot('scorm', $scorm);
1389
    $event->trigger();
1390
}
1391
 
1392
/**
1393
 * Check if the module has any update that affects the current user since a given time.
1394
 *
1395
 * @param  cm_info $cm course module data
1396
 * @param  int $from the time to check updates from
1397
 * @param  array $filter  if we need to check only specific updates
1398
 * @return stdClass an object with the different type of areas indicating if they were updated or not
1399
 * @since Moodle 3.2
1400
 */
1401
function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1402
    global $DB, $USER, $CFG;
1403
    require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1404
 
1405
    $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1406
    $updates = new stdClass();
1407
    list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1408
    if (!$available) {
1409
        return $updates;
1410
    }
1411
    $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1412
 
1413
    $updates->tracks = (object) array('updated' => false);
1414
    $sql = "SELECT v.id
1415
              FROM {scorm_scoes_value} v
1416
              JOIN {scorm_attempt} a ON a.id = v.attemptid
1417
             WHERE a.scormid = :scormid AND v.timemodified > :timemodified";
1418
    $params = ['scormid' => $scorm->id, 'timemodified' => $from, 'userid' => $USER->id];
1419
    $tracks = $DB->get_records_sql($sql ." AND a.userid = :userid", $params);
1420
    if (!empty($tracks)) {
1421
        $updates->tracks->updated = true;
1422
        $updates->tracks->itemids = array_keys($tracks);
1423
    }
1424
 
1425
    // Now, teachers should see other students updates.
1426
    if (has_capability('mod/scorm:viewreport', $cm->context)) {
1427
        $params = ['scormid' => $scorm->id, 'timemodified' => $from];
1428
 
1429
        if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1430
            $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1431
            if (empty($groupusers)) {
1432
                return $updates;
1433
            }
1434
            list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1435
            $sql .= ' AND userid ' . $insql;
1436
            $params = array_merge($params, $inparams);
1437
        }
1438
 
1439
        $updates->usertracks = (object) array('updated' => false);
1440
 
1441
        $tracks = $DB->get_records_sql($sql, $params);
1442
        if (!empty($tracks)) {
1443
            $updates->usertracks->updated = true;
1444
            $updates->usertracks->itemids = array_keys($tracks);
1445
        }
1446
    }
1447
    return $updates;
1448
}
1449
 
1450
/**
1451
 * Get icon mapping for font-awesome.
1452
 */
1453
function mod_scorm_get_fontawesome_icon_map() {
1454
    return [
1441 ariadna 1455
        'mod_scorm:asset' => 'fa-regular fa-file-zipper',
1456
        'mod_scorm:assetc' => 'fa-regular fa-file-zipper',
1457
        'mod_scorm:completed' => 'fa-regular fa-square-check',
1458
        'mod_scorm:failed' => 'fa-xmark',
1459
        'mod_scorm:incomplete' => 'fa-regular fa-pen-to-square',
1 efrain 1460
        'mod_scorm:minus' => 'fa-minus',
1441 ariadna 1461
        'mod_scorm:notattempted' => 'fa-regular fa-square',
1 efrain 1462
        'mod_scorm:passed' => 'fa-check',
1463
        'mod_scorm:plus' => 'fa-plus',
1441 ariadna 1464
        'mod_scorm:popdown' => 'fa-regular fa-rectangle-xmark',
1465
        'mod_scorm:popup' => 'fa-regular fa-window-restore',
1 efrain 1466
        'mod_scorm:suspend' => 'fa-pause',
1441 ariadna 1467
        'mod_scorm:wait' => 'fa-spinner fa-spin',
1 efrain 1468
    ];
1469
}
1470
 
1471
/**
1472
 * This standard function will check all instances of this module
1473
 * and make sure there are up-to-date events created for each of them.
1474
 * If courseid = 0, then every scorm event in the site is checked, else
1475
 * only scorm events belonging to the course specified are checked.
1476
 *
1477
 * @param int $courseid
1478
 * @param int|stdClass $instance scorm module instance or ID.
1479
 * @param int|stdClass $cm Course module object or ID.
1480
 * @return bool
1481
 */
1482
function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1483
    global $CFG, $DB;
1484
 
1485
    require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1486
 
1487
    // If we have instance information then we can just update the one event instead of updating all events.
1488
    if (isset($instance)) {
1489
        if (!is_object($instance)) {
1490
            $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1491
        }
1492
        if (isset($cm)) {
1493
            if (!is_object($cm)) {
1494
                $cm = (object)array('id' => $cm);
1495
            }
1496
        } else {
1497
            $cm = get_coursemodule_from_instance('scorm', $instance->id);
1498
        }
1499
        scorm_update_calendar($instance, $cm->id);
1500
        return true;
1501
    }
1502
 
1503
    if ($courseid) {
1504
        // Make sure that the course id is numeric.
1505
        if (!is_numeric($courseid)) {
1506
            return false;
1507
        }
1508
        if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1509
            return false;
1510
        }
1511
    } else {
1512
        if (!$scorms = $DB->get_records('scorm')) {
1513
            return false;
1514
        }
1515
    }
1516
 
1517
    foreach ($scorms as $scorm) {
1518
        $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1519
        scorm_update_calendar($scorm, $cm->id);
1520
    }
1521
 
1522
    return true;
1523
}
1524
 
1525
/**
1526
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1527
 *
1528
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1529
 * is not displayed on the block.
1530
 *
1531
 * @param calendar_event $event
1532
 * @param \core_calendar\action_factory $factory
1533
 * @param int $userid User id override
1534
 * @return \core_calendar\local\event\entities\action_interface|null
1535
 */
1536
function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1537
                                                      \core_calendar\action_factory $factory, $userid = null) {
1538
    global $CFG, $USER;
1539
 
1540
    require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1541
 
1542
    if (empty($userid)) {
1543
        $userid = $USER->id;
1544
    }
1545
 
1546
    $cm = get_fast_modinfo($event->courseid, $userid)->instances['scorm'][$event->instance];
1547
 
1548
    if (has_capability('mod/scorm:viewreport', $cm->context, $userid)) {
1549
        // Teachers do not need to be reminded to complete a scorm.
1550
        return null;
1551
    }
1552
 
1553
    $completion = new \completion_info($cm->get_course());
1554
 
1555
    $completiondata = $completion->get_data($cm, false, $userid);
1556
 
1557
    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1558
        return null;
1559
    }
1560
 
1561
    if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1562
        // The scorm has closed so the user can no longer submit anything.
1563
        return null;
1564
    }
1565
 
1566
    // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1567
    $customdata = $cm->customdata ?: [];
1568
    $customdata['id'] = $cm->instance;
1569
    $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1570
 
1571
    // Check that the SCORM activity is open.
1572
    list($actionable, $warnings) = scorm_get_availability_status($scorm, false, null, $userid);
1573
 
1574
    return $factory->create_instance(
1575
        get_string('enter', 'scorm'),
1576
        new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1577
        1,
1578
        $actionable
1579
    );
1580
}
1581
 
1582
/**
1583
 * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1584
 * for the course (see resource).
1585
 *
1586
 * Given a course_module object, this function returns any "extra" information that may be needed
1587
 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1588
 *
1589
 * @param stdClass $coursemodule The coursemodule object (record).
1590
 * @return cached_cm_info An object on information that the courses
1591
 *                        will know about (most noticeably, an icon).
1592
 */
1593
function scorm_get_coursemodule_info($coursemodule) {
1594
    global $DB;
1595
 
1596
    $dbparams = ['id' => $coursemodule->instance];
1597
    $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1598
        'timeopen, timeclose';
1599
    if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1600
        return false;
1601
    }
1602
 
1603
    $result = new cached_cm_info();
1604
    $result->name = $scorm->name;
1605
 
1606
    if ($coursemodule->showdescription) {
1607
        // Convert intro to html. Do not filter cached version, filters run at display time.
1608
        $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1609
    }
1610
 
1611
    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1612
    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1613
        $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1614
        $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1615
        $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1616
    }
1617
    // Populate some other values that can be used in calendar or on dashboard.
1618
    if ($scorm->timeopen) {
1619
        $result->customdata['timeopen'] = $scorm->timeopen;
1620
    }
1621
    if ($scorm->timeclose) {
1622
        $result->customdata['timeclose'] = $scorm->timeclose;
1623
    }
1624
 
1625
    return $result;
1626
}
1627
 
1628
/**
1629
 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1630
 *
1631
 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1632
 * @return array $descriptions the array of descriptions for the custom rules.
1633
 */
1634
function mod_scorm_get_completion_active_rule_descriptions($cm) {
1635
    // Values will be present in cm_info, and we assume these are up to date.
1636
    if (empty($cm->customdata['customcompletionrules'])
1637
        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1638
        return [];
1639
    }
1640
 
1641
    $descriptions = [];
1642
    foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1643
        switch ($key) {
1644
            case 'completionstatusrequired':
1645
                if (!is_null($val)) {
1646
                    // Determine the selected statuses using a bitwise operation.
1647
                    $cvalues = array();
1648
                    foreach (scorm_status_options(true) as $bit => $string) {
1649
                        if (($val & $bit) == $bit) {
1650
                            $cvalues[] = $string;
1651
                        }
1652
                    }
1653
                    $statusstring = implode(', ', $cvalues);
1654
                    $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1655
                }
1656
                break;
1657
            case 'completionscorerequired':
1658
                if (!is_null($val)) {
1659
                    $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1660
                }
1661
                break;
1662
            case 'completionstatusallscos':
1663
                if (!empty($val)) {
1664
                    $descriptions[] = get_string('completionstatusallscos', 'scorm');
1665
                }
1666
                break;
1667
            default:
1668
                break;
1669
        }
1670
    }
1671
    return $descriptions;
1672
}
1673
 
1674
/**
1675
 * This function will update the scorm module according to the
1676
 * event that has been modified.
1677
 *
1678
 * It will set the timeopen or timeclose value of the scorm instance
1679
 * according to the type of event provided.
1680
 *
1681
 * @throws \moodle_exception
1682
 * @param \calendar_event $event
1683
 * @param stdClass $scorm The module instance to get the range from
1684
 */
1685
function mod_scorm_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $scorm) {
1686
    global $DB;
1687
 
1688
    if (empty($event->instance) || $event->modulename != 'scorm') {
1689
        return;
1690
    }
1691
 
1692
    if ($event->instance != $scorm->id) {
1693
        return;
1694
    }
1695
 
1696
    if (!in_array($event->eventtype, [SCORM_EVENT_TYPE_OPEN, SCORM_EVENT_TYPE_CLOSE])) {
1697
        return;
1698
    }
1699
 
1700
    $courseid = $event->courseid;
1701
    $modulename = $event->modulename;
1702
    $instanceid = $event->instance;
1703
    $modified = false;
1704
 
1705
    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1706
    $context = context_module::instance($coursemodule->id);
1707
 
1708
    // The user does not have the capability to modify this activity.
1709
    if (!has_capability('moodle/course:manageactivities', $context)) {
1710
        return;
1711
    }
1712
 
1713
    if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1714
        // If the event is for the scorm activity opening then we should
1715
        // set the start time of the scorm activity to be the new start
1716
        // time of the event.
1717
        if ($scorm->timeopen != $event->timestart) {
1718
            $scorm->timeopen = $event->timestart;
1719
            $scorm->timemodified = time();
1720
            $modified = true;
1721
        }
1722
    } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1723
        // If the event is for the scorm activity closing then we should
1724
        // set the end time of the scorm activity to be the new start
1725
        // time of the event.
1726
        if ($scorm->timeclose != $event->timestart) {
1727
            $scorm->timeclose = $event->timestart;
1728
            $modified = true;
1729
        }
1730
    }
1731
 
1732
    if ($modified) {
1733
        $scorm->timemodified = time();
1734
        $DB->update_record('scorm', $scorm);
1735
        $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1736
        $event->trigger();
1737
    }
1738
}
1739
 
1740
/**
1741
 * This function calculates the minimum and maximum cutoff values for the timestart of
1742
 * the given event.
1743
 *
1744
 * It will return an array with two values, the first being the minimum cutoff value and
1745
 * the second being the maximum cutoff value. Either or both values can be null, which
1746
 * indicates there is no minimum or maximum, respectively.
1747
 *
1748
 * If a cutoff is required then the function must return an array containing the cutoff
1749
 * timestamp and error string to display to the user if the cutoff value is violated.
1750
 *
1751
 * A minimum and maximum cutoff return value will look like:
1752
 * [
1753
 *     [1505704373, 'The date must be after this date'],
1754
 *     [1506741172, 'The date must be before this date']
1755
 * ]
1756
 *
1757
 * @param \calendar_event $event The calendar event to get the time range for
1758
 * @param \stdClass $instance The module instance to get the range from
1759
 * @return array Returns an array with min and max date.
1760
 */
1761
function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1762
    $mindate = null;
1763
    $maxdate = null;
1764
 
1765
    if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1766
        // The start time of the open event can't be equal to or after the
1767
        // close time of the scorm activity.
1768
        if (!empty($instance->timeclose)) {
1769
            $maxdate = [
1770
                $instance->timeclose,
1771
                get_string('openafterclose', 'scorm')
1772
            ];
1773
        }
1774
    } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1775
        // The start time of the close event can't be equal to or earlier than the
1776
        // open time of the scorm activity.
1777
        if (!empty($instance->timeopen)) {
1778
            $mindate = [
1779
                $instance->timeopen,
1780
                get_string('closebeforeopen', 'scorm')
1781
            ];
1782
        }
1783
    }
1784
 
1785
    return [$mindate, $maxdate];
1786
}
1787
 
1788
/**
1789
 * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1790
 *
1791
 * @param  string $filearea The filearea.
1792
 * @param  array  $args The path (the part after the filearea and before the filename).
1793
 * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1794
 */
1795
function mod_scorm_get_path_from_pluginfile(string $filearea, array $args): array {
1796
    // SCORM never has an itemid (the number represents the revision but it's not stored in database).
1797
    array_shift($args);
1798
 
1799
    // Get the filepath.
1800
    if (empty($args)) {
1801
        $filepath = '/';
1802
    } else {
1803
        $filepath = '/' . implode('/', $args) . '/';
1804
    }
1805
 
1806
    return [
1807
        'itemid' => 0,
1808
        'filepath' => $filepath,
1809
    ];
1810
}
1811
 
1812
/**
1813
 * Callback to fetch the activity event type lang string.
1814
 *
1815
 * @param string $eventtype The event type.
1816
 * @return lang_string The event type lang string.
1817
 */
1818
function mod_scorm_core_calendar_get_event_action_string(string $eventtype): string {
1819
    $modulename = get_string('modulename', 'scorm');
1820
 
1821
    switch ($eventtype) {
1822
        case SCORM_EVENT_TYPE_OPEN:
1823
            $identifier = 'calendarstart';
1824
            break;
1825
        case SCORM_EVENT_TYPE_CLOSE:
1826
            $identifier = 'calendarend';
1827
            break;
1828
        default:
1829
            return get_string('requiresaction', 'calendar', $modulename);
1830
    }
1831
 
1832
    return get_string($identifier, 'scorm', $modulename);
1833
}
1834
 
1835
/**
1836
 * This function extends the settings navigation block for the site.
1837
 *
1838
 * It is safe to rely on PAGE here as we will only ever be within the module
1839
 * context when this is called
1840
 *
1841
 * @param settings_navigation $settings navigation_node object.
1842
 * @param navigation_node $scormnode navigation_node object.
1843
 * @return void
1844
 */
1845
function scorm_extend_settings_navigation(settings_navigation $settings, navigation_node $scormnode): void {
1846
    if (has_capability('mod/scorm:viewreport', $settings->get_page()->cm->context)) {
1847
        $url = new moodle_url('/mod/scorm/report.php', ['id' => $settings->get_page()->cm->id]);
1848
        $scormnode->add(get_string("reports", "scorm"), $url, navigation_node::TYPE_CUSTOM, null, 'scormreport');
1849
    }
1850
}