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
use mod_quiz\local\access_rule_base;
18
use mod_quiz\quiz_attempt;
19
use quizaccess_seb\seb_access_manager;
20
use quizaccess_seb\seb_quiz_settings;
21
use quizaccess_seb\settings_provider;
22
use quizaccess_seb\event\access_prevented;
23
 
24
/**
25
 * Implementation of the quizaccess_seb plugin.
26
 *
27
 * @package    quizaccess_seb
28
 * @author     Andrew Madden <andrewmadden@catalyst-au.net>
29
 * @author     Dmitrii Metelkin <dmitriim@catalyst-au.net>
30
 * @copyright  2019 Catalyst IT
31
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32
 */
33
class quizaccess_seb extends access_rule_base {
34
 
35
    /** @var seb_access_manager $accessmanager Instance to manage the access to the quiz for this plugin. */
36
    private $accessmanager;
37
 
38
    /**
39
     * Create an instance of this rule for a particular quiz.
40
     *
41
     * @param \mod_quiz\quiz_settings $quizobj information about the quiz in question.
42
     * @param int $timenow the time that should be considered as 'now'.
43
     * @param seb_access_manager $accessmanager the quiz accessmanager.
44
     */
45
    public function __construct(\mod_quiz\quiz_settings $quizobj, int $timenow, seb_access_manager $accessmanager) {
46
        parent::__construct($quizobj, $timenow);
47
        $this->accessmanager = $accessmanager;
48
    }
49
 
50
    /**
51
     * Return an appropriately configured instance of this rule, if it is applicable
52
     * to the given quiz, otherwise return null.
53
     *
54
     * @param \mod_quiz\quiz_settings $quizobj information about the quiz in question.
55
     * @param int $timenow the time that should be considered as 'now'.
56
     * @param bool $canignoretimelimits whether the current user is exempt from
57
     *      time limits by the mod/quiz:ignoretimelimits capability.
58
     * @return access_rule_base|null the rule, if applicable, else null.
59
     */
60
    public static function make(\mod_quiz\quiz_settings $quizobj, $timenow, $canignoretimelimits) {
61
        $accessmanager = new seb_access_manager($quizobj);
62
        // If Safe Exam Browser is not required, this access rule is not applicable.
63
        if (!$accessmanager->seb_required()) {
64
            return null;
65
        }
66
 
67
        return new self($quizobj, $timenow, $accessmanager);
68
    }
69
 
70
    /**
71
     * Add any fields that this rule requires to the quiz settings form. This
72
     * method is called from {@link mod_quiz_mod_form::definition()}, while the
73
     * security section is being built.
74
     *
75
     * @param mod_quiz_mod_form $quizform the quiz settings form that is being built.
76
     * @param MoodleQuickForm $mform the wrapped MoodleQuickForm.
77
     */
78
    public static function add_settings_form_fields(mod_quiz_mod_form $quizform, MoodleQuickForm $mform) {
79
        settings_provider::add_seb_settings_fields($quizform, $mform);
80
    }
81
 
82
    /**
83
     * Validate the data from any form fields added using {@link add_settings_form_fields()}.
84
     *
1441 ariadna 85
     * If the managing user cannot configure SEB by either lack of permissions or locked
86
     * settings, then the form fields will be frozen and no validation will be done.
87
     *
1 efrain 88
     * @param array $errors the errors found so far.
89
     * @param array $data the submitted form data.
90
     * @param array $files information about any uploaded files.
91
     * @param mod_quiz_mod_form $quizform the quiz form object.
92
     * @return array $errors the updated $errors array.
93
     */
94
    public static function validate_settings_form_fields(array $errors,
95
                                                         array $data, $files, mod_quiz_mod_form $quizform): array {
96
 
97
        $quizid = $data['instance'];
98
        $cmid = $data['coursemodule'];
99
        $context = $quizform->get_context();
100
 
101
        if (!settings_provider::can_configure_seb($context)) {
102
            return $errors;
103
        }
104
 
105
        if (settings_provider::is_seb_settings_locked($quizid)) {
106
            return $errors;
107
        }
108
 
109
        if (settings_provider::is_conflicting_permissions($context)) {
110
            return $errors;
111
        }
112
 
113
        $settings = settings_provider::filter_plugin_settings((object) $data);
114
 
115
        // Validate basic settings using persistent class.
116
        $quizsettings = (new seb_quiz_settings())->from_record($settings);
117
        // Set non-form fields.
118
        $quizsettings->set('quizid', $quizid);
119
        $quizsettings->set('cmid', $cmid);
120
        $quizsettings->validate();
121
 
122
        // Add any errors to list.
123
        foreach ($quizsettings->get_errors() as $name => $error) {
124
            $name = settings_provider::add_prefix($name); // Re-add prefix to match form element.
125
            $errors[$name] = $error->out();
126
        }
127
 
128
        // Edge case for filemanager_sebconfig.
129
        if ($quizsettings->get('requiresafeexambrowser') == settings_provider::USE_SEB_UPLOAD_CONFIG) {
130
            $errorvalidatefile = settings_provider::validate_draftarea_configfile($data['filemanager_sebconfigfile']);
131
            if (!empty($errorvalidatefile)) {
132
                $errors['filemanager_sebconfigfile'] = $errorvalidatefile;
133
            }
134
        }
135
 
136
        // Edge case to force user to select a template.
137
        if ($quizsettings->get('requiresafeexambrowser') == settings_provider::USE_SEB_TEMPLATE) {
138
            if (empty($data['seb_templateid'])) {
139
                $errors['seb_templateid'] = get_string('invalidtemplate', 'quizaccess_seb');
140
            }
141
        }
142
 
143
        if ($quizsettings->get('requiresafeexambrowser') != settings_provider::USE_SEB_NO) {
144
            // Global settings may be active which require a quiz password to be set if using SEB.
145
            if (!empty(get_config('quizaccess_seb', 'quizpasswordrequired')) && empty($data['quizpassword'])) {
146
                $errors['quizpassword'] = get_string('passwordnotset', 'quizaccess_seb');
147
            }
148
        }
149
 
150
        return $errors;
151
    }
152
 
153
    /**
154
     * Save any submitted settings when the quiz settings form is submitted. This
155
     * is called from {@link quiz_after_add_or_update()} in lib.php.
156
     *
157
     * @param stdClass $quiz the data from the quiz form, including $quiz->id
158
     *      which is the id of the quiz being saved.
159
     */
160
    public static function save_settings($quiz) {
161
        $context = context_module::instance($quiz->coursemodule);
162
 
163
        if (!settings_provider::can_configure_seb($context)) {
164
            return;
165
        }
166
 
167
        if (settings_provider::is_seb_settings_locked($quiz->id)) {
168
            return;
169
        }
170
 
171
        if (settings_provider::is_conflicting_permissions($context)) {
172
            return;
173
        }
174
 
175
        $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course, false, MUST_EXIST);
176
 
177
        $settings = settings_provider::filter_plugin_settings($quiz);
178
        $settings->quizid = $quiz->id;
179
        $settings->cmid = $cm->id;
180
 
181
        // Get existing settings or create new settings if none exist.
182
        $quizsettings = seb_quiz_settings::get_by_quiz_id($quiz->id);
183
        if (empty($quizsettings)) {
184
            $quizsettings = new seb_quiz_settings(0, $settings);
185
        } else {
186
            $settings->id = $quizsettings->get('id');
187
            $quizsettings->from_record($settings);
188
        }
189
 
190
        // Process uploaded files if required.
191
        if ($quizsettings->get('requiresafeexambrowser') == settings_provider::USE_SEB_UPLOAD_CONFIG) {
192
            $draftitemid = file_get_submitted_draft_itemid('filemanager_sebconfigfile');
193
            settings_provider::save_filemanager_sebconfigfile_draftarea($draftitemid, $cm->id);
194
        } else {
195
            settings_provider::delete_uploaded_config_file($cm->id);
196
        }
197
 
198
        // Save or delete settings.
199
        if ($quizsettings->get('requiresafeexambrowser') != settings_provider::USE_SEB_NO) {
200
            $quizsettings->save();
201
        } else if ($quizsettings->get('id')) {
202
            $quizsettings->delete();
203
        }
204
    }
205
 
206
    /**
207
     * Delete any rule-specific settings when the quiz is deleted. This is called
208
     * from {@link quiz_delete_instance()} in lib.php.
209
     *
210
     * @param stdClass $quiz the data from the database, including $quiz->id
211
     *      which is the id of the quiz being deleted.
212
     */
213
    public static function delete_settings($quiz) {
214
        $quizsettings = seb_quiz_settings::get_by_quiz_id($quiz->id);
215
        // Check that there are existing settings.
216
        if ($quizsettings !== false) {
217
            $quizsettings->delete();
218
        }
219
    }
220
 
221
    /**
222
     * Return the bits of SQL needed to load all the settings from all the access
223
     * plugins in one DB query. The easiest way to understand what you need to do
224
     * here is probably to read the code of {@see \mod_quiz\access_manager::load_settings()}.
225
     *
226
     * If you have some settings that cannot be loaded in this way, then you can
227
     * use the {@link get_extra_settings()} method instead, but that has
228
     * performance implications.
229
     *
230
     * @param int $quizid the id of the quiz we are loading settings for. This
231
     *     can also be accessed as quiz.id in the SQL. (quiz is a table alisas for {quiz}.)
232
     * @return array with three elements:
233
     *     1. fields: any fields to add to the select list. These should be alised
234
     *        if neccessary so that the field name starts the name of the plugin.
235
     *     2. joins: any joins (should probably be LEFT JOINS) with other tables that
236
     *        are needed.
237
     *     3. params: array of placeholder values that are needed by the SQL. You must
238
     *        used named placeholders, and the placeholder names should start with the
239
     *        plugin name, to avoid collisions.
240
     */
241
    public static function get_settings_sql($quizid): array {
242
        return [
243
                'seb.requiresafeexambrowser AS seb_requiresafeexambrowser, '
244
                . 'seb.showsebtaskbar AS seb_showsebtaskbar, '
245
                . 'seb.showwificontrol AS seb_showwificontrol, '
246
                . 'seb.showreloadbutton AS seb_showreloadbutton, '
247
                . 'seb.showtime AS seb_showtime, '
248
                . 'seb.showkeyboardlayout AS seb_showkeyboardlayout, '
249
                . 'seb.allowuserquitseb AS seb_allowuserquitseb, '
250
                . 'seb.quitpassword AS seb_quitpassword, '
251
                . 'seb.linkquitseb AS seb_linkquitseb, '
252
                . 'seb.userconfirmquit AS seb_userconfirmquit, '
253
                . 'seb.enableaudiocontrol AS seb_enableaudiocontrol, '
254
                . 'seb.muteonstartup AS seb_muteonstartup, '
1441 ariadna 255
                . 'seb.allowcapturecamera AS seb_allowcapturecamera, '
256
                . 'seb.allowcapturemicrophone AS seb_allowcapturemicrophone, '
1 efrain 257
                . 'seb.allowspellchecking AS seb_allowspellchecking, '
258
                . 'seb.allowreloadinexam AS seb_allowreloadinexam, '
259
                . 'seb.activateurlfiltering AS seb_activateurlfiltering, '
260
                . 'seb.filterembeddedcontent AS seb_filterembeddedcontent, '
261
                . 'seb.expressionsallowed AS seb_expressionsallowed, '
262
                . 'seb.regexallowed AS seb_regexallowed, '
263
                . 'seb.expressionsblocked AS seb_expressionsblocked, '
264
                . 'seb.regexblocked AS seb_regexblocked, '
265
                . 'seb.allowedbrowserexamkeys AS seb_allowedbrowserexamkeys, '
266
                . 'seb.showsebdownloadlink AS seb_showsebdownloadlink, '
267
                . 'sebtemplate.id AS seb_templateid '
268
                , 'LEFT JOIN {quizaccess_seb_quizsettings} seb ON seb.quizid = quiz.id '
269
                . 'LEFT JOIN {quizaccess_seb_template} sebtemplate ON seb.templateid = sebtemplate.id '
270
                , []
271
        ];
272
    }
273
 
274
    /**
275
     * Whether the user should be blocked from starting a new attempt or continuing
276
     * an attempt now.
277
     *
278
     * @return string false if access should be allowed, a message explaining the
279
     *      reason if access should be prevented.
280
     */
281
    public function prevent_access() {
282
        global $PAGE;
283
 
284
        if (!$this->accessmanager->seb_required()) {
285
            return false;
286
        }
287
 
288
        if ($this->accessmanager->can_bypass_seb()) {
289
            return false;
290
        }
291
 
292
        // If the rule is active, enforce a secure view whilst taking the quiz.
293
        $PAGE->set_pagelayout('secure');
294
        $this->prevent_display_blocks();
295
 
296
        // Access has previously been validated for this session and quiz.
297
        if ($this->accessmanager->validate_session_access()) {
298
            return false;
299
        }
300
 
301
        if (!$this->accessmanager->validate_basic_header()) {
302
            access_prevented::create_strict($this->accessmanager, $this->get_reason_text('not_seb'))->trigger();
303
            return $this->get_require_seb_error_message();
304
        }
305
 
306
        if (!$this->accessmanager->validate_config_key()) {
307
            if ($this->accessmanager->should_redirect_to_seb_config_link()) {
308
                $this->accessmanager->redirect_to_seb_config_link();
309
            }
310
 
311
            access_prevented::create_strict($this->accessmanager, $this->get_reason_text('invalid_config_key'))->trigger();
312
            return $this->get_invalid_key_error_message();
313
        }
314
 
315
        if (!$this->accessmanager->validate_browser_exam_key()) {
316
            access_prevented::create_strict($this->accessmanager, $this->get_reason_text('invalid_browser_key'))->trigger();
317
            return $this->get_invalid_key_error_message();
318
        }
319
 
320
        // Set the state of the access for this Moodle session.
321
        $this->accessmanager->set_session_access(true);
322
 
323
        return false;
324
    }
325
 
326
    /**
327
     * Returns a list of finished attempts for the current user.
328
     *
329
     * @return array
330
     */
331
    private function get_user_finished_attempts(): array {
332
        global $USER;
333
 
334
        return quiz_get_user_attempts(
335
            $this->quizobj->get_quizid(),
336
            $USER->id,
337
            quiz_attempt::FINISHED,
338
            false
339
        );
340
    }
341
 
342
    /**
343
     * Prevent block displaying as configured.
344
     */
345
    private function prevent_display_blocks() {
346
        global $PAGE;
347
 
348
        if ($PAGE->has_set_url() && $PAGE->url == $this->quizobj->view_url()) {
349
            $attempts = $this->get_user_finished_attempts();
350
 
351
            // Don't display blocks before starting an attempt.
352
            if (empty($attempts) && !get_config('quizaccess_seb', 'displayblocksbeforestart')) {
353
                $PAGE->blocks->show_only_fake_blocks();
354
            }
355
 
356
            // Don't display blocks after finishing an attempt.
357
            if (!empty($attempts) && !get_config('quizaccess_seb', 'displayblockswhenfinished')) {
358
                $PAGE->blocks->show_only_fake_blocks();
359
            }
360
        }
361
    }
362
 
363
    /**
364
     * Returns reason for access prevention as a text.
365
     *
366
     * @param string $identifier Reason string identifier.
367
     * @return string
368
     */
369
    private function get_reason_text(string $identifier): string {
370
        if (in_array($identifier, ['not_seb', 'invalid_config_key', 'invalid_browser_key'])) {
371
            return get_string($identifier, 'quizaccess_seb');
372
        }
373
 
374
        return get_string('unknown_reason', 'quizaccess_seb');
375
    }
376
 
377
    /**
378
     * Return error message when a SEB key is not valid.
379
     *
380
     * @return string
381
     */
382
    private function get_invalid_key_error_message(): string {
383
        // Return error message with download link and links to get the seb config.
1441 ariadna 384
        if ($this->accessmanager->is_using_seb()) {
385
            return get_string('invalidkeys', 'quizaccess_seb')
386
                . $this->display_buttons($this->get_action_buttons());
387
        }
388
        return $this->display_buttons($this->get_action_buttons());
1 efrain 389
    }
390
 
391
    /**
392
     * Return error message when a SEB browser is not used.
393
     *
394
     * @return string
395
     */
396
    private function get_require_seb_error_message(): string {
397
        $message = get_string('clientrequiresseb', 'quizaccess_seb');
398
 
399
        if ($this->should_display_download_seb_link()) {
400
            $message .= $this->display_buttons($this->get_download_seb_button());
401
        }
402
 
403
        // Return error message with download link.
404
        return $message;
405
    }
406
 
407
    /**
408
     * Helper function to display an Exit Safe Exam Browser button if configured to do so and attempts are > 0.
409
     *
410
     * @return string empty or a button which has the configured seb quit link.
411
     */
412
    private function get_quit_button(): string {
413
        $quitbutton = '';
414
 
415
        if (empty($this->get_user_finished_attempts())) {
416
            return $quitbutton;
417
        }
418
 
419
        // Only display if the link has been configured and attempts are greater than 0.
420
        if (!empty($this->quiz->seb_linkquitseb)) {
421
            $quitbutton = html_writer::link(
422
                $this->quiz->seb_linkquitseb,
423
                get_string('exitsebbutton', 'quizaccess_seb'),
424
                ['class' => 'btn btn-secondary']
425
            );
426
        }
427
 
428
        return $quitbutton;
429
    }
430
 
431
    /**
432
     * Information, such as might be shown on the quiz view page, relating to this restriction.
433
     * There is no obligation to return anything. If it is not appropriate to tell students
434
     * about this rule, then just return ''.
435
     *
436
     * @return mixed a message, or array of messages, explaining the restriction
437
     *         (may be '' if no message is appropriate).
438
     */
439
    public function description(): array {
440
        global $PAGE;
441
 
442
        $messages = [get_string('sebrequired', 'quizaccess_seb')];
443
 
444
        // Display download SEB config link for those who can bypass using SEB.
445
        if ($this->accessmanager->can_bypass_seb() && $this->accessmanager->should_validate_config_key()) {
446
            $messages[] = $this->display_buttons($this->get_download_config_button());
447
        }
448
 
449
        // Those with higher level access will be able to see the button if they've made an attempt.
450
        if (!$this->prevent_access()) {
451
            $messages[] = $this->display_buttons($this->get_quit_button());
452
        } else {
453
            $PAGE->requires->js_call_amd('quizaccess_seb/validate_quiz_access', 'init',
454
                [$this->quiz->cmid, (bool)get_config('quizaccess_seb', 'autoreconfigureseb')]);
455
        }
456
 
457
        return $messages;
458
    }
459
 
460
    /**
461
     * Sets up the attempt (review or summary) page with any special extra
462
     * properties required by this rule.
463
     *
464
     * @param moodle_page $page the page object to initialise.
465
     */
466
    public function setup_attempt_page($page) {
467
        $page->set_title($this->quizobj->get_course()->shortname . ': ' . $page->title);
468
        $page->set_popup_notification_allowed(false); // Prevent message notifications.
469
        $page->set_heading($page->title);
470
        $page->set_pagelayout('secure');
471
    }
472
 
473
    /**
474
     * This is called when the current attempt at the quiz is finished.
475
     */
476
    public function current_attempt_finished() {
477
        $this->accessmanager->clear_session_access();
478
    }
479
 
480
    /**
481
     * Prepare buttons HTML code for being displayed on the screen.
482
     *
483
     * @param string $buttonshtml Html string of the buttons.
484
     * @param string $class Optional CSS class (or classes as space-separated list)
485
     * @param array $attributes Optional other attributes as array
486
     *
487
     * @return string HTML code of the provided buttons.
488
     */
1441 ariadna 489
    private function display_buttons(string $buttonshtml, $class = '', ?array $attributes = null): string {
1 efrain 490
        $html = '';
491
 
492
        if (!empty($buttonshtml)) {
493
            $html = html_writer::div($buttonshtml, $class, $attributes);
494
        }
495
 
496
        return $html;
497
    }
498
 
499
    /**
500
     * Get buttons to prompt user to download SEB or config file or launch SEB.
501
     *
502
     * @return string Html block of all action buttons.
503
     */
504
    private function get_action_buttons(): string {
505
        $buttons = '';
506
 
507
        if ($this->should_display_download_seb_link()) {
508
            $buttons .= $this->get_download_seb_button();
509
        }
510
 
511
        // Get config for displaying links.
512
        $linkconfig = explode(',', get_config('quizaccess_seb', 'showseblinks'));
513
 
514
        // Display links to download config/launch SEB only if required.
515
        if ($this->accessmanager->should_validate_config_key()) {
516
            if (in_array('seb', $linkconfig)) {
517
                $buttons .= $this->get_launch_seb_button();
518
            }
519
 
520
            if (in_array('http', $linkconfig)) {
521
                $buttons .= $this->get_download_config_button();
522
            }
523
        }
524
 
525
        return $buttons;
526
    }
527
 
528
    /**
529
     * Get a button to download SEB.
530
     *
531
     * @return string A link to download SafeExam Browser.
532
     */
533
    private function get_download_seb_button(): string {
534
        global $OUTPUT;
535
 
536
        $button = '';
537
 
538
        if (!empty($this->get_seb_download_url())) {
1441 ariadna 539
            $sebdownloadlink = $this->get_seb_download_url();
540
            $button = html_writer::start_tag('div', ['class' => 'singlebutton']);
541
            $button .= html_writer::link($sebdownloadlink, get_string('sebdownloadbutton', 'quizaccess_seb'),
542
                ['class' => 'btn btn-secondary', 'target' => '_blank']);
543
            $button .= html_writer::end_tag('div');
544
 
1 efrain 545
        }
546
 
547
        return $button;
548
    }
549
 
550
    /**
551
     * Get a button to launch Safe Exam Browser.
552
     *
553
     * @return string A link to launch Safe Exam Browser.
554
     */
555
    private function get_launch_seb_button(): string {
556
        // Rendering as a href and not as button in a form to circumvent browser warnings for sending to URL with unknown protocol.
557
        $seblink = \quizaccess_seb\link_generator::get_link($this->quiz->cmid, true, is_https());
558
 
559
        $buttonlink = html_writer::start_tag('div', ['class' => 'singlebutton']);
560
        $buttonlink .= html_writer::link($seblink, get_string('seblinkbutton', 'quizaccess_seb'),
561
            ['class' => 'btn btn-secondary', 'title' => get_string('seblinkbutton', 'quizaccess_seb')]);
562
        $buttonlink .= html_writer::end_tag('div');
563
 
564
        return $buttonlink;
565
    }
566
 
567
    /**
568
     * Get a button to download Safe Exam Browser config.
569
     *
570
     * @return string A link to launch Safe Exam Browser.
571
     */
572
    private function get_download_config_button(): string {
573
        // Rendering as a href and not as button in a form to circumvent browser warnings for sending to URL with unknown protocol.
574
        $httplink = \quizaccess_seb\link_generator::get_link($this->quiz->cmid, false, is_https());
575
 
576
        $buttonlink = html_writer::start_tag('div', ['class' => 'singlebutton']);
577
        $buttonlink .= html_writer::link($httplink, get_string('httplinkbutton', 'quizaccess_seb'),
578
            ['class' => 'btn btn-secondary', 'title' => get_string('httplinkbutton', 'quizaccess_seb')]);
579
        $buttonlink .= html_writer::end_tag('div');
580
 
581
        return $buttonlink;
582
    }
583
 
584
    /**
585
     * Returns SEB download URL.
586
     *
587
     * @return string
588
     */
589
    private function get_seb_download_url(): string {
590
        return get_config('quizaccess_seb', 'downloadlink');
591
    }
592
 
593
    /**
594
     * Check if we should display a link to download Safe Exam Browser.
595
     *
596
     * @return bool
597
     */
598
    private function should_display_download_seb_link(): bool {
599
        return !empty($this->quiz->seb_showsebdownloadlink);
600
    }
601
}