Proyectos de Subversion Moodle

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Code for handling and processing questions.
19
 *
20
 * This is code that is module independent, i.e., can be used by any module that
21
 * uses questions, like quiz, lesson, etc.
22
 * This script also loads the questiontype classes.
23
 * Code for handling the editing of questions is in question/editlib.php
24
 *
25
 * @package    core
26
 * @subpackage questionbank
27
 * @copyright  1999 onwards Martin Dougiamas and others {@link http://moodle.com}
28
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29
 */
30
 
31
use core_question\local\bank\question_version_status;
32
use core_question\question_reference_manager;
33
 
34
defined('MOODLE_INTERNAL') || die();
35
 
36
require_once($CFG->dirroot . '/question/engine/lib.php');
37
require_once($CFG->dirroot . '/question/type/questiontypebase.php');
38
 
39
 
40
 
41
// CONSTANTS.
42
 
43
/**
44
 * Constant determines the number of answer boxes supplied in the editing
45
 * form for multiple choice and similar question types.
46
 */
47
define("QUESTION_NUMANS", 10);
48
 
49
/**
50
 * Constant determines the number of answer boxes supplied in the editing
51
 * form for multiple choice and similar question types to start with, with
52
 * the option of adding QUESTION_NUMANS_ADD more answers.
53
 */
54
define("QUESTION_NUMANS_START", 3);
55
 
56
/**
57
 * Constant determines the number of answer boxes to add in the editing
58
 * form for multiple choice and similar question types when the user presses
59
 * 'add form fields button'.
60
 */
61
define("QUESTION_NUMANS_ADD", 3);
62
 
63
/**
64
 * Move one question type in a list of question types. If you try to move one element
65
 * off of the end, nothing will change.
66
 *
67
 * @param array $sortedqtypes An array $qtype => anything.
68
 * @param string $tomove one of the keys from $sortedqtypes
69
 * @param integer $direction +1 or -1
70
 * @return array an array $index => $qtype, with $index from 0 to n in order, and
71
 *      the $qtypes in the same order as $sortedqtypes, except that $tomove will
72
 *      have been moved one place.
73
 */
74
function question_reorder_qtypes($sortedqtypes, $tomove, $direction): array {
75
    $neworder = array_keys($sortedqtypes);
76
    // Find the element to move.
77
    $key = array_search($tomove, $neworder);
78
    if ($key === false) {
79
        return $neworder;
80
    }
81
    // Work out the other index.
82
    $otherkey = $key + $direction;
83
    if (!isset($neworder[$otherkey])) {
84
        return $neworder;
85
    }
86
    // Do the swap.
87
    $swap = $neworder[$otherkey];
88
    $neworder[$otherkey] = $neworder[$key];
89
    $neworder[$key] = $swap;
90
    return $neworder;
91
}
92
 
93
/**
94
 * Save a new question type order to the config_plugins table.
95
 *
96
 * @param array $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
97
 * @param object $config get_config('question'), if you happen to have it around, to save one DB query.
98
 */
99
function question_save_qtype_order($neworder, $config = null): void {
100
    if (is_null($config)) {
101
        $config = get_config('question');
102
    }
103
 
104
    foreach ($neworder as $index => $qtype) {
105
        $sortvar = $qtype . '_sortorder';
106
        if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
107
            set_config($sortvar, $index + 1, 'question');
108
        }
109
    }
110
}
111
 
112
// FUNCTIONS.
113
 
114
/**
115
 * Check if the question is used.
116
 *
117
 * @param array $questionids of question ids.
118
 * @return boolean whether any of these questions are being used by any part of Moodle.
119
 */
120
function questions_in_use($questionids): bool {
121
 
122
    // Are they used by the core question system?
123
    if (question_engine::questions_in_use($questionids)) {
124
        return true;
125
    }
126
 
127
    if (question_reference_manager::questions_with_references($questionids)) {
128
        return true;
129
    }
130
 
131
    // Check if any plugins are using these questions.
132
    $callbacksbytype = get_plugins_with_function('questions_in_use');
133
    foreach ($callbacksbytype as $callbacks) {
134
        foreach ($callbacks as $function) {
135
            if ($function($questionids)) {
136
                return true;
137
            }
138
        }
139
    }
140
 
141
    // Finally check legacy callback.
142
    $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
143
    foreach ($legacycallbacks as $plugin => $function) {
144
        debugging($plugin . ' implements deprecated method ' . $function .
145
                '. ' . $plugin . '_questions_in_use should be implemented instead.', DEBUG_DEVELOPER);
146
 
147
        if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
148
            continue; // Already done.
149
        }
150
 
151
        foreach ($questionids as $questionid) {
152
            if (!empty($function($questionid))) {
153
                return true;
154
            }
155
        }
156
    }
157
 
158
    return false;
159
}
160
 
161
/**
162
 * Determine whether there are any questions belonging to this context, that is whether any of its
163
 * question categories contain any questions. This will return true even if all the questions are
164
 * hidden.
165
 *
166
 * @param mixed $context either a context object, or a context id.
167
 * @return boolean whether any of the question categories beloning to this context have
168
 *         any questions in them.
169
 */
170
function question_context_has_any_questions($context): bool {
171
    global $DB;
172
    if (is_object($context)) {
173
        $contextid = $context->id;
174
    } else if (is_numeric($context)) {
175
        $contextid = $context;
176
    } else {
177
        throw new moodle_exception('invalidcontextinhasanyquestions', 'question');
178
    }
179
    $sql = 'SELECT qbe.*
180
              FROM {question_bank_entries} qbe
181
              JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
182
             WHERE qc.contextid = ?';
183
    return $DB->record_exists_sql($sql, [$contextid]);
184
}
185
 
186
/**
187
 * Check whether a given grade is one of a list of allowed options. If not,
188
 * depending on $matchgrades, either return the nearest match, or return false
189
 * to signal an error.
190
 *
191
 * @param array $gradeoptionsfull list of valid options
192
 * @param int $grade grade to be tested
193
 * @param string $matchgrades 'error' or 'nearest'
194
 * @return false|int|string either 'fixed' value or false if error.
195
 */
196
function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
197
 
198
    if ($matchgrades == 'error') {
199
        // ...(Almost) exact match, or an error.
200
        foreach ($gradeoptionsfull as $value => $option) {
201
            // Slightly fuzzy test, never check floats for equality.
202
            if (abs($grade - $value) < 0.00001) {
203
                return $value; // Be sure the return the proper value.
204
            }
205
        }
206
        // Didn't find a match so that's an error.
207
        return false;
208
 
209
    } else if ($matchgrades == 'nearest') {
210
        // Work out nearest value.
211
        $best = false;
212
        $bestmismatch = 2;
213
        foreach ($gradeoptionsfull as $value => $option) {
214
            $newmismatch = abs($grade - $value);
215
            if ($newmismatch < $bestmismatch) {
216
                $best = $value;
217
                $bestmismatch = $newmismatch;
218
            }
219
        }
220
        return $best;
221
 
222
    } else {
223
        // Unknow option passed.
224
        throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
225
                ' passed to match_grade_options');
226
    }
227
}
228
 
229
/**
230
 * Category is about to be deleted,
231
 * 1/ All questions are deleted for this question category.
232
 * 2/ Any questions that can't be deleted are moved to a new category
233
 * NOTE: this function is called from lib/db/upgrade.php
234
 *
235
 * @param object|core_course_category $category course category object
236
 */
237
function question_category_delete_safe($category): void {
238
    global $DB;
239
    $criteria = ['questioncategoryid' => $category->id];
240
    $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
241
    $rescue = null; // See the code around the call to question_save_from_deletion.
242
 
243
    // Deal with any questions in the category.
244
    if ($questionentries = $DB->get_records('question_bank_entries', $criteria, '', 'id')) {
245
 
246
        foreach ($questionentries as $questionentry) {
247
            $questionids = $DB->get_records('question_versions',
248
                                                ['questionbankentryid' => $questionentry->id], '', 'questionid');
249
 
250
            // Try to delete each question.
251
            foreach ($questionids as $questionid) {
252
                question_delete_question($questionid->questionid, $category->contextid);
253
            }
254
        }
255
 
256
        // Check to see if there were any questions that were kept because
257
        // they are still in use somehow, even though quizzes in courses
258
        // in this category will already have been deleted. This could
259
        // happen, for example, if questions are added to a course,
260
        // and then that course is moved to another category (MDL-14802).
261
        $questionids = [];
262
        foreach ($questionentries as $questionentry) {
263
            $versions = $DB->get_records('question_versions', ['questionbankentryid' => $questionentry->id], '', 'questionid');
264
            foreach ($versions as $key => $version) {
265
                $questionids[$key] = $version;
266
            }
267
        }
268
        if (!empty($questionids)) {
269
            $parentcontextid = SYSCONTEXTID;
270
            $name = get_string('unknown', 'question');
271
            if ($context !== false) {
272
                $name = $context->get_context_name();
273
                $parentcontext = $context->get_parent_context();
274
                if ($parentcontext) {
275
                    $parentcontextid = $parentcontext->id;
276
                }
277
            }
278
            question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
279
        }
280
    }
281
 
282
    // Now delete the category.
283
    $DB->delete_records('question_categories', ['id' => $category->id]);
284
}
285
 
286
/**
287
 * Tests whether any question in a category is used by any part of Moodle.
288
 *
289
 * @param integer $categoryid a question category id.
290
 * @param boolean $recursive whether to check child categories too.
291
 * @return boolean whether any question in this category is in use.
292
 */
293
function question_category_in_use($categoryid, $recursive = false): bool {
294
    global $DB;
295
 
296
    // Look at each question in the category.
297
    $questionids = question_bank::get_finder()->get_questions_from_categories([$categoryid], null);
298
    if ($questionids) {
299
        if (questions_in_use(array_keys($questionids))) {
300
            return true;
301
        }
302
    }
303
    if (!$recursive) {
304
        return false;
305
    }
306
 
307
    // Look under child categories recursively.
308
    if ($children = $DB->get_records('question_categories',
309
            ['parent' => $categoryid], '', 'id, 1')) {
310
        foreach ($children as $child) {
311
            if (question_category_in_use($child->id, $recursive)) {
312
                return true;
313
            }
314
        }
315
    }
316
 
317
    return false;
318
}
319
 
320
/**
321
 * Check if there is more versions left for the entry.
322
 * If not delete the entry.
323
 *
324
 * @param int $entryid
325
 */
326
function delete_question_bank_entry($entryid): void {
327
    global $DB;
328
    if (!$DB->record_exists('question_versions', ['questionbankentryid' => $entryid])) {
329
        $DB->delete_records('question_bank_entries', ['id' => $entryid]);
330
    }
331
}
332
 
333
/**
334
 * Deletes question and all associated data from the database
335
 *
336
 * It will not delete a question if it is used somewhere, instead it will just delete the reference.
337
 *
338
 * @param int $questionid The id of the question being deleted
339
 */
340
function question_delete_question($questionid): void {
341
    global $DB;
342
 
343
    $question = $DB->get_record('question', ['id' => $questionid]);
344
    if (!$question) {
345
        // In some situations, for example if this was a child of a
346
        // Cloze question that was previously deleted, the question may already
347
        // have gone. In this case, just do nothing.
348
        return;
349
    }
350
 
351
    $sql = 'SELECT qv.id as versionid,
352
                   qv.version,
353
                   qbe.id as entryid,
354
                   qc.id as categoryid,
355
                   ctx.id as contextid
356
              FROM {question} q
357
              LEFT JOIN {question_versions} qv ON qv.questionid = q.id
358
              LEFT JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
359
              LEFT JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
360
              LEFT JOIN {context} ctx ON ctx.id = qc.contextid
361
             WHERE q.id = ?';
362
    $questiondata = $DB->get_record_sql($sql, [$question->id]);
363
 
364
    $questionstocheck = [$question->id];
365
 
366
    if ($question->parent) {
367
        $questionstocheck[] = $question->parent;
368
    }
369
 
370
    // Do not delete a question if it is used by an activity module. Just mark the version hidden.
371
    if (questions_in_use($questionstocheck)) {
372
        $DB->set_field('question_versions', 'status',
373
                question_version_status::QUESTION_STATUS_HIDDEN, ['questionid' => $questionid]);
374
        return;
375
    }
376
 
377
    // This sometimes happens in old sites with bad data.
378
    if (!$questiondata->contextid) {
379
        debugging('Deleting question ' . $question->id . ' which is no longer linked to a context. ' .
380
            'Assuming system context to avoid errors, but this may mean that some data like files, ' .
381
            'tags, are not cleaned up.');
382
        $questiondata->contextid = context_system::instance()->id;
383
        $questiondata->categoryid = 0;
384
    }
385
 
386
    // Delete previews of the question.
387
    $dm = new question_engine_data_mapper();
388
    $dm->delete_previews($question->id);
389
 
390
    // Delete questiontype-specific data.
391
    question_bank::get_qtype($question->qtype, false)->delete_question($question->id, $questiondata->contextid);
392
 
393
    // Now recursively delete all child questions
394
    if ($children = $DB->get_records('question',
395
            array('parent' => $questionid), '', 'id, qtype')) {
396
        foreach ($children as $child) {
397
            if ($child->id != $questionid) {
398
                question_delete_question($child->id);
399
            }
400
        }
401
    }
402
 
403
    // Finally delete the question record itself.
404
    $DB->delete_records('question', ['id' => $question->id]);
405
    $DB->delete_records('question_versions', ['id' => $questiondata->versionid]);
406
    $DB->delete_records('question_references',
407
        [
408
            'version' => $questiondata->version,
409
            'questionbankentryid' => $questiondata->entryid,
410
        ]);
411
    delete_question_bank_entry($questiondata->entryid);
412
    question_bank::notify_question_edited($question->id);
413
 
414
    // Log the deletion of this question.
415
    // Any qbank plugins storing additional question data should observe this event and perform the necessary deletion.
416
    $question->category = $questiondata->categoryid;
417
    $question->contextid = $questiondata->contextid;
418
    $event = \core\event\question_deleted::create_from_question_instance($question);
419
    $event->add_record_snapshot('question', $question);
420
    $event->trigger();
421
}
422
 
423
/**
424
 * All question categories and their questions are deleted for this context id.
425
 *
426
 * @param int $contextid The contextid to delete question categories from
427
 * @return array only returns an empty array for backwards compatibility.
428
 */
429
function question_delete_context($contextid): array {
430
    global $DB;
431
 
432
    $fields = 'id, parent, name, contextid';
433
    if ($categories = $DB->get_records('question_categories', ['contextid' => $contextid], 'parent', $fields)) {
434
        // Sort categories following their tree (parent-child) relationships this will make the feedback more readable.
435
        $categories = sort_categories_by_tree($categories);
436
        foreach ($categories as $category) {
437
            question_category_delete_safe($category);
438
        }
439
    }
440
    return [];
441
}
442
 
443
/**
444
 * All question categories and their questions are deleted for this course.
445
 *
446
 * @param stdClass $course an object representing the activity
447
 * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
448
 * @return bool always true.
449
 */
450
function question_delete_course($course, $notused = false): bool {
451
    $coursecontext = context_course::instance($course->id);
452
    question_delete_context($coursecontext->id);
453
    return true;
454
}
455
 
456
/**
457
 * Category is about to be deleted,
458
 * 1/ All question categories and their questions are deleted for this course category.
459
 * 2/ All questions are moved to new category
460
 *
461
 * @param stdClass|core_course_category $category course category object
462
 * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
463
 *      category where content moved
464
 * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
465
 * @return boolean
466
 */
467
function question_delete_course_category($category, $newcategory, $notused=false): bool {
468
    global $DB;
469
 
470
    $context = context_coursecat::instance($category->id);
471
    if (empty($newcategory)) {
472
        question_delete_context($context->id);
473
 
474
    } else {
475
        // Move question categories to the new context.
476
        if (!$newcontext = context_coursecat::instance($newcategory->id)) {
477
            return false;
478
        }
479
 
480
        // Only move question categories if there is any question category at all!
481
        if ($topcategory = question_get_top_category($context->id)) {
482
            $newtopcategory = question_get_top_category($newcontext->id, true);
483
 
484
            question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
485
            $DB->set_field('question_categories', 'parent', $newtopcategory->id, ['parent' => $topcategory->id]);
486
            // Now delete the top category.
487
            $DB->delete_records('question_categories', ['id' => $topcategory->id]);
488
        }
489
    }
490
 
491
    return true;
492
}
493
 
494
/**
495
 * Creates a new category to save the questions in use.
496
 *
497
 * @param array $questionids of question ids
498
 * @param int $newcontextid the context to create the saved category in.
499
 * @param string $oldplace a textual description of the think being deleted,
500
 *      e.g. from get_context_name
501
 * @param object $newcategory
502
 * @return mixed false on
503
 */
504
function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
505
    global $DB;
506
 
507
    // Make a category in the parent context to move the questions to.
508
    if (is_null($newcategory)) {
509
        $newcategory = new stdClass();
510
        $newcategory->parent = question_get_top_category($newcontextid, true)->id;
511
        $newcategory->contextid = $newcontextid;
512
        // Max length of column name in question_categories is 255.
513
        $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
514
        $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
515
        $newcategory->sortorder = 999;
516
        $newcategory->stamp = make_unique_id_code();
517
        $newcategory->id = $DB->insert_record('question_categories', $newcategory);
518
    }
519
 
520
    // Move any remaining questions to the 'saved' category.
521
    if (!question_move_questions_to_category($questionids, $newcategory->id)) {
522
        return false;
523
    }
524
    return $newcategory;
525
}
526
 
527
/**
528
 * All question categories and their questions are deleted for this activity.
529
 *
530
 * @param object $cm the course module object representing the activity
531
 * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
532
 * @return boolean
533
 */
534
function question_delete_activity($cm, $notused = false): bool {
535
    $modcontext = context_module::instance($cm->id);
536
    question_delete_context($modcontext->id);
537
    return true;
538
}
539
 
540
/**
541
 * This function will handle moving all tag instances to a new context for a
542
 * given list of questions.
543
 *
544
 * Questions can be tagged in up to two contexts:
545
 * 1.) The context the question exists in.
546
 * 2.) The course context (if the question context is a higher context.
547
 *     E.g. course category context or system context.
548
 *
549
 * This means a question that exists in a higher context (e.g. course cat or
550
 * system context) may have multiple groups of tags in any number of child
551
 * course contexts.
552
 *
553
 * Questions in the course category context can be move "down" a context level
554
 * into one of their child course contexts or activity contexts which affects the
555
 * availability of that question in other courses / activities.
556
 *
557
 * In this case it makes the questions no longer available in the other course or
558
 * activity contexts so we need to make sure that the tag instances in those other
559
 * contexts are removed.
560
 *
561
 * @param stdClass[] $questions The list of question being moved (must include
562
 *                              the id and contextid)
563
 * @param context $newcontext The Moodle context the questions are being moved to
564
 */
565
function question_move_question_tags_to_new_context(array $questions, context $newcontext): void {
566
    // If the questions are moving to a new course/activity context then we need to
567
    // find any existing tag instances from any unavailable course contexts and
568
    // delete them because they will no longer be applicable (we don't support
569
    // tagging questions across courses).
570
    $instancestodelete = [];
571
    $instancesfornewcontext = [];
572
    $newcontextparentids = $newcontext->get_parent_context_ids();
573
    $questionids = array_map(function($question) {
574
        return $question->id;
575
    }, $questions);
576
    $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
577
 
578
    foreach ($questions as $question) {
579
        $tagobjects = $questionstagobjects[$question->id] ?? [];
580
 
581
        foreach ($tagobjects as $tagobject) {
582
            $tagid = $tagobject->taginstanceid;
583
            $tagcontextid = $tagobject->taginstancecontextid;
584
            $istaginnewcontext = $tagcontextid == $newcontext->id;
585
            $istaginquestioncontext = $tagcontextid == $question->contextid;
586
 
587
            if ($istaginnewcontext) {
588
                // This tag instance is already in the correct context so we can
589
                // ignore it.
590
                continue;
591
            }
592
 
593
            if ($istaginquestioncontext) {
594
                // This tag instance is in the question context so it needs to be
595
                // updated.
596
                $instancesfornewcontext[] = $tagid;
597
                continue;
598
            }
599
 
600
            // These tag instances are in neither the new context nor the
601
            // question context so we need to determine what to do based on
602
            // the context they are in and the new question context.
603
            $tagcontext = context::instance_by_id($tagcontextid);
604
            $tagcoursecontext = $tagcontext->get_course_context(false);
605
            // The tag is in a course context if get_course_context() returns
606
            // itself.
607
            $istaginstancecontextcourse = !empty($tagcoursecontext)
608
                && $tagcontext->id == $tagcoursecontext->id;
609
 
610
            if ($istaginstancecontextcourse) {
611
                // If the tag instance is in a course context we need to add some
612
                // special handling.
613
                $tagcontextparentids = $tagcontext->get_parent_context_ids();
614
                $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
615
                $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
616
 
617
                if ($isnewcontextaparent) {
618
                    // If the tag instance is a course context tag and the new
619
                    // context is still a parent context to the tag context then
620
                    // we can leave this tag where it is.
621
                    continue;
622
                } else if ($isnewcontextachild) {
623
                    // If the new context is a child context (e.g. activity) of this
624
                    // tag instance then we should move all of this tag instance
625
                    // down into the activity context along with the question.
626
                    $instancesfornewcontext[] = $tagid;
627
                } else {
628
                    // If the tag is in a course context that is no longer a parent
629
                    // or child of the new context then this tag instance should be
630
                    // removed.
631
                    $instancestodelete[] = $tagid;
632
                }
633
            } else {
634
                // This is a catch all for any tag instances not in the question
635
                // context or a course context. These tag instances should be
636
                // updated to the new context id. This will clean up old invalid
637
                // data.
638
                $instancesfornewcontext[] = $tagid;
639
            }
640
        }
641
    }
642
 
643
    if (!empty($instancestodelete)) {
644
        // Delete any course context tags that may no longer be valid.
645
        core_tag_tag::delete_instances_by_id($instancestodelete);
646
    }
647
 
648
    if (!empty($instancesfornewcontext)) {
649
        // Update the tag instances to the new context id.
650
        core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
651
    }
652
}
653
 
654
/**
655
 * Check if an idnumber exist in the category.
656
 *
657
 * @param int $questionidnumber
658
 * @param int $categoryid
659
 * @param int $limitfrom
660
 * @param int $limitnum
661
 * @return array
662
 */
663
function idnumber_exist_in_question_category($questionidnumber, $categoryid, $limitfrom = 0, $limitnum = 1): array {
664
    global $DB;
665
    $response  = false;
666
    $record = [];
667
    // Check if the idnumber exist in the category.
668
    $sql = 'SELECT qbe.idnumber
669
              FROM {question_bank_entries} qbe
670
             WHERE qbe.idnumber LIKE ?
671
               AND qbe.questioncategoryid = ?
672
          ORDER BY qbe.idnumber DESC';
673
    $questionrecord = $DB->record_exists_sql($sql, [$questionidnumber, $categoryid]);
674
    if ((string) $questionidnumber !== '' && $questionrecord) {
675
        $record = $DB->get_records_sql($sql, [$questionidnumber . '_%', $categoryid], 0, 1);
676
        $response  = true;
677
    }
678
 
679
    return [$response, $record];
680
}
681
 
682
/**
683
 * This function should be considered private to the question bank, it is called from
684
 * question/editlib.php question/contextmoveq.php and a few similar places to to the
685
 * work of actually moving questions and associated data. However, callers of this
686
 * function also have to do other work, which is why you should not call this method
687
 * directly from outside the questionbank.
688
 *
689
 * @param array $questionids of question ids.
690
 * @param integer $newcategoryid the id of the category to move to.
691
 * @return bool
692
 */
693
function question_move_questions_to_category($questionids, $newcategoryid): bool {
694
    global $DB;
695
 
696
    $newcategorydata = $DB->get_record('question_categories', ['id' => $newcategoryid]);
697
    if (!$newcategorydata) {
698
        return false;
699
    }
700
    list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
701
 
702
    $sql = "SELECT qv.id as versionid,
703
                   qbe.id as entryid,
704
                   qc.id as category,
705
                   qc.contextid as contextid,
706
                   q.id,
707
                   q.qtype,
708
                   qbe.idnumber
709
              FROM {question} q
710
              JOIN {question_versions} qv ON qv.questionid = q.id
711
              JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
712
              JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
713
             WHERE q.id $questionidcondition
714
                   OR (q.parent <> 0 AND q.parent $questionidcondition)";
715
 
716
    // Also, we need to move children questions.
717
    $params = array_merge($params, $params);
718
    $questions = $DB->get_records_sql($sql, $params);
719
    foreach ($questions as $question) {
720
        if ($newcategorydata->contextid != $question->contextid) {
721
            question_bank::get_qtype($question->qtype)->move_files(
722
                    $question->id, $question->contextid, $newcategorydata->contextid);
723
        }
724
        // Check whether there could be a clash of idnumbers in the new category.
725
        list($idnumberclash, $rec) = idnumber_exist_in_question_category($question->idnumber, $newcategoryid);
726
        if ($idnumberclash) {
727
            $unique = 1;
728
            if (count($rec)) {
729
                $rec = reset($rec);
730
                $idnumber = $rec->idnumber;
731
                if (strpos($idnumber, '_') !== false) {
732
                    $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
733
                }
734
            }
735
            // For the move process, add a numerical increment to the idnumber. This means that if a question is
736
            // mistakenly moved then the idnumber will not be completely lost.
737
            $qbankentry = new stdClass();
738
            $qbankentry->id = $question->entryid;
739
            $qbankentry->idnumber = $question->idnumber . '_' . $unique;
740
            $DB->update_record('question_bank_entries', $qbankentry);
741
        }
742
 
743
        // Update the entry to the new category id.
744
        $entry = new stdClass();
745
        $entry->id = $question->entryid;
746
        $entry->questioncategoryid = $newcategorydata->id;
747
        $DB->update_record('question_bank_entries', $entry);
748
 
749
        // Log this question move.
750
        $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
751
                ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategorydata->id]);
752
        $event->trigger();
753
    }
754
 
755
    $newcontext = context::instance_by_id($newcategorydata->contextid);
756
    question_move_question_tags_to_new_context($questions, $newcontext);
757
 
758
    // TODO Deal with datasets.
759
 
760
    // Purge these questions from the cache.
761
    foreach ($questions as $question) {
762
        question_bank::notify_question_edited($question->id);
763
    }
764
 
765
    return true;
766
}
767
 
768
/**
769
 * Update the questioncontextid field for all question_set_references records given a new context id
770
 *
771
 * @param int $oldcategoryid Old category to be moved.
772
 * @param int $newcatgoryid New category that will receive the questions.
773
 * @param int $oldcontextid Old context to be moved.
774
 * @param int $newcontextid New context that will receive the questions.
775
 * @param bool $delete If the action is delete.
776
 * @throws dml_exception
777
 */
778
function move_question_set_references(int $oldcategoryid, int $newcatgoryid,
779
                                      int $oldcontextid, int $newcontextid, bool $delete = false): void {
780
    global $DB;
781
 
782
    if ($delete || $oldcontextid !== $newcontextid) {
783
        $setreferences = $DB->get_recordset('question_set_references', ['questionscontextid' => $oldcontextid]);
784
        foreach ($setreferences as $setreference) {
785
            $filter = json_decode($setreference->filtercondition);
786
            if (isset($filter->questioncategoryid)) {
787
                if ((int)$filter->questioncategoryid === $oldcategoryid) {
788
                    $setreference->questionscontextid = $newcontextid;
789
                    if ($oldcategoryid !== $newcatgoryid) {
790
                        $filter->questioncategoryid = $newcatgoryid;
791
                        $setreference->filtercondition = json_encode($filter);
792
                    }
793
                    $DB->update_record('question_set_references', $setreference);
794
                }
795
            }
796
        }
797
        $setreferences->close();
798
    }
799
}
800
 
801
/**
802
 * This function helps move a question cateogry to a new context by moving all
803
 * the files belonging to all the questions to the new context.
804
 * Also moves subcategories.
805
 * @param integer $categoryid the id of the category being moved.
806
 * @param integer $oldcontextid the old context id.
807
 * @param integer $newcontextid the new context id.
808
 */
809
function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid): void {
810
    global $DB;
811
 
812
    $questions = [];
813
    $sql = "SELECT q.id, q.qtype
814
              FROM {question} q
815
              JOIN {question_versions} qv ON qv.questionid = q.id
816
              JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
817
             WHERE qbe.questioncategoryid = ?";
818
 
819
    $questionids = $DB->get_records_sql_menu($sql, [$categoryid]);
820
    foreach ($questionids as $questionid => $qtype) {
821
        question_bank::get_qtype($qtype)->move_files($questionid, $oldcontextid, $newcontextid);
822
        // Purge this question from the cache.
823
        question_bank::notify_question_edited($questionid);
824
 
825
        $questions[] = (object) [
826
            'id' => $questionid,
827
            'contextid' => $oldcontextid
828
        ];
829
    }
830
 
831
    $newcontext = context::instance_by_id($newcontextid);
832
    question_move_question_tags_to_new_context($questions, $newcontext);
833
 
834
    $subcatids = $DB->get_records_menu('question_categories', ['parent' => $categoryid], '', 'id,1');
835
    foreach ($subcatids as $subcatid => $notused) {
836
        $DB->set_field('question_categories', 'contextid', $newcontextid, ['id' => $subcatid]);
837
        question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
838
    }
839
}
840
 
841
/**
842
 * Given a list of ids, load the basic information about a set of questions from
843
 * the questions table. The $join and $extrafields arguments can be used together
844
 * to pull in extra data. See, for example, the usage in {@see \mod_quiz\quiz_attempt}, and
845
 * read the code below to see how the SQL is assembled. Throws exceptions on error.
846
 *
847
 * @param array $questionids array of question ids to load. If null, then all
848
 * questions matched by $join will be loaded.
849
 * @param string $extrafields extra SQL code to be added to the query.
850
 * @param string $join extra SQL code to be added to the query.
851
 * @param array $extraparams values for any placeholders in $join.
852
 * You must use named placeholders.
853
 * @param string $orderby what to order the results by. Optional, default is unspecified order.
854
 *
855
 * @return array partially complete question objects. You need to call get_question_options
856
 * on them before they can be properly used.
857
 */
858
function question_preload_questions($questionids = null, $extrafields = '', $join = '', $extraparams = [], $orderby = ''): array {
859
    global $DB;
860
 
861
    if ($questionids === null) {
862
        $extracondition = '';
863
        $params = [];
864
    } else {
865
        if (empty($questionids)) {
866
            return [];
867
        }
868
 
869
        list($questionidcondition, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED, 'qid0000');
870
        $extracondition = 'WHERE q.id ' . $questionidcondition;
871
    }
872
 
873
    if ($join) {
874
        $join = 'JOIN ' . $join;
875
    }
876
 
877
    if ($extrafields) {
878
        $extrafields = ', ' . $extrafields;
879
    }
880
 
881
    if ($orderby) {
882
        $orderby = 'ORDER BY ' . $orderby;
883
    }
884
 
885
    $sql = "SELECT q.*,
886
                   qc.id as category,
887
                   qv.status,
888
                   qv.id as versionid,
889
                   qv.version,
890
                   qv.questionbankentryid,
891
                   qc.contextid as contextid
892
                   {$extrafields}
893
              FROM {question} q
894
              JOIN {question_versions} qv
895
                ON qv.questionid = q.id
896
              JOIN {question_bank_entries} qbe
897
                ON qbe.id = qv.questionbankentryid
898
              JOIN {question_categories} qc
899
                ON qc.id = qbe.questioncategoryid
900
              {$join}
901
              {$extracondition}
902
              {$orderby}";
903
 
904
    // Load the questions.
905
    $questions = $DB->get_records_sql($sql, $extraparams + $params);
906
    foreach ($questions as $question) {
907
        $question->_partiallyloaded = true;
908
    }
909
 
910
    return $questions;
911
}
912
 
913
/**
914
 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
915
 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
916
 * read the code below to see how the SQL is assembled. Throws exceptions on error.
917
 *
918
 * @param array $questionids array of question ids.
919
 * @param string $extrafields extra SQL code to be added to the query.
920
 * @param string $join extra SQL code to be added to the query.
921
 * @return array|string question objects.
922
 */
923
function question_load_questions($questionids, $extrafields = '', $join = '') {
924
    $questions = question_preload_questions($questionids, $extrafields, $join);
925
 
926
    // Load the question type specific information.
927
    if (!get_question_options($questions)) {
928
        return get_string('questionloaderror', 'question');
929
    }
930
 
931
    return $questions;
932
}
933
 
934
/**
935
 * Private function to factor common code out of get_question_options().
936
 *
937
 * @param object $question the question to tidy.
938
 * @param stdClass $category The question_categories record for the given $question.
939
 * @param \core_tag_tag[]|null $tagobjects The tags for the given $question.
940
 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
941
 */
942
function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null): void {
943
    // Convert numeric fields to float. This prevents these being displayed as 1.0000000.
944
    $question->defaultmark += 0;
945
    $question->penalty += 0;
946
 
947
    // Indicate the question is now fully initialised.
948
    if (isset($question->_partiallyloaded)) {
949
        unset($question->_partiallyloaded);
950
    }
951
 
952
    $question->categoryobject = $category;
953
 
954
    // Add any tags we have been passed.
955
    if (!is_null($tagobjects)) {
956
        $categorycontext = context::instance_by_id($category->contextid);
957
        $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
958
        $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
959
        $question->coursetags = $sortedtagobjects->coursetags;
960
        $question->tagobjects = $sortedtagobjects->tagobjects;
961
        $question->tags = $sortedtagobjects->tags;
962
    }
963
 
964
    // Load question-type specific fields.
965
    if (question_bank::is_qtype_installed($question->qtype)) {
966
        question_bank::get_qtype($question->qtype)->get_question_options($question);
967
    } else {
968
        $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
969
                'qtype_missingtype')) . $question->questiontext;
970
    }
971
}
972
 
973
/**
974
 * Updates the question objects with question type specific
975
 * information by calling {@see get_question_options()}
976
 *
977
 * Can be called either with an array of question objects or with a single
978
 * question object.
979
 *
980
 * @param mixed $questions Either an array of question objects to be updated
981
 *         or just a single question object
982
 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
983
 * @param stdClass[] $filtercourses The courses to filter the course tags by.
984
 * @return bool Indicates success or failure.
985
 */
986
function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
987
    global $DB;
988
 
989
    $questionlist = is_array($questions) ? $questions : [$questions];
990
    $categoryids = [];
991
    $questionids = [];
992
 
993
    if (empty($questionlist)) {
994
        return true;
995
    }
996
 
997
    foreach ($questionlist as $question) {
998
        $questionids[] = $question->id;
999
        if (isset($question->category)) {
1000
            $qcategoryid = $question->category;
1001
        } else {
1002
            $qcategoryid = get_question_bank_entry($question->id)->questioncategoryid;
1003
            $question->questioncategoryid = $qcategoryid;
1004
        }
1005
 
1006
        if (!in_array($qcategoryid, $categoryids)) {
1007
            $categoryids[] = $qcategoryid;
1008
        }
1009
    }
1010
 
1011
    $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
1012
 
1013
    if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
1014
        $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
1015
    } else {
1016
        $tagobjectsbyquestion = null;
1017
    }
1018
 
1019
    foreach ($questionlist as $question) {
1020
        if (is_null($tagobjectsbyquestion)) {
1021
            $tagobjects = null;
1022
        } else {
1023
            $tagobjects = $tagobjectsbyquestion[$question->id];
1024
        }
1025
        $qcategoryid = $question->category ?? $question->questioncategoryid ??
1026
            get_question_bank_entry($question->id)->questioncategoryid;
1027
 
1028
        _tidy_question($question, $categories[$qcategoryid], $tagobjects, $filtercourses);
1029
    }
1030
 
1031
    return true;
1032
}
1033
 
1034
/**
1035
 * Sort question tags by course or normal tags.
1036
 *
1037
 * This function also search tag instances that may have a context id that don't match either a course or
1038
 * question context and fix the data setting the correct context id.
1039
 *
1040
 * @param \core_tag_tag[] $tagobjects The tags for the given $question.
1041
 * @param stdClass $categorycontext The question categories context.
1042
 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1043
 * @return stdClass $sortedtagobjects Sorted tag objects.
1044
 */
1045
function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null): stdClass {
1046
 
1047
    // Questions can have two sets of tag instances. One set at the
1048
    // course context level and another at the context the question
1049
    // belongs to (e.g. course category, system etc).
1050
    $sortedtagobjects = new stdClass();
1051
    $sortedtagobjects->coursetagobjects = [];
1052
    $sortedtagobjects->coursetags = [];
1053
    $sortedtagobjects->tagobjects = [];
1054
    $sortedtagobjects->tags = [];
1055
    $taginstanceidstonormalise = [];
1056
    $filtercoursecontextids = [];
1057
    $hasfiltercourses = !empty($filtercourses);
1058
 
1059
    if ($hasfiltercourses) {
1060
        // If we're being asked to filter the course tags by a set of courses
1061
        // then get the context ids to filter below.
1062
        $filtercoursecontextids = array_map(function($course) {
1063
            $coursecontext = context_course::instance($course->id);
1064
            return $coursecontext->id;
1065
        }, $filtercourses);
1066
    }
1067
 
1068
    foreach ($tagobjects as $tagobject) {
1069
        $tagcontextid = $tagobject->taginstancecontextid;
1070
        $tagcontext = context::instance_by_id($tagcontextid);
1071
        $tagcoursecontext = $tagcontext->get_course_context(false);
1072
        // This is a course tag if the tag context is a course context which
1073
        // doesn't match the question's context. Any tag in the question context
1074
        // is not considered a course tag, it belongs to the question.
1075
        $iscoursetag = $tagcoursecontext
1076
            && $tagcontext->id == $tagcoursecontext->id
1077
            && $tagcontext->id != $categorycontext->id;
1078
 
1079
        if ($iscoursetag) {
1080
            // Any tag instance in a course context level is considered a course tag.
1081
            if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1082
                // Add the tag to the list of course tags if we aren't being
1083
                // asked to filter or if this tag is in the list of courses
1084
                // we're being asked to filter by.
1085
                $sortedtagobjects->coursetagobjects[] = $tagobject;
1086
                $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1087
            }
1088
        } else {
1089
            // All non course context level tag instances or tags in the question
1090
            // context belong to the context that the question was created in.
1091
            $sortedtagobjects->tagobjects[] = $tagobject;
1092
            $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1093
 
1094
            // Due to legacy tag implementations that don't force the recording
1095
            // of a context id, some tag instances may have context ids that don't
1096
            // match either a course context or the question context. In this case
1097
            // we should take the opportunity to fix up the data and set the correct
1098
            // context id.
1099
            if ($tagcontext->id != $categorycontext->id) {
1100
                $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1101
                // Update the object properties to reflect the DB update that will
1102
                // happen below.
1103
                $tagobject->taginstancecontextid = $categorycontext->id;
1104
            }
1105
        }
1106
    }
1107
 
1108
    if (!empty($taginstanceidstonormalise)) {
1109
        // If we found any tag instances with incorrect context id data then we can
1110
        // correct those values now by setting them to the question context id.
1111
        core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1112
    }
1113
 
1114
    return $sortedtagobjects;
1115
}
1116
 
1117
/**
1118
 * Print the icon for the question type
1119
 *
1120
 * @param object $question The question object for which the icon is required.
1121
 *       Only $question->qtype is used.
1122
 * @return string the HTML for the img tag.
1123
 */
1124
function print_question_icon($question): string {
1125
    global $PAGE;
1126
 
1127
    if (gettype($question->qtype) == 'object') {
1128
        $qtype = $question->qtype->name();
1129
    } else {
1130
        // Assume string.
1131
        $qtype = $question->qtype;
1132
    }
1133
 
1134
    return $PAGE->get_renderer('question', 'bank')->qtype_icon($qtype);
1135
}
1136
 
1137
// CATEGORY FUNCTIONS.
1138
 
1139
/**
1140
 * Returns the categories with their names ordered following parent-child relationships.
1141
 * finally it tries to return pending categories (those being orphaned, whose parent is
1142
 * incorrect) to avoid missing any category from original array.
1143
 *
1144
 * @param array $categories
1145
 * @param int $id
1146
 * @param int $level
1147
 * @return array
1148
 */
1149
function sort_categories_by_tree(&$categories, $id = 0, $level = 1): array {
1150
    global $DB;
1151
 
1152
    $children = [];
1153
    $keys = array_keys($categories);
1154
 
1155
    foreach ($keys as $key) {
1156
        if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1157
            $children[$key] = $categories[$key];
1158
            $categories[$key]->processed = true;
1159
            $children = $children + sort_categories_by_tree(
1160
                    $categories, $children[$key]->id, $level + 1);
1161
        }
1162
    }
1163
    // If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too.
1164
    if ($level == 1) {
1165
        foreach ($keys as $key) {
1166
            // If not processed and it's a good candidate to start (because its parent doesn't exist in the course).
1167
            if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1168
                    array('contextid' => $categories[$key]->contextid,
1169
                            'id' => $categories[$key]->parent))) {
1170
                $children[$key] = $categories[$key];
1171
                $categories[$key]->processed = true;
1172
                $children = $children + sort_categories_by_tree(
1173
                        $categories, $children[$key]->id, $level + 1);
1174
            }
1175
        }
1176
    }
1177
    return $children;
1178
}
1179
 
1180
/**
1181
 * Get the default category for the context.
1182
 *
1183
 * @param integer $contextid a context id.
1184
 * @return object|bool the default question category for that context, or false if none.
1185
 */
1186
function question_get_default_category($contextid) {
1187
    global $DB;
1188
    $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1189
                                        [$contextid], 'id', '*', 0, 1);
1190
    if (!empty($category)) {
1191
        return reset($category);
1192
    } else {
1193
        return false;
1194
    }
1195
}
1196
 
1197
/**
1198
 * Gets the top category in the given context.
1199
 * This function can optionally create the top category if it doesn't exist.
1200
 *
1201
 * @param int $contextid A context id.
1202
 * @param bool $create Whether create a top category if it doesn't exist.
1203
 * @return bool|stdClass The top question category for that context, or false if none.
1204
 */
1205
function question_get_top_category($contextid, $create = false) {
1206
    global $DB;
1207
    $category = $DB->get_record('question_categories', ['contextid' => $contextid, 'parent' => 0]);
1208
 
1209
    if (!$category && $create) {
1210
        // We need to make one.
1211
        $category = new stdClass();
1212
        $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1213
        $category->info = '';
1214
        $category->contextid = $contextid;
1215
        $category->parent = 0;
1216
        $category->sortorder = 0;
1217
        $category->stamp = make_unique_id_code();
1218
        $category->id = $DB->insert_record('question_categories', $category);
1219
    }
1220
 
1221
    return $category;
1222
}
1223
 
1224
/**
1225
 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1226
 *
1227
 * @param array $contextids List of context ids
1228
 * @return array
1229
 */
1230
function question_get_top_categories_for_contexts($contextids): array {
1231
    global $DB;
1232
 
1233
    $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1234
    list($insql, $params) = $DB->get_in_or_equal($contextids);
1235
    $sql = "SELECT $concatsql
1236
              FROM {question_categories}
1237
             WHERE contextid $insql
1238
               AND parent = 0";
1239
 
1240
    $topcategories = $DB->get_fieldset_sql($sql, $params);
1241
 
1242
    return $topcategories;
1243
}
1244
 
1245
/**
1246
 * Gets the default category in the most specific context.
1247
 * If no categories exist yet then default ones are created in all contexts.
1248
 *
1249
 * @param array $contexts  The context objects for this context and all parent contexts.
1250
 * @return object The default category - the category in the course context
1251
 */
1252
function question_make_default_categories($contexts): object {
1253
    global $DB;
1254
    static $preferredlevels = array(
1255
        CONTEXT_COURSE => 4,
1256
        CONTEXT_MODULE => 3,
1257
        CONTEXT_COURSECAT => 2,
1258
        CONTEXT_SYSTEM => 1,
1259
    );
1260
 
1261
    $toreturn = null;
1262
    $preferredness = 0;
1263
    // If it already exists, just return it.
1264
    foreach ($contexts as $key => $context) {
1265
        $topcategory = question_get_top_category($context->id, true);
1266
        if (!$exists = $DB->record_exists("question_categories",
1267
                array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1268
            // Otherwise, we need to make one.
1269
            $category = new stdClass();
1270
            $contextname = $context->get_context_name(false, true);
1271
            // Max length of name field is 255.
1272
            $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1273
            $category->info = get_string('defaultinfofor', 'question', $contextname);
1274
            $category->contextid = $context->id;
1275
            $category->parent = $topcategory->id;
1276
            // By default, all categories get this number, and are sorted alphabetically.
1277
            $category->sortorder = 999;
1278
            $category->stamp = make_unique_id_code();
1279
            $category->id = $DB->insert_record('question_categories', $category);
1280
        } else {
1281
            $category = question_get_default_category($context->id);
1282
        }
1283
        $thispreferredness = $preferredlevels[$context->contextlevel];
1284
        if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1285
            $thispreferredness += 10;
1286
        }
1287
        if ($thispreferredness > $preferredness) {
1288
            $toreturn = $category;
1289
            $preferredness = $thispreferredness;
1290
        }
1291
    }
1292
 
1293
    if (!is_null($toreturn)) {
1294
        $toreturn = clone($toreturn);
1295
    }
1296
    return $toreturn;
1297
}
1298
 
1299
/**
1300
 * Get the list of categories.
1301
 *
1302
 * @param int $categoryid
1303
 * @return array of question category ids of the category and all subcategories.
1304
 */
1305
function question_categorylist($categoryid): array {
1306
    global $DB;
1307
 
1308
    // Final list of category IDs.
1309
    $categorylist = [];
1310
 
1311
    // A list of category IDs to check for any sub-categories.
1312
    $subcategories = [$categoryid];
1313
    $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $categoryid]);
1314
 
1315
    while ($subcategories) {
1316
        foreach ($subcategories as $subcategory) {
1317
            // If anything from the temporary list was added already, then we have a loop.
1318
            if (isset($categorylist[$subcategory])) {
1319
                throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1320
            }
1321
            $categorylist[$subcategory] = $subcategory;
1322
        }
1323
 
1324
        [$in, $params] = $DB->get_in_or_equal($subcategories);
1325
        $params[] = $contextid;
1326
 
1327
        // Order by id is not strictly needed, but it will be cheap, and makes the results deterministic.
1328
        $subcategories = $DB->get_records_select_menu('question_categories',
1329
                "parent $in AND contextid = ?", $params, 'id', 'id,id AS id2');
1330
    }
1331
 
1332
    return $categorylist;
1333
}
1334
 
1335
/**
1336
 * Get all parent categories of a given question category in descending order.
1337
 *
1338
 * @param int $categoryid for which you want to find the parents.
1339
 * @return array of question category ids of all parents categories.
1340
 */
1341
function question_categorylist_parents(int $categoryid): array {
1342
    global $DB;
1343
 
1344
    $category = $DB->get_record('question_categories', ['id' => $categoryid]);
1345
    $contextid = $category->contextid;
1346
 
1347
    $categorylist = [];
1348
    while ($category->parent) {
1349
        $category = $DB->get_record('question_categories', ['id' => $category->parent]);
1350
        if (!$category || $category->contextid != $contextid) {
1351
            break;
1352
        }
1353
        $categorylist[] = $category->id;
1354
    }
1355
 
1356
    // Present the list in descending order (the top category at the top).
1357
    return array_reverse($categorylist);
1358
}
1359
 
1360
// Import/Export Functions.
1361
 
1362
/**
1363
 * Get list of available import or export formats
1364
 * @param string $type 'import' if import list, otherwise export list assumed
1365
 * @return array sorted list of import/export formats available
1366
 */
1367
function get_import_export_formats($type): array {
1368
    global $CFG;
1369
    require_once($CFG->dirroot . '/question/format.php');
1370
 
1371
    $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1372
 
1373
    $fileformatname = array();
1374
    foreach ($formatclasses as $component => $formatclass) {
1375
 
1376
        $format = new $formatclass();
1377
        if ($type == 'import') {
1378
            $provided = $format->provide_import();
1379
        } else {
1380
            $provided = $format->provide_export();
1381
        }
1382
 
1383
        if ($provided) {
1384
            list($notused, $fileformat) = explode('_', $component, 2);
1385
            $fileformatnames[$fileformat] = get_string('pluginname', $component);
1386
        }
1387
    }
1388
 
1389
    core_collator::asort($fileformatnames);
1390
    return $fileformatnames;
1391
}
1392
 
1393
 
1394
/**
1395
 * Create a reasonable default file name for exporting questions from a particular
1396
 * category.
1397
 * @param object $course the course the questions are in.
1398
 * @param object $category the question category.
1399
 * @return string the filename.
1400
 */
1401
function question_default_export_filename($course, $category): string {
1402
    // We build a string that is an appropriate name (questions) from the lang pack,
1403
    // then the corse shortname, then the question category name, then a timestamp.
1404
 
1405
    $base = clean_filename(get_string('exportfilename', 'question'));
1406
 
1407
    $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1408
    $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1409
 
1410
    $shortname = clean_filename($course->shortname);
1411
    if ($shortname == '' || $shortname == '_' ) {
1412
        $shortname = $course->id;
1413
    }
1414
 
1415
    $categoryname = clean_filename(format_string($category->name));
1416
 
1417
    return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1418
}
1419
 
1420
/**
1421
 * Check capability on category.
1422
 *
1423
 * @param int|stdClass|question_definition $questionorid object or id.
1424
 *      If an object is passed, it should include ->contextid and ->createdby.
1425
 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1426
 * @param int $notused no longer used.
1427
 * @return bool this user has the capability $cap for this question $question?
1428
 */
1429
function question_has_capability_on($questionorid, $cap, $notused = -1): bool {
1430
    global $USER, $DB;
1431
 
1432
    if (is_numeric($questionorid)) {
1433
        $questionid = (int)$questionorid;
1434
    } else if (is_object($questionorid)) {
1435
        // All we really need in this function is the contextid and author of the question.
1436
        // We won't bother fetching other details of the question if these 2 fields are provided.
11 efrain 1437
        if (isset($questionorid->contextid) && property_exists($questionorid, 'createdby')) {
1 efrain 1438
            $question = $questionorid;
1439
        } else if (!empty($questionorid->id)) {
1440
            $questionid = $questionorid->id;
1441
        }
1442
    }
1443
 
1444
    // At this point, either $question or $questionid is expected to be set.
1445
    if (isset($questionid)) {
1446
        try {
1447
            $question = question_bank::load_question_data($questionid);
1448
        } catch (Exception $e) {
1449
            // Let's log the exception for future debugging,
1450
            // but not during Behat, or we can't test these cases.
1451
            if (!defined('BEHAT_SITE_RUNNING')) {
1452
                debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1453
            }
1454
 
1455
            $sql = 'SELECT q.id,
1456
                           q.createdby,
1457
                           qc.contextid
1458
                      FROM {question} q
1459
                      JOIN {question_versions} qv
1460
                        ON qv.questionid = q.id
1461
                      JOIN {question_bank_entries} qbe
1462
                        ON qbe.id = qv.questionbankentryid
1463
                      JOIN {question_categories} qc
1464
                        ON qc.id = qbe.questioncategoryid
1465
                     WHERE q.id = :id';
1466
 
1467
            // Well, at least we tried. Seems that we really have to read from DB.
11 efrain 1468
            $question = $DB->get_record_sql($sql, ['id' => $questionid], MUST_EXIST);
1 efrain 1469
        }
1470
    }
1471
 
1472
    if (!isset($question)) {
1473
        throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1474
    }
1475
 
1476
    $context = context::instance_by_id($question->contextid);
1477
 
1478
    // These are existing questions capabilities that are set per category.
1479
    // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1480
    $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1481
 
1482
    if (!isset($capabilitieswithallandmine[$cap])) {
1483
        return has_capability('moodle/question:' . $cap, $context);
1484
    } else {
1485
        return has_capability('moodle/question:' . $cap . 'all', $context) ||
1486
            ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1487
    }
1488
}
1489
 
1490
/**
1491
 * Require capability on question.
1492
 *
1493
 * @param int|stdClass|question_definition $question object or id.
1494
 *      If an object is passed, it should include ->contextid and ->createdby.
1495
 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1496
 * @return bool true if the user has the capability. Throws exception if not.
1497
 */
1498
function question_require_capability_on($question, $cap): bool {
1499
    if (!question_has_capability_on($question, $cap)) {
1500
        throw new moodle_exception('nopermissions', '', '', $cap);
1501
    }
1502
    return true;
1503
}
1504
 
1505
/**
1506
 * Gets the question edit url.
1507
 *
1508
 * @param object $context a context
1509
 * @return string|bool|void A URL for editing questions in this context.
1510
 */
1511
function question_edit_url($context) {
1512
    global $CFG, $SITE;
1513
    if (!has_any_capability(question_get_question_capabilities(), $context)) {
1514
        return false;
1515
    }
1516
    $baseurl = $CFG->wwwroot . '/question/edit.php?';
1517
    $defaultcategory = question_get_default_category($context->id);
1518
    if ($defaultcategory) {
1519
        $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1520
    }
1521
    switch ($context->contextlevel) {
1522
        case CONTEXT_SYSTEM:
1523
            return $baseurl . 'courseid=' . $SITE->id;
1524
        case CONTEXT_COURSECAT:
1525
            // This is nasty, becuase we can only edit questions in a course
1526
            // context at the moment, so for now we just return false.
1527
            return false;
1528
        case CONTEXT_COURSE:
1529
            return $baseurl . 'courseid=' . $context->instanceid;
1530
        case CONTEXT_MODULE:
1531
            return $baseurl . 'cmid=' . $context->instanceid;
1532
    }
1533
 
1534
}
1535
 
1536
/**
1537
 * Adds question bank setting links to the given navigation node if caps are met
1538
 * and loads the navigation from the plugins.
1539
 * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1540
 * this method will help to autoload those nodes in the question bank navigation.
1541
 *
1542
 * @param navigation_node $navigationnode The navigation node to add the question branch to
1543
 * @param object $context
1544
 * @param string $baseurl the url of the base where the api is implemented from
1545
 * @return navigation_node Returns the question branch that was added
1546
 */
1547
function question_extend_settings_navigation(navigation_node $navigationnode, $context, $baseurl = '/question/edit.php') {
1548
    global $PAGE;
1549
 
1550
    if ($context->contextlevel == CONTEXT_COURSE) {
1551
        $params = ['courseid' => $context->instanceid];
1552
    } else if ($context->contextlevel == CONTEXT_MODULE) {
1553
        $params = ['cmid' => $context->instanceid];
1554
    } else {
1555
        return;
1556
    }
1557
 
1558
    if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1559
        $params['cat'] = $cat;
1560
    }
1561
 
1562
    $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1563
            new moodle_url($baseurl, $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1564
 
1565
    $corenavigations = [
1566
            'questions' => [
1567
                    'title' => get_string('questions', 'question'),
1568
                    'url' => new moodle_url($baseurl)
1569
            ],
1570
            'categories' => [],
1571
            'import' => [],
1572
            'export' => []
1573
    ];
1574
 
1575
    $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1576
    foreach ($plugins as $componentname => $plugin) {
1577
        $pluginentrypoint = new $plugin();
1578
        $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1579
        // Don't need the plugins without navigation node.
1580
        if ($pluginentrypointobject === null) {
1581
            unset($plugins[$componentname]);
1582
            continue;
1583
        }
1584
        foreach ($corenavigations as $key => $corenavigation) {
1585
            if ($pluginentrypointobject->get_navigation_key() === $key) {
1586
                unset($plugins[$componentname]);
1587
                if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1588
                    unset($corenavigations[$key]);
1589
                    break;
1590
                }
1591
                $corenavigations[$key] = [
1592
                    'title' => $pluginentrypointobject->get_navigation_title(),
1593
                    'url'   => $pluginentrypointobject->get_navigation_url()
1594
                ];
1595
            }
1596
        }
1597
    }
1598
 
1599
    // Mitigate the risk of regression.
1600
    foreach ($corenavigations as $node => $corenavigation) {
1601
        if (empty($corenavigation)) {
1602
            unset($corenavigations[$node]);
1603
        }
1604
    }
1605
 
1606
    // Community/additional plugins have navigation node.
1607
    $pluginnavigations = [];
1608
    foreach ($plugins as $componentname => $plugin) {
1609
        $pluginentrypoint = new $plugin();
1610
        $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1611
        // Don't need the plugins without navigation node.
1612
        if ($pluginentrypointobject === null || !\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1613
            unset($plugins[$componentname]);
1614
            continue;
1615
        }
1616
        $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1617
            'title' => $pluginentrypointobject->get_navigation_title(),
1618
            'url'   => $pluginentrypointobject->get_navigation_url(),
1619
            'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1620
        ];
1621
    }
1622
 
1623
    $contexts = new core_question\local\bank\question_edit_contexts($context);
1624
    foreach ($corenavigations as $key => $corenavigation) {
1625
        if ($contexts->have_one_edit_tab_cap($key)) {
1626
            $questionnode->add($corenavigation['title'], new moodle_url(
1627
                    $corenavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1628
        }
1629
    }
1630
 
1631
    foreach ($pluginnavigations as $key => $pluginnavigation) {
1632
        if (is_array($pluginnavigation['capabilities'])) {
1633
            if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1634
                continue;
1635
            }
1636
        }
1637
        $questionnode->add($pluginnavigation['title'], new moodle_url(
1638
                $pluginnavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1639
    }
1640
 
1641
    return $questionnode;
1642
}
1643
 
1644
/**
1645
 * Get the array of capabilities for question.
1646
 *
1647
 * @return array all the capabilities that relate to accessing particular questions.
1648
 */
1649
function question_get_question_capabilities(): array {
1650
    return [
1651
        'moodle/question:add',
1652
        'moodle/question:editmine',
1653
        'moodle/question:editall',
1654
        'moodle/question:viewmine',
1655
        'moodle/question:viewall',
1656
        'moodle/question:usemine',
1657
        'moodle/question:useall',
1658
        'moodle/question:movemine',
1659
        'moodle/question:moveall',
1660
        'moodle/question:tagmine',
1661
        'moodle/question:tagall',
1662
        'moodle/question:commentmine',
1663
        'moodle/question:commentall',
1664
    ];
1665
}
1666
 
1667
/**
1668
 * Get the question bank caps.
1669
 *
1670
 * @return array all the question bank capabilities.
1671
 */
1672
function question_get_all_capabilities(): array {
1673
    $caps = question_get_question_capabilities();
1674
    $caps[] = 'moodle/question:managecategory';
1675
    $caps[] = 'moodle/question:flag';
1676
    return $caps;
1677
}
1678
 
1679
/**
1680
 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1681
 *
1682
 * @package  core_question
1683
 * @category files
1684
 * @param string $text text being processed
1685
 * @param string $file the php script used to serve files
1686
 * @param int $contextid context ID
1687
 * @param string $component component
1688
 * @param string $filearea filearea
1689
 * @param array $ids other IDs will be used to check file permission
1690
 * @param int $itemid item ID
1691
 * @param array $options options
1692
 * @return string
1693
 */
1694
function question_rewrite_question_urls($text, $file, $contextid, $component, $filearea,
1695
                                        array $ids, $itemid, array $options=null): string {
1696
 
1697
    $idsstr = '';
1698
    if (!empty($ids)) {
1699
        $idsstr .= implode('/', $ids);
1700
    }
1701
    if ($itemid !== null) {
1702
        $idsstr .= '/' . $itemid;
1703
    }
1704
    return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1705
            $filearea, $idsstr, $options);
1706
}
1707
 
1708
/**
1709
 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1710
 * viewing the question outside an attempt (for example, in the question bank
1711
 * listing or in the quiz statistics report).
1712
 *
1713
 * @param string $text the question text.
1714
 * @param int $questionid the question id.
1715
 * @param int $filecontextid the context id of the question being displayed.
1716
 * @param string $filecomponent the component that owns the file area.
1717
 * @param string $filearea the file area name.
1718
 * @param int|null $itemid the file's itemid
1719
 * @param int $previewcontextid the context id where the preview is being displayed.
1720
 * @param string $previewcomponent component responsible for displaying the preview.
1721
 * @param array $options text and file options ('forcehttps'=>false)
1722
 * @return string $questiontext with URLs rewritten.
1723
 */
1724
function question_rewrite_question_preview_urls($text, $questionid, $filecontextid, $filecomponent, $filearea, $itemid,
1725
                                                $previewcontextid, $previewcomponent, $options = null): string {
1726
 
1727
    $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1728
    if ($itemid) {
1729
        $path .= '/' . $itemid;
1730
    }
1731
 
1732
    return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1733
            $filecomponent, $filearea, $path, $options);
1734
}
1735
 
1736
/**
1737
 * Called by pluginfile.php to serve files related to the 'question' core
1738
 * component and for files belonging to qtypes.
1739
 *
1740
 * For files that relate to questions in a question_attempt, then we delegate to
1741
 * a function in the component that owns the attempt (for example in the quiz,
1742
 * or in core question preview) to get necessary inforation.
1743
 *
1744
 * (Note that, at the moment, all question file areas relate to questions in
1745
 * attempts, so the If at the start of the last paragraph is always true.)
1746
 *
1747
 * Does not return, either calls send_file_not_found(); or serves the file.
1748
 *
1749
 * @category files
1750
 * @param stdClass $course course settings object
1751
 * @param stdClass $context context object
1752
 * @param string $component the name of the component we are serving files for.
1753
 * @param string $filearea the name of the file area.
1754
 * @param array $args the remaining bits of the file path.
1755
 * @param bool $forcedownload whether the user must be forced to download the file.
1756
 * @param array $options additional options affecting the file serving
1757
 * @return array|bool
1758
 */
1759
function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, $options = []) {
1760
    global $DB, $CFG;
1761
 
1762
    // Special case, sending a question bank export.
1763
    if ($filearea === 'export') {
1764
        list($context, $course, $cm) = get_context_info_array($context->id);
1765
        require_login($course, false, $cm);
1766
 
1767
        require_once($CFG->dirroot . '/question/editlib.php');
1768
        $contexts = new core_question\local\bank\question_edit_contexts($context);
1769
        // Check export capability.
1770
        $contexts->require_one_edit_tab_cap('export');
1771
        $categoryid = (int)array_shift($args);
1772
        $format      = array_shift($args);
1773
        $cattofile   = array_shift($args);
1774
        $contexttofile = array_shift($args);
1775
        $filename    = array_shift($args);
1776
 
1777
        // Load parent class for import/export.
1778
        require_once($CFG->dirroot . '/question/format.php');
1779
        require_once($CFG->dirroot . '/question/editlib.php');
1780
        require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1781
 
1782
        $classname = 'qformat_' . $format;
1783
        if (!class_exists($classname)) {
1784
            send_file_not_found();
1785
        }
1786
 
1787
        $qformat = new $classname();
1788
 
1789
        if (!$category = $DB->get_record('question_categories', array('id' => $categoryid))) {
1790
            send_file_not_found();
1791
        }
1792
 
1793
        $qformat->setCategory($category);
1794
        $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1795
        $qformat->setCourse($course);
1796
 
1797
        if ($cattofile == 'withcategories') {
1798
            $qformat->setCattofile(true);
1799
        } else {
1800
            $qformat->setCattofile(false);
1801
        }
1802
 
1803
        if ($contexttofile == 'withcontexts') {
1804
            $qformat->setContexttofile(true);
1805
        } else {
1806
            $qformat->setContexttofile(false);
1807
        }
1808
 
1809
        if (!$qformat->exportpreprocess()) {
1810
            send_file_not_found();
1811
            throw new moodle_exception('exporterror', 'question', $thispageurl->out());
1812
        }
1813
 
1814
        // Export data to moodle file pool.
1815
        if (!$content = $qformat->exportprocess()) {
1816
            send_file_not_found();
1817
        }
1818
 
1819
        send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1820
    }
1821
 
1822
    // Normal case, a file belonging to a question.
1823
    $qubaidorpreview = array_shift($args);
1824
 
1825
    // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1826
    if ($qubaidorpreview === 'preview') {
1827
        $previewcontextid = (int)array_shift($args);
1828
        $previewcomponent = array_shift($args);
1829
        $questionid = (int) array_shift($args);
1830
        $previewcontext = context_helper::instance_by_id($previewcontextid);
1831
 
1832
        $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1833
                $previewcontext, $questionid,
1834
                $context, $component, $filearea, $args,
1835
                $forcedownload, $options), 'callbackmissing');
1836
 
1837
        if ($result === 'callbackmissing') {
1838
            throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1839
                    "{$previewcomponent}_question_preview_pluginfile callback. " .
1840
                    "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
1841
        }
1842
 
1843
        send_file_not_found();
1844
    }
1845
 
1846
    // 2. A question being attempted in the normal way.
1847
    $qubaid = (int)$qubaidorpreview;
1848
    $slot = (int)array_shift($args);
1849
 
1850
    $module = $DB->get_field('question_usages', 'component',
1851
            array('id' => $qubaid));
1852
    if (!$module) {
1853
        send_file_not_found();
1854
    }
1855
 
1856
    if ($module === 'core_question_preview') {
1857
        return qbank_previewquestion\helper::question_preview_question_pluginfile($course, $context,
1858
                $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1859
 
1860
    } else {
1861
        $dir = core_component::get_component_directory($module);
1862
        if (!file_exists("$dir/lib.php")) {
1863
            send_file_not_found();
1864
        }
1865
        include_once("$dir/lib.php");
1866
 
1867
        $filefunction = $module . '_question_pluginfile';
1868
        if (function_exists($filefunction)) {
1869
            $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1870
                $args, $forcedownload, $options);
1871
        }
1872
 
1873
        // Okay, we're here so lets check for function without 'mod_'.
1874
        if (strpos($module, 'mod_') === 0) {
1875
            $filefunctionold  = substr($module, 4) . '_question_pluginfile';
1876
            if (function_exists($filefunctionold)) {
1877
                $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1878
                    $args, $forcedownload, $options);
1879
            }
1880
        }
1881
 
1882
        send_file_not_found();
1883
    }
1884
}
1885
 
1886
/**
1887
 * Serve questiontext files in the question text when they are displayed in this report.
1888
 *
1889
 * @param context $previewcontext the context in which the preview is happening.
1890
 * @param int $questionid the question id.
1891
 * @param context $filecontext the file (question) context.
1892
 * @param string $filecomponent the component the file belongs to.
1893
 * @param string $filearea the file area.
1894
 * @param array $args remaining file args.
1895
 * @param bool $forcedownload
1896
 * @param array $options additional options affecting the file serving.
1897
 */
1898
function core_question_question_preview_pluginfile($previewcontext, $questionid, $filecontext, $filecomponent,
1899
                                                    $filearea, $args, $forcedownload, $options = []): void {
1900
    global $DB;
1901
    $sql = 'SELECT q.*,
1902
                   qc.contextid
1903
              FROM {question} q
1904
              JOIN {question_versions} qv
1905
                ON qv.questionid = q.id
1906
              JOIN {question_bank_entries} qbe
1907
                ON qbe.id = qv.questionbankentryid
1908
              JOIN {question_categories} qc
1909
                ON qc.id = qbe.questioncategoryid
1910
             WHERE q.id = :id
1911
               AND qc.contextid = :contextid';
1912
 
1913
    // Verify that contextid matches the question.
1914
    $question = $DB->get_record_sql($sql, ['id' => $questionid, 'contextid' => $filecontext->id], MUST_EXIST);
1915
 
1916
    // Check the capability.
1917
    list($context, $course, $cm) = get_context_info_array($previewcontext->id);
1918
    require_login($course, false, $cm);
1919
 
1920
    question_require_capability_on($question, 'use');
1921
 
1922
    $fs = get_file_storage();
1923
    $relativepath = implode('/', $args);
1924
    $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1925
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1926
        send_file_not_found();
1927
    }
1928
 
1929
    send_stored_file($file, 0, 0, $forcedownload, $options);
1930
}
1931
 
1932
/**
1933
 * Return a list of page types
1934
 * @param string $pagetype current page type
1935
 * @param stdClass $parentcontext Block's parent context
1936
 * @param stdClass $currentcontext Current context of block
1937
 * @return array
1938
 */
1939
function question_page_type_list($pagetype, $parentcontext, $currentcontext): array {
1940
    global $CFG;
1941
    $types = [
1942
        'question-*' => get_string('page-question-x', 'question'),
1943
        'question-edit' => get_string('page-question-edit', 'question'),
1944
        'question-category' => get_string('page-question-category', 'question'),
1945
        'question-export' => get_string('page-question-export', 'question'),
1946
        'question-import' => get_string('page-question-import', 'question')
1947
    ];
1948
    if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1949
        require_once($CFG->dirroot . '/course/lib.php');
1950
        return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1951
    } else {
1952
        return $types;
1953
    }
1954
}
1955
 
1956
/**
1957
 * Does an activity module use the question bank?
1958
 *
1959
 * @param string $modname The name of the module (without mod_ prefix).
1960
 * @return bool true if the module uses questions.
1961
 */
1962
function question_module_uses_questions($modname): bool {
1963
    if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
1964
        return true;
1965
    }
1966
 
1967
    $component = 'mod_'.$modname;
1968
    if (component_callback_exists($component, 'question_pluginfile')) {
1969
        debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
1970
        return true;
1971
    }
1972
 
1973
    return false;
1974
}
1975
 
1976
/**
1977
 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
1978
 *
1979
 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
1980
 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
1981
 *
1982
 * @param string|null $oldidnumber a question idnumber, or can be null.
1983
 * @param int $categoryid a question category id.
1984
 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
1985
 */
1986
function core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid): ?string {
1987
    global $DB;
1988
 
1989
    // The the old idnumber is not of the right form, bail now.
1990
    if ($oldidnumber === null || !preg_match('~\d+$~', $oldidnumber, $matches)) {
1991
        return null;
1992
    }
1993
 
1994
    // Find all used idnumbers in one DB query.
1995
    $usedidnumbers = $DB->get_records_select_menu('question_bank_entries', 'questioncategoryid = ? AND idnumber IS NOT NULL',
1996
            [$categoryid], '', 'idnumber, 1');
1997
 
1998
    // Find the next unused idnumber.
1999
    $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
2000
    $stem = substr($oldidnumber, 0, -strlen($matches[0]));
2001
    do {
2002
 
2003
        // If we have got to something9999, insert an extra digit before incrementing.
2004
        if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2005
            $numberbit = $matches[1] . '0' . $matches[2];
2006
        }
2007
        $numberbit++;
2008
        $newidnumber = $stem . substr($numberbit, 1);
2009
    } while (isset($usedidnumbers[$newidnumber]));
2010
 
2011
    return (string) $newidnumber;
2012
}
2013
 
2014
/**
2015
 * Get the question_bank_entry object given a question id.
2016
 *
2017
 * @param int $questionid Question id.
2018
 * @return false|mixed
2019
 * @throws dml_exception
2020
 */
2021
function get_question_bank_entry(int $questionid): object {
2022
    global $DB;
2023
 
2024
    $sql = "SELECT qbe.*
2025
              FROM {question} q
2026
              JOIN {question_versions} qv ON qv.questionid = q.id
2027
              JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2028
             WHERE q.id = :id";
2029
 
2030
    $qbankentry = $DB->get_record_sql($sql, ['id' => $questionid]);
2031
 
2032
    return $qbankentry;
2033
}
2034
 
2035
/**
2036
 * Get the question versions given a question id in a descending sort .
2037
 *
2038
 * @param int $questionid Question id.
2039
 * @return array
2040
 * @throws dml_exception
2041
 */
2042
function get_question_version($questionid): array {
2043
    global $DB;
2044
 
2045
    $version = $DB->get_records('question_versions', ['questionid' => $questionid]);
2046
    krsort($version);
2047
 
2048
    return $version;
2049
}
2050
 
2051
/**
2052
 * Get the next version number to create base on a Question bank entry id.
2053
 *
2054
 * @param int $questionbankentryid Question bank entry id.
2055
 * @return int next version number.
2056
 * @throws dml_exception
2057
 */
2058
function get_next_version(int $questionbankentryid): int {
2059
    global $DB;
2060
 
2061
    $sql = "SELECT MAX(qv.version)
2062
              FROM {question_versions} qv
2063
              JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2064
             WHERE qbe.id = :id";
2065
 
2066
    $nextversion = $DB->get_field_sql($sql, ['id' => $questionbankentryid]);
2067
 
2068
    if ($nextversion) {
2069
        return (int)$nextversion + 1;
2070
    }
2071
 
2072
    return 1;
2073
}
2074
 
2075
/**
2076
 * Checks if question is the latest version.
2077
 *
2078
 * @param string $version Question version to check.
2079
 * @param string $questionbankentryid Entry to check against.
2080
 * @return bool
2081
 */
2082
function is_latest(string $version, string $questionbankentryid): bool {
2083
    global $DB;
2084
 
2085
    $sql = 'SELECT MAX(version) AS max
2086
                  FROM {question_versions}
2087
                 WHERE questionbankentryid = ?';
2088
    $latestversion = $DB->get_record_sql($sql, [$questionbankentryid]);
2089
 
2090
    if (isset($latestversion->max)) {
2091
        return ($version === $latestversion->max) ? true : false;
2092
    }
2093
    return false;
2094
}