Proyectos de Subversion Moodle

Rev

| 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
 * The default questiontype class.
19
 *
20
 * @package    moodlecore
21
 * @subpackage questiontypes
22
 * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
require_once($CFG->dirroot . '/question/engine/lib.php');
30
require_once($CFG->libdir . '/questionlib.php');
31
 
32
 
33
/**
34
 * This is the base class for Moodle question types.
35
 *
36
 * There are detailed comments on each method, explaining what the method is
37
 * for, and the circumstances under which you might need to override it.
38
 *
39
 * Note: the questiontype API should NOT be considered stable yet. Very few
40
 * question types have been produced yet, so we do not yet know all the places
41
 * where the current API is insufficient. I would rather learn from the
42
 * experiences of the first few question type implementors, and improve the
43
 * interface to meet their needs, rather the freeze the API prematurely and
44
 * condem everyone to working round a clunky interface for ever afterwards.
45
 *
46
 * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
47
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48
 */
49
class question_type {
50
    protected $fileoptions = array(
51
        'subdirs' => true,
52
        'maxfiles' => -1,
53
        'maxbytes' => 0,
54
    );
55
 
56
    public function __construct() {
57
    }
58
 
59
    /**
60
     * @return string the name of this question type.
61
     */
62
    public function name() {
63
        return substr(get_class($this), 6);
64
    }
65
 
66
    /**
67
     * @return string the full frankenstyle name for this plugin.
68
     */
69
    public function plugin_name() {
70
        return get_class($this);
71
    }
72
 
73
    /**
74
     * @return string the name of this question type in the user's language.
75
     * You should not need to override this method, the default behaviour should be fine.
76
     */
77
    public function local_name() {
78
        return get_string('pluginname', $this->plugin_name());
79
    }
80
 
81
    /**
82
     * The name this question should appear as in the create new question
83
     * dropdown. Override this method to return false if you don't want your
84
     * question type to be createable, for example if it is an abstract base type,
85
     * otherwise, you should not need to override this method.
86
     *
87
     * @return mixed the desired string, or false to hide this question type in the menu.
88
     */
89
    public function menu_name() {
90
        return $this->local_name();
91
    }
92
 
93
    /**
94
     * @return bool override this to return false if this is not really a
95
     *      question type, for example the description question type is not
96
     *      really a question type.
97
     */
98
    public function is_real_question_type() {
99
        return true;
100
    }
101
 
102
    /**
103
     * @return bool true if this question type sometimes requires manual grading.
104
     */
105
    public function is_manual_graded() {
106
        return false;
107
    }
108
 
109
    /**
110
     * @param object $question a question of this type.
111
     * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt.
112
     * @return bool true if a particular instance of this question requires manual grading.
113
     */
114
    public function is_question_manual_graded($question, $otherquestionsinuse) {
115
        return $this->is_manual_graded();
116
    }
117
 
118
    /**
119
     * @return bool true if this question type can be used by the random question type.
120
     */
121
    public function is_usable_by_random() {
122
        return true;
123
    }
124
 
125
    /**
126
     * Whether this question type can perform a frequency analysis of student
127
     * responses.
128
     *
129
     * If this method returns true, you must implement the get_possible_responses
130
     * method, and the question_definition class must implement the
131
     * classify_response method.
132
     *
133
     * @return bool whether this report can analyse all the student responses
134
     * for things like the quiz statistics report.
135
     */
136
    public function can_analyse_responses() {
137
        // This works in most cases.
138
        return !$this->is_manual_graded();
139
    }
140
 
141
    /**
142
     * @return whether the question_answers.answer field needs to have
143
     * restore_decode_content_links_worker called on it.
144
     */
145
    public function has_html_answers() {
146
        return false;
147
    }
148
 
149
    /**
150
     * If your question type has a table that extends the question table, and
151
     * you want the base class to automatically save, backup and restore the extra fields,
152
     * override this method to return an array wherer the first element is the table name,
153
     * and the subsequent entries are the column names (apart from id and questionid).
154
     *
155
     * @return mixed array as above, or null to tell the base class to do nothing.
156
     */
157
    public function extra_question_fields() {
158
        return null;
159
    }
160
 
161
    /**
162
     * If you use extra_question_fields, overload this function to return question id field name
163
     *  in case you table use another name for this column
164
     */
165
    public function questionid_column_name() {
166
        return 'questionid';
167
    }
168
 
169
    /**
170
     * If your question type has a table that extends the question_answers table,
171
     * make this method return an array wherer the first element is the table name,
172
     * and the subsequent entries are the column names (apart from id and answerid).
173
     *
174
     * @return mixed array as above, or null to tell the base class to do nothing.
175
     */
176
    public function extra_answer_fields() {
177
        return null;
178
    }
179
 
180
    /**
181
     * If the quetsion type uses files in responses, then this method should
182
     * return an array of all the response variables that might have corresponding
183
     * files. For example, the essay qtype returns array('attachments', 'answers').
184
     *
185
     * @return array response variable names that may have associated files.
186
     */
187
    public function response_file_areas() {
188
        return array();
189
    }
190
 
191
    /**
192
     * Return an instance of the question editing form definition. This looks for a
193
     * class called edit_{$this->name()}_question_form in the file
194
     * question/type/{$this->name()}/edit_{$this->name()}_question_form.php
195
     * and if it exists returns an instance of it.
196
     *
197
     * @param string $submiturl passed on to the constructor call.
198
     * @return object an instance of the form definition, or null if one could not be found.
199
     */
200
    public function create_editing_form($submiturl, $question, $category,
201
            $contexts, $formeditable) {
202
        global $CFG;
203
        require_once($CFG->dirroot . '/question/type/edit_question_form.php');
204
        $definitionfile = $CFG->dirroot . '/question/type/' . $this->name() .
205
                '/edit_' . $this->name() . '_form.php';
206
        if (!is_readable($definitionfile) || !is_file($definitionfile)) {
207
            throw new coding_exception($this->plugin_name() .
208
                    ' is missing the definition of its editing formin file ' .
209
                    $definitionfile . '.');
210
        }
211
        require_once($definitionfile);
212
        $classname = $this->plugin_name() . '_edit_form';
213
        if (!class_exists($classname)) {
214
            throw new coding_exception($this->plugin_name() .
215
                    ' does not define the class ' . $this->plugin_name() .
216
                    '_edit_form.');
217
        }
218
        return new $classname($submiturl, $question, $category, $contexts, $formeditable);
219
    }
220
 
221
    /**
222
     * @return string the full path of the folder this plugin's files live in.
223
     */
224
    public function plugin_dir() {
225
        global $CFG;
226
        return $CFG->dirroot . '/question/type/' . $this->name();
227
    }
228
 
229
    /**
230
     * @return string the URL of the folder this plugin's files live in.
231
     */
232
    public function plugin_baseurl() {
233
        global $CFG;
234
        return $CFG->wwwroot . '/question/type/' . $this->name();
235
    }
236
 
237
    /**
238
     * Get extra actions for a question of this type to add to the question bank edit menu.
239
     *
240
     * This method is called if the {@link edit_menu_column} is being used in the
241
     * question bank, which it is by default since Moodle 3.8. If applicable for
242
     * your question type, you can return arn array of {@link action_menu_link}s.
243
     * These will be added at the end of the Edit menu for this question.
244
     *
245
     * The $question object passed in will have a hard-to-predict set of fields,
246
     * because the fields present depend on which columns are included in the
247
     * question bank view. However, you can rely on 'id', 'createdby',
248
     * 'contextid', 'hidden' and 'category' (id) being present, and so you
249
     * can call question_has_capability_on without causing performance problems.
250
     *
251
     * @param stdClass $question the available information about the particular question the action is for.
252
     * @return action_menu_link[] any actions you want to add to the Edit menu for this question.
253
     */
254
    public function get_extra_question_bank_actions(stdClass $question): array {
255
        return [];
256
    }
257
 
258
    /**
259
     * This method should be overriden if you want to include a special heading or some other
260
     * html on a question editing page besides the question editing form.
261
     *
262
     * @param question_edit_form $mform a child of question_edit_form
263
     * @param object $question
264
     * @param string $wizardnow is '' for first page.
265
     */
266
    public function display_question_editing_page($mform, $question, $wizardnow) {
267
        global $OUTPUT;
268
        $heading = $this->get_heading(empty($question->id));
269
        echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
270
        $mform->display();
271
    }
272
 
273
    /**
274
     * Method called by display_question_editing_page and by question.php to get
275
     * heading for breadcrumbs.
276
     *
277
     * @return string the heading
278
     */
279
    public function get_heading($adding = false) {
280
        if ($adding) {
281
            $string = 'pluginnameadding';
282
        } else {
283
            $string = 'pluginnameediting';
284
        }
285
        return get_string($string, $this->plugin_name());
286
    }
287
 
288
    /**
289
     * Set any missing settings for this question to the default values. This is
290
     * called before displaying the question editing form.
291
     *
292
     * @param object $questiondata the question data, loaded from the databsae,
293
     *      or more likely a newly created question object that is only partially
294
     *      initialised.
295
     */
296
    public function set_default_options($questiondata) {
297
    }
298
 
299
    /**
300
     * Return default value for a given form element either from user_preferences table or $default.
301
     *
302
     * @param string $name the name of the form element.
303
     * @param mixed $default default value.
304
     * @return string|null default value for a given  form element.
305
     */
306
    public function get_default_value(string $name, $default): ?string {
307
        return get_user_preferences($this->plugin_name() . '_' . $name, $default ?? '0');
308
    }
309
 
310
    /**
311
     * Save the default value for a given form element in user_preferences table.
312
     *
313
     * @param string $name the name of the value to set.
314
     * @param string $value the setting value.
315
     */
316
    public function set_default_value(string $name, string $value): void {
317
        set_user_preference($this->plugin_name() . '_' . $name, $value);
318
    }
319
 
320
    /**
321
     * Save question defaults when creating new questions.
322
     *
323
     * @param stdClass $fromform data from the form.
324
     */
325
    public function save_defaults_for_new_questions(stdClass $fromform): void {
326
        // Some question types may not make use of the certain form elements, so
327
        // we need to do a check on the following generic form elements. For instance,
328
        // 'defaultmark' is not use in qtype_multianswer and 'penalty' in not used in
329
        // qtype_essay and qtype_recordrtc.
330
        if (isset($fromform->defaultmark)) {
331
            $this->set_default_value('defaultmark', $fromform->defaultmark);
332
        }
333
        if (isset($fromform->penalty)) {
334
            $this->set_default_value('penalty', $fromform->penalty);
335
        }
336
    }
337
 
338
    /**
339
     * Saves (creates or updates) a question.
340
     *
341
     * Given some question info and some data about the answers
342
     * this function parses, organises and saves the question
343
     * It is used by {@link question.php} when saving new data from
344
     * a form, and also by {@link import.php} when importing questions
345
     * This function in turn calls {@link save_question_options}
346
     * to save question-type specific data.
347
     *
348
     * Whether we are saving a new question or updating an existing one can be
349
     * determined by testing !empty($question->id). If it is not empty, we are updating.
350
     *
351
     * The question will be saved in category $form->category.
352
     *
353
     * @param object $question the question object which should be updated. For a
354
     *      new question will be mostly empty.
355
     * @param object $form the object containing the information to save, as if
356
     *      from the question editing form.
357
     * @param object $course not really used any more.
358
     * @return object On success, return the new question object. On failure,
359
     *       return an object as follows. If the error object has an errors field,
360
     *       display that as an error message. Otherwise, the editing form will be
361
     *       redisplayed with validation errors, from validation_errors field, which
362
     *       is itself an object, shown next to the form fields. (I don't think this
363
     *       is accurate any more.)
364
     */
365
    public function save_question($question, $form) {
366
        global $USER, $DB;
367
 
368
        // The actual update/insert done with multiple DB access, so we do it in a transaction.
369
        $transaction = $DB->start_delegated_transaction ();
370
 
371
        list($form->category) = explode(',', $form->category);
372
        $context = $this->get_context_by_category_id($form->category);
373
        $question->category = $form->category;
374
 
375
        // This default implementation is suitable for most
376
        // question types.
377
 
378
        // First, save the basic question itself.
379
        $question->name = trim($form->name);
380
        $question->parent = isset($form->parent) ? $form->parent : 0;
381
        $question->length = $this->actual_number_of_questions($question);
382
        $question->penalty = isset($form->penalty) ? $form->penalty : 0;
383
 
384
        // The trim call below has the effect of casting any strange values received,
385
        // like null or false, to an appropriate string, so we only need to test for
386
        // missing values. Be careful not to break the value '0' here.
387
        if (!isset($form->questiontext['text'])) {
388
            $question->questiontext = '';
389
        } else {
390
            $question->questiontext = trim($form->questiontext['text']);
391
        }
392
        $question->questiontextformat = !empty($form->questiontext['format']) ?
393
                $form->questiontext['format'] : 0;
394
 
395
        if (empty($form->generalfeedback['text'])) {
396
            $question->generalfeedback = '';
397
        } else {
398
            $question->generalfeedback = trim($form->generalfeedback['text']);
399
        }
400
        $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
401
                $form->generalfeedback['format'] : 0;
402
 
403
        if ($question->name === '') {
404
            $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
405
            if ($question->name === '') {
406
                $question->name = '-';
407
            }
408
        }
409
 
410
        if ($question->penalty > 1 or $question->penalty < 0) {
411
            $question->errors['penalty'] = get_string('invalidpenalty', 'question');
412
        }
413
 
414
        if (isset($form->defaultmark)) {
415
            $question->defaultmark = $form->defaultmark;
416
        }
417
 
418
        // Only create a new bank entry if the question is not a new version (New question or duplicating a question).
419
        $questionbankentry = null;
420
        if (isset($question->id)) {
421
            $oldparent = $question->id;
422
            if (!empty($question->id)) {
423
                // Get the bank entry record where the question is referenced.
424
                $questionbankentry = get_question_bank_entry($question->id);
425
            }
426
        }
427
 
428
        // Get the bank entry old id (this is when there are questions related with a parent, e.g.: qtype_multianswers).
429
        if (isset($question->oldid)) {
430
            if (!empty($question->oldid)) {
431
                $questionbankentry = get_question_bank_entry($question->oldid);
432
            }
433
        }
434
 
435
        // Always creates a new question and version record.
436
        // Set the unique code.
437
        $question->stamp = make_unique_id_code();
438
        $question->createdby = $USER->id;
439
        $question->timecreated = time();
440
 
441
        // Idnumber validation.
442
        $question->idnumber = null;
443
        if (isset($form->idnumber)) {
444
            if ((string) $form->idnumber === '') {
445
                $question->idnumber = null;
446
            } else {
447
                // While this check already exists in the form validation,
448
                // this is a backstop preventing unnecessary errors.
449
                // Only set the idnumber if it has changed and will not cause a unique index violation.
450
                if (strpos($form->category, ',') !== false) {
451
                    list($category, $categorycontextid) = explode(',', $form->category);
452
                } else {
453
                    $category = $form->category;
454
                }
455
                $params = ['idnumber' => $form->idnumber, 'categoryid' => $category];
456
                $andcondition = '';
457
                if (isset($question->id) && isset($questionbankentry->id)) {
458
                    $andcondition = 'AND qbe.id != :notid';
459
                    $params['notid'] = $questionbankentry->id;
460
                }
461
                $sql = "SELECT qbe.id
462
                          FROM {question_bank_entries} qbe
463
                         WHERE qbe.idnumber = :idnumber
464
                               AND qbe.questioncategoryid = :categoryid
465
                           $andcondition";
466
                if (!$DB->record_exists_sql($sql, $params)) {
467
                    $question->idnumber = $form->idnumber;
468
                }
469
            }
470
        }
471
 
472
        // Create the question.
473
        $question->id = $DB->insert_record('question', $question);
474
        if (!$questionbankentry) {
475
            // Create a record for question_bank_entries, question_versions and question_references.
476
            $questionbankentry = new \stdClass();
477
            $questionbankentry->questioncategoryid = $form->category;
478
            $questionbankentry->idnumber = $question->idnumber;
479
            $questionbankentry->ownerid = $question->createdby;
480
            $questionbankentry->id = $DB->insert_record('question_bank_entries', $questionbankentry);
481
        } else {
482
            $questionbankentryold = new \stdClass();
483
            $questionbankentryold->id = $questionbankentry->id;
484
            $questionbankentryold->idnumber = $question->idnumber;
485
            $DB->update_record('question_bank_entries', $questionbankentryold);
486
        }
487
 
488
        // Create question_versions records.
489
        $questionversion = new \stdClass();
490
        $questionversion->questionbankentryid = $questionbankentry->id;
491
        $questionversion->questionid = $question->id;
492
        // Get the version and status from the parent question if parent is set.
493
        if (!$question->parent) {
494
            // Get the status field. It comes from the form, but for testing we can.
495
            $status = $form->status ?? $question->status ??
496
                \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
497
            $questionversion->version = get_next_version($questionbankentry->id);
498
            $questionversion->status = $status;
499
        } else {
500
            $parentversion = get_question_version($form->parent);
501
            $questionversion->version = $parentversion[array_key_first($parentversion)]->version;
502
            $questionversion->status = $parentversion[array_key_first($parentversion)]->status;
503
        }
504
        $questionversion->id = $DB->insert_record('question_versions', $questionversion);
505
 
506
        // Now, whether we are updating a existing question, or creating a new
507
        // one, we have to do the files processing and update the record.
508
        // Question already exists, update.
509
        $question->modifiedby = $USER->id;
510
        $question->timemodified = time();
511
 
512
        if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
513
            $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
514
                    $context->id, 'question', 'questiontext', (int)$question->id,
515
                    $this->fileoptions, $question->questiontext);
516
        }
517
        if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
518
            $question->generalfeedback = file_save_draft_area_files(
519
                    $form->generalfeedback['itemid'], $context->id,
520
                    'question', 'generalfeedback', (int)$question->id,
521
                    $this->fileoptions, $question->generalfeedback);
522
        }
523
        $DB->update_record('question', $question);
524
 
525
        // Now to save all the answers and type-specific options.
526
        $form->id = $question->id;
527
        $form->qtype = $question->qtype;
528
        $form->questiontext = $question->questiontext;
529
        $form->questiontextformat = $question->questiontextformat;
530
        // Current context.
531
        $form->context = $context;
532
        // Old parent question id is used when there are questions related with a parent, e.g.: qtype_multianswers).
533
        if (isset($oldparent)) {
534
            $form->oldparent = $oldparent;
535
        } else {
536
            $form->oldparent = $question->parent;
537
        }
538
        $result = $this->save_question_options($form);
539
 
540
        if (!empty($result->error)) {
541
            throw new \moodle_exception($result->error);
542
        }
543
 
544
        if (!empty($result->notice)) {
545
            notice($result->notice, "question.php?id={$question->id}");
546
        }
547
 
548
        if (!empty($result->noticeyesno)) {
549
            throw new coding_exception(
550
                    '$result->noticeyesno no longer supported in save_question.');
551
        }
552
 
553
        // Log the creation of this question.
554
        $event = \core\event\question_created::create_from_question_instance($question, $context);
555
        $event->trigger();
556
 
557
        $transaction->allow_commit();
558
 
559
        return $question;
560
    }
561
 
562
    /**
563
     * Saves question-type specific options
564
     *
565
     * This is called by {@see save_question()} to save the question-type specific data
566
     *
567
     * @param object $question This holds the information from the editing form,
568
     *      it is not a standard question object.
569
     * @return bool|stdClass $result->error or $result->notice
570
     */
571
    public function save_question_options($question) {
572
        global $DB;
573
        $extraquestionfields = $this->extra_question_fields();
574
 
575
        if (is_array($extraquestionfields)) {
576
            $question_extension_table = array_shift($extraquestionfields);
577
 
578
            $function = 'update_record';
579
            $questionidcolname = $this->questionid_column_name();
580
            $options = $DB->get_record($question_extension_table,
581
                    array($questionidcolname => $question->id));
582
            if (!$options) {
583
                $function = 'insert_record';
584
                $options = new stdClass();
585
                $options->$questionidcolname = $question->id;
586
            }
587
            foreach ($extraquestionfields as $field) {
588
                if (property_exists($question, $field)) {
589
                    $options->$field = $question->$field;
590
                }
591
            }
592
 
593
            $DB->{$function}($question_extension_table, $options);
594
        }
595
    }
596
 
597
    /**
598
     * Save the answers, with any extra data.
599
     *
600
     * Questions that use answers will call it from {@link save_question_options()}.
601
     * @param object $question  This holds the information from the editing form,
602
     *      it is not a standard question object.
603
     * @return object $result->error or $result->notice
604
     */
605
    public function save_question_answers($question) {
606
        global $DB;
607
 
608
        $context = $question->context;
609
        $oldanswers = $DB->get_records('question_answers',
610
                array('question' => $question->id), 'id ASC');
611
 
612
        // We need separate arrays for answers and extra answer data, so no JOINS there.
613
        $extraanswerfields = $this->extra_answer_fields();
614
        $isextraanswerfields = is_array($extraanswerfields);
615
        $extraanswertable = '';
616
        $oldanswerextras = array();
617
        if ($isextraanswerfields) {
618
            $extraanswertable = array_shift($extraanswerfields);
619
            if (!empty($oldanswers)) {
620
                $oldanswerextras = $DB->get_records_sql("SELECT * FROM {{$extraanswertable}} WHERE " .
621
                    'answerid IN (SELECT id FROM {question_answers} WHERE question = ' . $question->id . ')' );
622
            }
623
        }
624
 
625
        // Insert all the new answers.
626
        foreach ($question->answer as $key => $answerdata) {
627
            // Check for, and ignore, completely blank answer from the form.
628
            if ($this->is_answer_empty($question, $key)) {
629
                continue;
630
            }
631
 
632
            // Update an existing answer if possible.
633
            $answer = array_shift($oldanswers);
634
            if (!$answer) {
635
                $answer = new stdClass();
636
                $answer->question = $question->id;
637
                $answer->answer = '';
638
                $answer->feedback = '';
639
                $answer->id = $DB->insert_record('question_answers', $answer);
640
            }
641
 
642
            $answer = $this->fill_answer_fields($answer, $question, $key, $context);
643
            $DB->update_record('question_answers', $answer);
644
 
645
            if ($isextraanswerfields) {
646
                // Check, if this answer contains some extra field data.
647
                if ($this->is_extra_answer_fields_empty($question, $key)) {
648
                    continue;
649
                }
650
 
651
                $answerextra = array_shift($oldanswerextras);
652
                if (!$answerextra) {
653
                    $answerextra = new stdClass();
654
                    $answerextra->answerid = $answer->id;
655
                    // Avoid looking for correct default for any possible DB field type
656
                    // by setting real values.
657
                    $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
658
                    $answerextra->id = $DB->insert_record($extraanswertable, $answerextra);
659
                } else {
660
                    // Update answerid, as record may be reused from another answer.
661
                    $answerextra->answerid = $answer->id;
662
                    $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
663
                    $DB->update_record($extraanswertable, $answerextra);
664
                }
665
            }
666
        }
667
 
668
        if ($isextraanswerfields) {
669
            // Delete any left over extra answer fields records.
670
            $oldanswerextraids = array();
671
            foreach ($oldanswerextras as $oldextra) {
672
                $oldanswerextraids[] = $oldextra->id;
673
            }
674
            $DB->delete_records_list($extraanswertable, 'id', $oldanswerextraids);
675
        }
676
 
677
        // Delete any left over old answer records.
678
        $fs = get_file_storage();
679
        foreach ($oldanswers as $oldanswer) {
680
            $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
681
            $DB->delete_records('question_answers', array('id' => $oldanswer->id));
682
        }
683
    }
684
 
685
    /**
686
     * Returns true is answer with the $key is empty in the question data and should not be saved in DB.
687
     *
688
     * The questions using question_answers table may want to overload this. Default code will work
689
     * for shortanswer and similar question types.
690
     * @param object $questiondata This holds the information from the question editing form or import.
691
     * @param int $key A key of the answer in question.
692
     * @return bool True if answer shouldn't be saved in DB.
693
     */
694
    protected function is_answer_empty($questiondata, $key) {
695
        return trim($questiondata->answer[$key]) == '' && $questiondata->fraction[$key] == 0 &&
696
                    html_is_blank($questiondata->feedback[$key]['text']);
697
    }
698
 
699
    /**
700
     * Return $answer, filling necessary fields for the question_answers table.
701
     *
702
     * The questions using question_answers table may want to overload this. Default code will work
703
     * for shortanswer and similar question types.
704
     * @param stdClass $answer Object to save data.
705
     * @param object $questiondata This holds the information from the question editing form or import.
706
     * @param int $key A key of the answer in question.
707
     * @param object $context needed for working with files.
708
     * @return $answer answer with filled data.
709
     */
710
    protected function fill_answer_fields($answer, $questiondata, $key, $context) {
711
        $answer->answer   = $questiondata->answer[$key];
712
        $answer->fraction = $questiondata->fraction[$key];
713
        $answer->feedback = $this->import_or_save_files($questiondata->feedback[$key],
714
                $context, 'question', 'answerfeedback', $answer->id);
715
        $answer->feedbackformat = $questiondata->feedback[$key]['format'];
716
        return $answer;
717
    }
718
 
719
    /**
720
     * Returns true if extra answer fields for answer with the $key is empty
721
     * in the question data and should not be saved in DB.
722
     *
723
     * Questions where extra answer fields are optional will want to overload this.
724
     * @param object $questiondata This holds the information from the question editing form or import.
725
     * @param int $key A key of the answer in question.
726
     * @return bool True if extra answer data shouldn't be saved in DB.
727
     */
728
    protected function is_extra_answer_fields_empty($questiondata, $key) {
729
        // No extra answer data in base class.
730
        return true;
731
    }
732
 
733
    /**
734
     * Return $answerextra, filling necessary fields for the extra answer fields table.
735
     *
736
     * The questions may want to overload it to save files or do other data processing.
737
     * @param stdClass $answerextra Object to save data.
738
     * @param object $questiondata This holds the information from the question editing form or import.
739
     * @param int $key A key of the answer in question.
740
     * @param object $context needed for working with files.
741
     * @param array $extraanswerfields extra answer fields (without table name).
742
     * @return $answer answerextra with filled data.
743
     */
744
    protected function fill_extra_answer_fields($answerextra, $questiondata, $key, $context, $extraanswerfields) {
745
        foreach ($extraanswerfields as $field) {
746
            // The $questiondata->$field[$key] won't work in PHP, break it down to two strings of code.
747
            $fieldarray = $questiondata->$field;
748
            $answerextra->$field = $fieldarray[$key];
749
        }
750
        return $answerextra;
751
    }
752
 
753
    public function save_hints($formdata, $withparts = false) {
754
        global $DB;
755
        $context = $formdata->context;
756
 
757
        $oldhints = $DB->get_records('question_hints',
758
                array('questionid' => $formdata->id), 'id ASC');
759
 
760
 
761
        $numhints = $this->count_hints_on_form($formdata, $withparts);
762
 
763
        for ($i = 0; $i < $numhints; $i += 1) {
764
            if (html_is_blank($formdata->hint[$i]['text'])) {
765
                $formdata->hint[$i]['text'] = '';
766
            }
767
 
768
            if ($withparts) {
769
                $clearwrong = !empty($formdata->hintclearwrong[$i]);
770
                $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
771
            }
772
 
773
            if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) {
774
                continue;
775
            }
776
 
777
            // Update an existing hint if possible.
778
            $hint = array_shift($oldhints);
779
            if (!$hint) {
780
                $hint = new stdClass();
781
                $hint->questionid = $formdata->id;
782
                $hint->hint = '';
783
                $hint->id = $DB->insert_record('question_hints', $hint);
784
            }
785
 
786
            $hint->hint = $this->import_or_save_files($formdata->hint[$i],
787
                    $context, 'question', 'hint', $hint->id);
788
            $hint->hintformat = $formdata->hint[$i]['format'];
789
            if ($withparts) {
790
                $hint->clearwrong = $clearwrong;
791
                $hint->shownumcorrect = $shownumcorrect;
792
            }
793
            $hint->options = $this->save_hint_options($formdata, $i, $withparts);
794
            $DB->update_record('question_hints', $hint);
795
        }
796
 
797
        // Delete any remaining old hints.
798
        $fs = get_file_storage();
799
        foreach ($oldhints as $oldhint) {
800
            $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
801
            $DB->delete_records('question_hints', array('id' => $oldhint->id));
802
        }
803
    }
804
 
805
    /**
806
     * Count number of hints on the form.
807
     * Overload if you use custom hint controls.
808
     * @param object $formdata the data from the form.
809
     * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
810
     * @return int count of hints on the form.
811
     */
812
    protected function count_hints_on_form($formdata, $withparts) {
813
        if (!empty($formdata->hint)) {
814
            $numhints = max(array_keys($formdata->hint)) + 1;
815
        } else {
816
            $numhints = 0;
817
        }
818
 
819
        if ($withparts) {
820
            if (!empty($formdata->hintclearwrong)) {
821
                $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
822
            } else {
823
                $numclears = 0;
824
            }
825
            if (!empty($formdata->hintshownumcorrect)) {
826
                $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
827
            } else {
828
                $numshows = 0;
829
            }
830
            $numhints = max($numhints, $numclears, $numshows);
831
        }
832
        return $numhints;
833
    }
834
 
835
    /**
836
     * Determine if the hint with specified number is not empty and should be saved.
837
     * Overload if you use custom hint controls.
838
     * @param object $formdata the data from the form.
839
     * @param int $number number of hint under question.
840
     * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
841
     * @return bool is this particular hint data empty.
842
     */
843
    protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
844
        if ($withparts) {
845
            return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) &&
846
                    empty($formdata->hintshownumcorrect[$number]);
847
        } else {
848
            return  empty($formdata->hint[$number]['text']);
849
        }
850
    }
851
 
852
    /**
853
     * Save additional question type data into the hint optional field.
854
     * Overload if you use custom hint information.
855
     * @param object $formdata the data from the form.
856
     * @param int $number number of hint to get options from.
857
     * @param bool $withparts whether question have parts.
858
     * @return string value to save into the options field of question_hints table.
859
     */
860
    protected function save_hint_options($formdata, $number, $withparts) {
861
        return null;    // By default, options field is unused.
862
    }
863
 
864
    /**
865
     * Can be used to {@link save_question_options()} to transfer the combined
866
     * feedback fields from $formdata to $options.
867
     * @param object $options the $question->options object being built.
868
     * @param object $formdata the data from the form.
869
     * @param object $context the context the quetsion is being saved into.
870
     * @param bool $withparts whether $options->shownumcorrect should be set.
871
     */
872
    protected function save_combined_feedback_helper($options, $formdata,
873
            $context, $withparts = false) {
874
        $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
875
                $context, 'question', 'correctfeedback', $formdata->id);
876
        $options->correctfeedbackformat = $formdata->correctfeedback['format'];
877
 
878
        $options->partiallycorrectfeedback = $this->import_or_save_files(
879
                $formdata->partiallycorrectfeedback,
880
                $context, 'question', 'partiallycorrectfeedback', $formdata->id);
881
        $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
882
 
883
        $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
884
                $context, 'question', 'incorrectfeedback', $formdata->id);
885
        $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
886
 
887
        if ($withparts) {
888
            $options->shownumcorrect = !empty($formdata->shownumcorrect);
889
        }
890
 
891
        return $options;
892
    }
893
 
894
    /**
895
     * Loads the question type specific options for the question.
896
     *
897
     * This function loads any question type specific options for the
898
     * question from the database into the question object. This information
899
     * is placed in the $question->options field. A question type is
900
     * free, however, to decide on a internal structure of the options field.
901
     * @return bool            Indicates success or failure.
902
     * @param object $question The question object for the question. This object
903
     *                         should be updated to include the question type
904
     *                         specific information (it is passed by reference).
905
     */
906
    public function get_question_options($question) {
907
        global $DB, $OUTPUT;
908
 
909
        if (!isset($question->options)) {
910
            $question->options = new stdClass();
911
        }
912
 
913
        $extraquestionfields = $this->extra_question_fields();
914
        if (is_array($extraquestionfields)) {
915
            $question_extension_table = array_shift($extraquestionfields);
916
            $extra_data = $DB->get_record($question_extension_table,
917
                    array($this->questionid_column_name() => $question->id),
918
                    implode(', ', $extraquestionfields));
919
            if ($extra_data) {
920
                foreach ($extraquestionfields as $field) {
921
                    $question->options->$field = $extra_data->$field;
922
                }
923
            } else {
924
                echo $OUTPUT->notification('Failed to load question options from the table ' .
925
                        $question_extension_table . ' for questionid ' . $question->id);
926
                return false;
927
            }
928
        }
929
 
930
        $extraanswerfields = $this->extra_answer_fields();
931
        if (is_array($extraanswerfields)) {
932
            $answerextensiontable = array_shift($extraanswerfields);
933
            // Use LEFT JOIN in case not every answer has extra data.
934
            $answers = $DB->get_records_sql("
935
                    SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . '
936
                    FROM {question_answers} qa ' . "
937
                    LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid
938
                    WHERE qa.question = ?
939
                    ORDER BY qa.id", array($question->id));
940
            if (!$answers) {
941
                echo $OUTPUT->notification('Failed to load question answers from the table ' .
942
                        $answerextensiontable . 'for questionid ' . $question->id);
943
                return false;
944
            }
945
        } else {
946
            // Don't check for success or failure because some question types do
947
            // not use the answers table.
948
            $answers = $DB->get_records('question_answers',
949
                    array('question' => $question->id), 'id ASC');
950
        }
951
        // Store the answers into the question object.
952
        $question->options->answers = array_map(function($answer) {
953
            // Some database engines return floats as strings like '1.0000000'. Cast to float for consistency.
954
            $answer->fraction = (float) $answer->fraction;
955
            return $answer;
956
        }, $answers);
957
 
958
        $question->hints = $DB->get_records('question_hints',
959
                array('questionid' => $question->id), 'id ASC');
960
 
961
        return true;
962
    }
963
 
964
    /**
965
     * Create an appropriate question_definition for the question of this type
966
     * using data loaded from the database.
967
     * @param object $questiondata the question data loaded from the database.
968
     * @return question_definition the corresponding question_definition.
969
     */
970
    public function make_question($questiondata) {
971
        $question = $this->make_question_instance($questiondata);
972
        $this->initialise_question_instance($question, $questiondata);
973
        return $question;
974
    }
975
 
976
    /**
977
     * Create an appropriate question_definition for the question of this type
978
     * using data loaded from the database.
979
     * @param object $questiondata the question data loaded from the database.
980
     * @return question_definition an instance of the appropriate question_definition subclass.
981
     *      Still needs to be initialised.
982
     */
983
    protected function make_question_instance($questiondata) {
984
        question_bank::load_question_definition_classes($this->name());
985
        $class = 'qtype_' . $this->name() . '_question';
986
        return new $class();
987
    }
988
 
989
    /**
990
     * Initialise the common question_definition fields.
991
     * @param question_definition $question the question_definition we are creating.
992
     * @param object $questiondata the question data loaded from the database.
993
     */
994
    protected function initialise_question_instance(question_definition $question, $questiondata) {
995
        $question->id = $questiondata->id;
996
        $question->category = $questiondata->category;
997
        $question->contextid = $questiondata->contextid;
998
        $question->parent = $questiondata->parent;
999
        $question->qtype = $this;
1000
        $question->name = $questiondata->name;
1001
        $question->questiontext = $questiondata->questiontext;
1002
        $question->questiontextformat = $questiondata->questiontextformat;
1003
        $question->generalfeedback = $questiondata->generalfeedback;
1004
        $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
1005
        $question->defaultmark = $questiondata->defaultmark + 0;
1006
        $question->length = $questiondata->length;
1007
        $question->penalty = $questiondata->penalty;
1008
        $question->stamp = $questiondata->stamp;
1009
        $question->timecreated = $questiondata->timecreated;
1010
        $question->timemodified = $questiondata->timemodified;
1011
        $question->createdby = $questiondata->createdby;
1012
        $question->modifiedby = $questiondata->modifiedby;
1013
 
1014
        $this->initialise_core_question_metadata($question, $questiondata);
1015
 
1016
        // Fill extra question fields values.
1017
        $extraquestionfields = $this->extra_question_fields();
1018
        if (is_array($extraquestionfields)) {
1019
            // Omit table name.
1020
            array_shift($extraquestionfields);
1021
            foreach ($extraquestionfields as $field) {
1022
                $question->$field = $questiondata->options->$field;
1023
            }
1024
        }
1025
 
1026
        $this->initialise_question_hints($question, $questiondata);
1027
 
1028
        // Add the custom fields.
1029
        $this->initialise_custom_fields($question, $questiondata);
1030
    }
1031
 
1032
    /**
1033
     * Initialise the question metadata.
1034
     *
1035
     * @param question_definition $question the question_definition we are creating.
1036
     * @param object $questiondata the question data loaded from the database.
1037
     */
1038
    protected function initialise_core_question_metadata(question_definition $question, $questiondata) {
1039
        $fields =
1040
            [
1041
                'status',
1042
                'versionid',
1043
                'version',
1044
                'questionbankentryid',
1045
                'idnumber',
1046
            ];
1047
 
1048
        foreach ($fields as $field) {
1049
            if (isset($questiondata->{$field})) {
1050
                $question->{$field} = $questiondata->{$field};
1051
            }
1052
        }
1053
    }
1054
 
1055
    /**
1056
     * Initialise question_definition::hints field.
1057
     * @param question_definition $question the question_definition we are creating.
1058
     * @param object $questiondata the question data loaded from the database.
1059
     */
1060
    protected function initialise_question_hints(question_definition $question, $questiondata) {
1061
        if (empty($questiondata->hints)) {
1062
            return;
1063
        }
1064
        foreach ($questiondata->hints as $hint) {
1065
            $question->hints[] = $this->make_hint($hint);
1066
        }
1067
    }
1068
 
1069
    /**
1070
     * Create a question_hint, or an appropriate subclass for this question,
1071
     * from a row loaded from the database.
1072
     * @param object $hint the DB row from the question hints table.
1073
     * @return question_hint
1074
     */
1075
    protected function make_hint($hint) {
1076
        return question_hint::load_from_record($hint);
1077
    }
1078
 
1079
    /**
1080
     * Initialise question custom fields.
1081
     * @param question_definition $question the question_definition we are creating.
1082
     * @param object $questiondata the question data loaded from the database.
1083
     */
1084
    protected function initialise_custom_fields(question_definition $question, $questiondata) {
1085
        if (!empty($questiondata->customfields)) {
1086
             $question->customfields = $questiondata->customfields;
1087
        }
1088
    }
1089
 
1090
    /**
1091
     * Initialise the combined feedback fields.
1092
     * @param question_definition $question the question_definition we are creating.
1093
     * @param object $questiondata the question data loaded from the database.
1094
     * @param bool $withparts whether to set the shownumcorrect field.
1095
     */
1096
    protected function initialise_combined_feedback(question_definition $question,
1097
            $questiondata, $withparts = false) {
1098
        $question->correctfeedback = $questiondata->options->correctfeedback;
1099
        $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
1100
        $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
1101
        $question->partiallycorrectfeedbackformat =
1102
                $questiondata->options->partiallycorrectfeedbackformat;
1103
        $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
1104
        $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
1105
        if ($withparts) {
1106
            $question->shownumcorrect = $questiondata->options->shownumcorrect;
1107
        }
1108
    }
1109
 
1110
    /**
1111
     * Initialise question_definition::answers field.
1112
     * @param question_definition $question the question_definition we are creating.
1113
     * @param object $questiondata the question data loaded from the database.
1114
     * @param bool $forceplaintextanswers most qtypes assume that answers are
1115
     *      FORMAT_PLAIN, and dont use the answerformat DB column (it contains
1116
     *      the default 0 = FORMAT_MOODLE). Therefore, by default this method
1117
     *      ingores answerformat. Pass false here to use answerformat. For example
1118
     *      multichoice does this.
1119
     */
1120
    protected function initialise_question_answers(question_definition $question,
1121
            $questiondata, $forceplaintextanswers = true) {
1122
        $question->answers = array();
1123
        if (empty($questiondata->options->answers)) {
1124
            return;
1125
        }
1126
        foreach ($questiondata->options->answers as $a) {
1127
            $question->answers[$a->id] = $this->make_answer($a);
1128
            if (!$forceplaintextanswers) {
1129
                $question->answers[$a->id]->answerformat = $a->answerformat;
1130
            }
1131
        }
1132
    }
1133
 
1134
    /**
1135
     * Create a question_answer, or an appropriate subclass for this question,
1136
     * from a row loaded from the database.
1137
     * @param object $answer the DB row from the question_answers table plus extra answer fields.
1138
     * @return question_answer
1139
     */
1140
    protected function make_answer($answer) {
1141
        return new question_answer($answer->id, $answer->answer,
1142
                    $answer->fraction, $answer->feedback, $answer->feedbackformat);
1143
    }
1144
 
1145
    /**
1146
     * Deletes the question-type specific data when a question is deleted.
1147
     * @param int $question the question being deleted.
1148
     * @param int $contextid the context this quesiotn belongs to.
1149
     */
1150
    public function delete_question($questionid, $contextid) {
1151
        global $DB;
1152
 
1153
        $this->delete_files($questionid, $contextid);
1154
 
1155
        $extraquestionfields = $this->extra_question_fields();
1156
        if (is_array($extraquestionfields)) {
1157
            $question_extension_table = array_shift($extraquestionfields);
1158
            $DB->delete_records($question_extension_table,
1159
                    array($this->questionid_column_name() => $questionid));
1160
        }
1161
 
1162
        $extraanswerfields = $this->extra_answer_fields();
1163
        if (is_array($extraanswerfields)) {
1164
            $answer_extension_table = array_shift($extraanswerfields);
1165
            $DB->delete_records_select($answer_extension_table,
1166
                    'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
1167
                    array($questionid));
1168
        }
1169
 
1170
        $DB->delete_records('question_answers', array('question' => $questionid));
1171
 
1172
        $DB->delete_records('question_hints', array('questionid' => $questionid));
1173
    }
1174
 
1175
    /**
1176
     * Returns the number of question numbers which are used by the question
1177
     *
1178
     * This function returns the number of question numbers to be assigned
1179
     * to the question. Most question types will have length one; they will be
1180
     * assigned one number. The 'description' type, however does not use up a
1181
     * number and so has a length of zero. Other question types may wish to
1182
     * handle a bundle of questions and hence return a number greater than one.
1183
     * @return int         The number of question numbers which should be
1184
     *                         assigned to the question.
1185
     * @param object $question The question whose length is to be determined.
1186
     *                         Question type specific information is included.
1187
     */
1188
    public function actual_number_of_questions($question) {
1189
        // By default, each question is given one number.
1190
        return 1;
1191
    }
1192
 
1193
    /**
1194
     * Calculate the score a monkey would get on a question by clicking randomly.
1195
     *
1196
     * Some question types have significant non-zero average expected score
1197
     * of the response is just selected randomly. For example 50% for a
1198
     * true-false question. It is useful to know what this is. For example
1199
     * it gets shown in the quiz statistics report.
1200
     *
1201
     * For almost any open-ended question type (E.g. shortanswer or numerical)
1202
     * this should be 0.
1203
     *
1204
     * For selective response question types (e.g. multiple choice), you can probably compute this.
1205
     *
1206
     * For particularly complicated question types the may be impossible or very
1207
     * difficult to compute. In this case return null. (Or, if the expected score
1208
     * is very tiny even though the exact value is unknown, it may appropriate
1209
     * to return 0.)
1210
     *
1211
     * @param stdClass $questiondata data defining a question, as returned by
1212
     *      question_bank::load_question_data().
1213
     * @return number|null either a fraction estimating what the student would
1214
     *      score by guessing, or null, if it is not possible to estimate.
1215
     */
1216
    public function get_random_guess_score($questiondata) {
1217
        return 0;
1218
    }
1219
 
1220
    /**
1221
     * Whether or not to break down question stats and response analysis, for a question defined by $questiondata.
1222
     *
1223
     * @param object $questiondata The full question definition data.
1224
     * @return bool
1225
     */
1226
    public function break_down_stats_and_response_analysis_by_variant($questiondata) {
1227
        return true;
1228
    }
1229
 
1230
    /**
1231
     * This method should return all the possible types of response that are
1232
     * recognised for this question.
1233
     *
1234
     * The question is modelled as comprising one or more subparts. For each
1235
     * subpart, there are one or more classes that that students response
1236
     * might fall into, each of those classes earning a certain score.
1237
     *
1238
     * For example, in a shortanswer question, there is only one subpart, the
1239
     * text entry field. The response the student gave will be classified according
1240
     * to which of the possible $question->options->answers it matches.
1241
     *
1242
     * For the matching question type, there will be one subpart for each
1243
     * question stem, and for each stem, each of the possible choices is a class
1244
     * of student's response.
1245
     *
1246
     * A response is an object with two fields, ->responseclass is a string
1247
     * presentation of that response, and ->fraction, the credit for a response
1248
     * in that class.
1249
     *
1250
     * Array keys have no specific meaning, but must be unique, and must be
1251
     * the same if this function is called repeatedly.
1252
     *
1253
     * @param object $question the question definition data.
1254
     * @return array keys are subquestionid, values are arrays of possible
1255
     *      responses to that subquestion.
1256
     */
1257
    public function get_possible_responses($questiondata) {
1258
        return array();
1259
    }
1260
 
1261
    /**
1262
     * Utility method used by {@link qtype_renderer::head_code()}. It looks
1263
     * for any of the files script.js or script.php that exist in the plugin
1264
     * folder and ensures they get included.
1265
     */
1266
    public function find_standard_scripts() {
1267
        global $PAGE;
1268
 
1269
        $plugindir = $this->plugin_dir();
1270
        $plugindirrel = 'question/type/' . $this->name();
1271
 
1272
        if (file_exists($plugindir . '/script.js')) {
1273
            $PAGE->requires->js('/' . $plugindirrel . '/script.js');
1274
        }
1275
        if (file_exists($plugindir . '/script.php')) {
1276
            $PAGE->requires->js('/' . $plugindirrel . '/script.php');
1277
        }
1278
    }
1279
 
1280
    /**
1281
     * Returns true if the editing wizard is finished, false otherwise.
1282
     *
1283
     * The default implementation returns true, which is suitable for all question-
1284
     * types that only use one editing form. This function is used in
1285
     * question.php to decide whether we can regrade any states of the edited
1286
     * question and redirect to edit.php.
1287
     *
1288
     * The dataset dependent question-type, which is extended by the calculated
1289
     * question-type, overwrites this method because it uses multiple pages (i.e.
1290
     * a wizard) to set up the question and associated datasets.
1291
     *
1292
     * @param object $form  The data submitted by the previous page.
1293
     *
1294
     * @return bool      Whether the wizard's last page was submitted or not.
1295
     */
1296
    public function finished_edit_wizard($form) {
1297
        // In the default case there is only one edit page.
1298
        return true;
1299
    }
1300
 
1301
    // IMPORT/EXPORT FUNCTIONS --------------------------------- .
1302
 
1303
    /*
1304
     * Imports question from the Moodle XML format
1305
     *
1306
     * Imports question using information from extra_question_fields function
1307
     * If some of you fields contains id's you'll need to reimplement this
1308
     */
1309
    public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
1310
        $question_type = $data['@']['type'];
1311
        if ($question_type != $this->name()) {
1312
            return false;
1313
        }
1314
 
1315
        $extraquestionfields = $this->extra_question_fields();
1316
        if (!is_array($extraquestionfields)) {
1317
            return false;
1318
        }
1319
 
1320
        // Omit table name.
1321
        array_shift($extraquestionfields);
1322
        $qo = $format->import_headers($data);
1323
        $qo->qtype = $question_type;
1324
 
1325
        foreach ($extraquestionfields as $field) {
1326
            $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
1327
        }
1328
 
1329
        // Run through the answers.
1330
        $answers = $data['#']['answer'];
1331
        $a_count = 0;
1332
        $extraanswersfields = $this->extra_answer_fields();
1333
        if (is_array($extraanswersfields)) {
1334
            array_shift($extraanswersfields);
1335
        }
1336
        foreach ($answers as $answer) {
1337
            $ans = $format->import_answer($answer);
1338
            if (!$this->has_html_answers()) {
1339
                $qo->answer[$a_count] = $ans->answer['text'];
1340
            } else {
1341
                $qo->answer[$a_count] = $ans->answer;
1342
            }
1343
            $qo->fraction[$a_count] = $ans->fraction;
1344
            $qo->feedback[$a_count] = $ans->feedback;
1345
            if (is_array($extraanswersfields)) {
1346
                foreach ($extraanswersfields as $field) {
1347
                    $qo->{$field}[$a_count] =
1348
                        $format->getpath($answer, array('#', $field, 0, '#'), '');
1349
                }
1350
            }
1351
            ++$a_count;
1352
        }
1353
        return $qo;
1354
    }
1355
 
1356
    /*
1357
     * Export question to the Moodle XML format
1358
     *
1359
     * Export question using information from extra_question_fields function
1360
     * If some of you fields contains id's you'll need to reimplement this
1361
     */
1362
    public function export_to_xml($question, qformat_xml $format, $extra=null) {
1363
        $extraquestionfields = $this->extra_question_fields();
1364
        if (!is_array($extraquestionfields)) {
1365
            return false;
1366
        }
1367
 
1368
        // Omit table name.
1369
        array_shift($extraquestionfields);
1370
        $expout='';
1371
        foreach ($extraquestionfields as $field) {
1372
            $exportedvalue = $format->xml_escape($question->options->$field);
1373
            $expout .= "    <{$field}>{$exportedvalue}</{$field}>\n";
1374
        }
1375
 
1376
        $extraanswersfields = $this->extra_answer_fields();
1377
        if (is_array($extraanswersfields)) {
1378
            array_shift($extraanswersfields);
1379
        }
1380
        foreach ($question->options->answers as $answer) {
1381
            $extra = '';
1382
            if (is_array($extraanswersfields)) {
1383
                foreach ($extraanswersfields as $field) {
1384
                    $exportedvalue = $format->xml_escape($answer->$field);
1385
                    $extra .= "      <{$field}>{$exportedvalue}</{$field}>\n";
1386
                }
1387
            }
1388
 
1389
            $expout .= $format->write_answer($answer, $extra);
1390
        }
1391
        return $expout;
1392
    }
1393
 
1394
    /**
1395
     * Abstract function implemented by each question type. It runs all the code
1396
     * required to set up and save a question of any type for testing purposes.
1397
     * Alternate DB table prefix may be used to facilitate data deletion.
1398
     */
1399
    public function generate_test($name, $courseid=null) {
1400
        $form = new stdClass();
1401
        $form->name = $name;
1402
        $form->questiontextformat = 1;
1403
        $form->questiontext = 'test question, generated by script';
1404
        $form->defaultmark = 1;
1405
        $form->penalty = 0.3333333;
1406
        $form->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
1407
        $form->generalfeedback = "Well done";
1408
 
1409
        $context = context_course::instance($courseid);
1410
        $newcategory = question_make_default_categories(array($context));
1411
        $form->category = $newcategory->id . ',1';
1412
 
1413
        $question = new stdClass();
1414
        $question->courseid = $courseid;
1415
        $question->qtype = $this->name();
1416
        return array($form, $question);
1417
    }
1418
 
1419
    /**
1420
     * Get question context by category id
1421
     * @param int $category
1422
     * @return object $context
1423
     */
1424
    protected function get_context_by_category_id($category) {
1425
        global $DB;
1426
        $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
1427
        $context = context::instance_by_id($contextid, IGNORE_MISSING);
1428
        return $context;
1429
    }
1430
 
1431
    /**
1432
     * Save the file belonging to one text field.
1433
     *
1434
     * @param array $field the data from the form (or from import). This will
1435
     *      normally have come from the formslib editor element, so it will be an
1436
     *      array with keys 'text', 'format' and 'itemid'. However, when we are
1437
     *      importing, it will be an array with keys 'text', 'format' and 'files'
1438
     * @param object $context the context the question is in.
1439
     * @param string $component indentifies the file area question.
1440
     * @param string $filearea indentifies the file area questiontext,
1441
     *      generalfeedback, answerfeedback, etc.
1442
     * @param int $itemid identifies the file area.
1443
     *
1444
     * @return string the text for this field, after files have been processed.
1445
     */
1446
    protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1447
        if (!empty($field['itemid'])) {
1448
            // This is the normal case. We are safing the questions editing form.
1449
            return file_save_draft_area_files($field['itemid'], $context->id, $component,
1450
                    $filearea, $itemid, $this->fileoptions, trim($field['text']));
1451
 
1452
        } else if (!empty($field['files'])) {
1453
            // This is the case when we are doing an import.
1454
            foreach ($field['files'] as $file) {
1455
                $this->import_file($context, $component,  $filearea, $itemid, $file);
1456
            }
1457
        }
1458
        return trim($field['text']);
1459
    }
1460
 
1461
    /**
1462
     * Move all the files belonging to this question from one context to another.
1463
     * @param int $questionid the question being moved.
1464
     * @param int $oldcontextid the context it is moving from.
1465
     * @param int $newcontextid the context it is moving to.
1466
     */
1467
    public function move_files($questionid, $oldcontextid, $newcontextid) {
1468
        $fs = get_file_storage();
1469
        $fs->move_area_files_to_new_context($oldcontextid,
1470
                $newcontextid, 'question', 'questiontext', $questionid);
1471
        $fs->move_area_files_to_new_context($oldcontextid,
1472
                $newcontextid, 'question', 'generalfeedback', $questionid);
1473
    }
1474
 
1475
    /**
1476
     * Move all the files belonging to this question's answers when the question
1477
     * is moved from one context to another.
1478
     * @param int $questionid the question being moved.
1479
     * @param int $oldcontextid the context it is moving from.
1480
     * @param int $newcontextid the context it is moving to.
1481
     * @param bool $answerstoo whether there is an 'answer' question area,
1482
     *      as well as an 'answerfeedback' one. Default false.
1483
     */
1484
    protected function move_files_in_answers($questionid, $oldcontextid,
1485
            $newcontextid, $answerstoo = false) {
1486
        global $DB;
1487
        $fs = get_file_storage();
1488
 
1489
        $answerids = $DB->get_records_menu('question_answers',
1490
                array('question' => $questionid), 'id', 'id,1');
1491
        foreach ($answerids as $answerid => $notused) {
1492
            if ($answerstoo) {
1493
                $fs->move_area_files_to_new_context($oldcontextid,
1494
                        $newcontextid, 'question', 'answer', $answerid);
1495
            }
1496
            $fs->move_area_files_to_new_context($oldcontextid,
1497
                    $newcontextid, 'question', 'answerfeedback', $answerid);
1498
        }
1499
    }
1500
 
1501
    /**
1502
     * Move all the files belonging to this question's hints when the question
1503
     * is moved from one context to another.
1504
     * @param int $questionid the question being moved.
1505
     * @param int $oldcontextid the context it is moving from.
1506
     * @param int $newcontextid the context it is moving to.
1507
     * @param bool $answerstoo whether there is an 'answer' question area,
1508
     *      as well as an 'answerfeedback' one. Default false.
1509
     */
1510
    protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1511
        global $DB;
1512
        $fs = get_file_storage();
1513
 
1514
        $hintids = $DB->get_records_menu('question_hints',
1515
                array('questionid' => $questionid), 'id', 'id,1');
1516
        foreach ($hintids as $hintid => $notused) {
1517
            $fs->move_area_files_to_new_context($oldcontextid,
1518
                    $newcontextid, 'question', 'hint', $hintid);
1519
        }
1520
    }
1521
 
1522
    /**
1523
     * Move all the files belonging to this question's answers when the question
1524
     * is moved from one context to another.
1525
     * @param int $questionid the question being moved.
1526
     * @param int $oldcontextid the context it is moving from.
1527
     * @param int $newcontextid the context it is moving to.
1528
     * @param bool $answerstoo whether there is an 'answer' question area,
1529
     *      as well as an 'answerfeedback' one. Default false.
1530
     */
1531
    protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1532
            $newcontextid) {
1533
        global $DB;
1534
        $fs = get_file_storage();
1535
 
1536
        $fs->move_area_files_to_new_context($oldcontextid,
1537
                $newcontextid, 'question', 'correctfeedback', $questionid);
1538
        $fs->move_area_files_to_new_context($oldcontextid,
1539
                $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1540
        $fs->move_area_files_to_new_context($oldcontextid,
1541
                $newcontextid, 'question', 'incorrectfeedback', $questionid);
1542
    }
1543
 
1544
    /**
1545
     * Delete all the files belonging to this question.
1546
     * @param int $questionid the question being deleted.
1547
     * @param int $contextid the context the question is in.
1548
     */
1549
    protected function delete_files($questionid, $contextid) {
1550
        $fs = get_file_storage();
1551
        $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1552
        $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1553
    }
1554
 
1555
    /**
1556
     * Delete all the files belonging to this question's answers.
1557
     * @param int $questionid the question being deleted.
1558
     * @param int $contextid the context the question is in.
1559
     * @param bool $answerstoo whether there is an 'answer' question area,
1560
     *      as well as an 'answerfeedback' one. Default false.
1561
     */
1562
    protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1563
        global $DB;
1564
        $fs = get_file_storage();
1565
 
1566
        $answerids = $DB->get_records_menu('question_answers',
1567
                array('question' => $questionid), 'id', 'id,1');
1568
        foreach ($answerids as $answerid => $notused) {
1569
            if ($answerstoo) {
1570
                $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1571
            }
1572
            $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1573
        }
1574
    }
1575
 
1576
    /**
1577
     * Delete all the files belonging to this question's hints.
1578
     * @param int $questionid the question being deleted.
1579
     * @param int $contextid the context the question is in.
1580
     */
1581
    protected function delete_files_in_hints($questionid, $contextid) {
1582
        global $DB;
1583
        $fs = get_file_storage();
1584
 
1585
        $hintids = $DB->get_records_menu('question_hints',
1586
                array('questionid' => $questionid), 'id', 'id,1');
1587
        foreach ($hintids as $hintid => $notused) {
1588
            $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1589
        }
1590
    }
1591
 
1592
    /**
1593
     * Delete all the files belonging to this question's answers.
1594
     * @param int $questionid the question being deleted.
1595
     * @param int $contextid the context the question is in.
1596
     * @param bool $answerstoo whether there is an 'answer' question area,
1597
     *      as well as an 'answerfeedback' one. Default false.
1598
     */
1599
    protected function delete_files_in_combined_feedback($questionid, $contextid) {
1600
        global $DB;
1601
        $fs = get_file_storage();
1602
 
1603
        $fs->delete_area_files($contextid,
1604
                'question', 'correctfeedback', $questionid);
1605
        $fs->delete_area_files($contextid,
1606
                'question', 'partiallycorrectfeedback', $questionid);
1607
        $fs->delete_area_files($contextid,
1608
                'question', 'incorrectfeedback', $questionid);
1609
    }
1610
 
1611
    public function import_file($context, $component, $filearea, $itemid, $file) {
1612
        $fs = get_file_storage();
1613
        $record = new stdClass();
1614
        if (is_object($context)) {
1615
            $record->contextid = $context->id;
1616
        } else {
1617
            $record->contextid = $context;
1618
        }
1619
        $record->component = $component;
1620
        $record->filearea  = $filearea;
1621
        $record->itemid    = $itemid;
1622
        $record->filename  = $file->name;
1623
        $record->filepath  = '/';
1624
        return $fs->create_file_from_string($record, $this->decode_file($file));
1625
    }
1626
 
1627
    protected function decode_file($file) {
1628
        switch ($file->encoding) {
1629
            case 'base64':
1630
            default:
1631
                return base64_decode($file->content);
1632
        }
1633
    }
1634
}
1635
 
1636
 
1637
/**
1638
 * This class is used in the return value from
1639
 * {@link question_type::get_possible_responses()}.
1640
 *
1641
 * @copyright  2010 The Open University
1642
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1643
 */
1644
class question_possible_response {
1645
    /**
1646
     * @var string the classification of this response the student gave to this
1647
     * part of the question. Must match one of the responseclasses returned by
1648
     * {@link question_type::get_possible_responses()}.
1649
     */
1650
    public $responseclass;
1651
 
1652
    /** @var string the (partial) credit awarded for this responses. */
1653
    public $fraction;
1654
 
1655
    /**
1656
     * Constructor, just an easy way to set the fields.
1657
     * @param string $responseclassid see the field descriptions above.
1658
     * @param string $response see the field descriptions above.
1659
     * @param number $fraction see the field descriptions above.
1660
     */
1661
    public function __construct($responseclass, $fraction) {
1662
        $this->responseclass = $responseclass;
1663
        $this->fraction = $fraction;
1664
    }
1665
 
1666
    public static function no_response() {
1667
        return new question_possible_response(get_string('noresponse', 'question'), 0);
1668
    }
1669
}