Merge branch 'MDL-78811-Master' of https://github.com/aydevworks/moodle
[moodle.git] / lib / questionlib.php
blob438fe683aa35471028231ec373d37205064e392e
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.
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/>.
17 /**
18 * Code for handling and processing questions.
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
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
31 use core_question\local\bank\question_version_status;
32 use core_question\question_reference_manager;
34 defined('MOODLE_INTERNAL') || die();
36 require_once($CFG->dirroot . '/question/engine/lib.php');
37 require_once($CFG->dirroot . '/question/type/questiontypebase.php');
41 // CONSTANTS.
43 /**
44 * Constant determines the number of answer boxes supplied in the editing
45 * form for multiple choice and similar question types.
47 define("QUESTION_NUMANS", 10);
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.
54 define("QUESTION_NUMANS_START", 3);
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'.
61 define("QUESTION_NUMANS_ADD", 3);
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.
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.
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;
81 // Work out the other index.
82 $otherkey = $key + $direction;
83 if (!isset($neworder[$otherkey])) {
84 return $neworder;
86 // Do the swap.
87 $swap = $neworder[$otherkey];
88 $neworder[$otherkey] = $neworder[$key];
89 $neworder[$key] = $swap;
90 return $neworder;
93 /**
94 * Save a new question type order to the config_plugins table.
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.
99 function question_save_qtype_order($neworder, $config = null): void {
100 if (is_null($config)) {
101 $config = get_config('question');
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');
112 // FUNCTIONS.
115 * Check if the question is used.
117 * @param array $questionids of question ids.
118 * @return boolean whether any of these questions are being used by any part of Moodle.
120 function questions_in_use($questionids): bool {
122 // Are they used by the core question system?
123 if (question_engine::questions_in_use($questionids)) {
124 return true;
127 if (question_reference_manager::questions_with_references($questionids)) {
128 return true;
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;
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);
147 if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
148 continue; // Already done.
151 foreach ($questionids as $questionid) {
152 if (!empty($function($questionid))) {
153 return true;
158 return false;
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.
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.
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');
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]);
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.
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.
196 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
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.
206 // Didn't find a match so that's an error.
207 return false;
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;
220 return $best;
222 } else {
223 // Unknow option passed.
224 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
225 ' passed to match_grade_options');
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
235 * @param object|core_course_category $category course category object
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.
243 // Deal with any questions in the category.
244 if ($questionentries = $DB->get_records('question_bank_entries', $criteria, '', 'id')) {
246 foreach ($questionentries as $questionentry) {
247 $questionids = $DB->get_records('question_versions',
248 ['questionbankentryid' => $questionentry->id], '', 'questionid');
250 // Try to delete each question.
251 foreach ($questionids as $questionid) {
252 question_delete_question($questionid->questionid, $category->contextid);
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;
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;
278 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
282 // Now delete the category.
283 $DB->delete_records('question_categories', ['id' => $category->id]);
287 * Tests whether any question in a category is used by any part of Moodle.
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.
293 function question_category_in_use($categoryid, $recursive = false): bool {
294 global $DB;
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;
303 if (!$recursive) {
304 return false;
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;
317 return false;
321 * Check if there is more versions left for the entry.
322 * If not delete the entry.
324 * @param int $entryid
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]);
334 * Deletes question and all associated data from the database
336 * It will not delete a question if it is used somewhere, instead it will just delete the reference.
338 * @param int $questionid The id of the question being deleted
340 function question_delete_question($questionid): void {
341 global $DB;
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;
351 $sql = 'SELECT qv.id as versionid,
352 qv.version,
353 qbe.id as entryid,
354 qc.id as categoryid,
355 qc.contextid 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 WHERE q.id = ?';
361 $questiondata = $DB->get_record_sql($sql, [$question->id]);
363 $questionstocheck = [$question->id];
365 if ($question->parent) {
366 $questionstocheck[] = $question->parent;
369 // Do not delete a question if it is used by an activity module. Just mark the version hidden.
370 if (questions_in_use($questionstocheck)) {
371 $DB->set_field('question_versions', 'status',
372 question_version_status::QUESTION_STATUS_HIDDEN, ['questionid' => $questionid]);
373 return;
376 // This sometimes happens in old sites with bad data.
377 if (!$questiondata->contextid) {
378 debugging('Deleting question ' . $question->id . ' which is no longer linked to a context. ' .
379 'Assuming system context to avoid errors, but this may mean that some data like files, ' .
380 'tags, are not cleaned up.');
381 $questiondata->contextid = context_system::instance()->id;
382 $questiondata->categoryid = 0;
385 // Delete previews of the question.
386 $dm = new question_engine_data_mapper();
387 $dm->delete_previews($question->id);
389 // Delete questiontype-specific data.
390 question_bank::get_qtype($question->qtype, false)->delete_question($question->id, $questiondata->contextid);
392 // Now recursively delete all child questions
393 if ($children = $DB->get_records('question',
394 array('parent' => $questionid), '', 'id, qtype')) {
395 foreach ($children as $child) {
396 if ($child->id != $questionid) {
397 question_delete_question($child->id);
402 // Finally delete the question record itself.
403 $DB->delete_records('question', ['id' => $question->id]);
404 $DB->delete_records('question_versions', ['id' => $questiondata->versionid]);
405 $DB->delete_records('question_references',
407 'version' => $questiondata->version,
408 'questionbankentryid' => $questiondata->entryid,
410 delete_question_bank_entry($questiondata->entryid);
411 question_bank::notify_question_edited($question->id);
413 // Log the deletion of this question.
414 // Any qbank plugins storing additional question data should observe this event and perform the necessary deletion.
415 $question->category = $questiondata->categoryid;
416 $question->contextid = $questiondata->contextid;
417 $event = \core\event\question_deleted::create_from_question_instance($question);
418 $event->add_record_snapshot('question', $question);
419 $event->trigger();
423 * All question categories and their questions are deleted for this context id.
425 * @param int $contextid The contextid to delete question categories from
426 * @return array only returns an empty array for backwards compatibility.
428 function question_delete_context($contextid): array {
429 global $DB;
431 $fields = 'id, parent, name, contextid';
432 if ($categories = $DB->get_records('question_categories', ['contextid' => $contextid], 'parent', $fields)) {
433 // Sort categories following their tree (parent-child) relationships this will make the feedback more readable.
434 $categories = sort_categories_by_tree($categories);
435 foreach ($categories as $category) {
436 question_category_delete_safe($category);
439 return [];
443 * All question categories and their questions are deleted for this course.
445 * @param stdClass $course an object representing the activity
446 * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
447 * @return bool always true.
449 function question_delete_course($course, $notused = false): bool {
450 $coursecontext = context_course::instance($course->id);
451 question_delete_context($coursecontext->id);
452 return true;
456 * Category is about to be deleted,
457 * 1/ All question categories and their questions are deleted for this course category.
458 * 2/ All questions are moved to new category
460 * @param stdClass|core_course_category $category course category object
461 * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
462 * category where content moved
463 * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
464 * @return boolean
466 function question_delete_course_category($category, $newcategory, $notused=false): bool {
467 global $DB;
469 $context = context_coursecat::instance($category->id);
470 if (empty($newcategory)) {
471 question_delete_context($context->id);
473 } else {
474 // Move question categories to the new context.
475 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
476 return false;
479 // Only move question categories if there is any question category at all!
480 if ($topcategory = question_get_top_category($context->id)) {
481 $newtopcategory = question_get_top_category($newcontext->id, true);
483 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
484 $DB->set_field('question_categories', 'parent', $newtopcategory->id, ['parent' => $topcategory->id]);
485 // Now delete the top category.
486 $DB->delete_records('question_categories', ['id' => $topcategory->id]);
490 return true;
494 * Creates a new category to save the questions in use.
496 * @param array $questionids of question ids
497 * @param object $newcontextid the context to create the saved category in.
498 * @param string $oldplace a textual description of the think being deleted,
499 * e.g. from get_context_name
500 * @param object $newcategory
501 * @return mixed false on
503 function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
504 global $DB;
506 // Make a category in the parent context to move the questions to.
507 if (is_null($newcategory)) {
508 $newcategory = new stdClass();
509 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
510 $newcategory->contextid = $newcontextid;
511 // Max length of column name in question_categories is 255.
512 $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
513 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
514 $newcategory->sortorder = 999;
515 $newcategory->stamp = make_unique_id_code();
516 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
519 // Move any remaining questions to the 'saved' category.
520 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
521 return false;
523 return $newcategory;
527 * All question categories and their questions are deleted for this activity.
529 * @param object $cm the course module object representing the activity
530 * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
531 * @return boolean
533 function question_delete_activity($cm, $notused = false): bool {
534 $modcontext = context_module::instance($cm->id);
535 question_delete_context($modcontext->id);
536 return true;
540 * This function will handle moving all tag instances to a new context for a
541 * given list of questions.
543 * Questions can be tagged in up to two contexts:
544 * 1.) The context the question exists in.
545 * 2.) The course context (if the question context is a higher context.
546 * E.g. course category context or system context.
548 * This means a question that exists in a higher context (e.g. course cat or
549 * system context) may have multiple groups of tags in any number of child
550 * course contexts.
552 * Questions in the course category context can be move "down" a context level
553 * into one of their child course contexts or activity contexts which affects the
554 * availability of that question in other courses / activities.
556 * In this case it makes the questions no longer available in the other course or
557 * activity contexts so we need to make sure that the tag instances in those other
558 * contexts are removed.
560 * @param stdClass[] $questions The list of question being moved (must include
561 * the id and contextid)
562 * @param context $newcontext The Moodle context the questions are being moved to
564 function question_move_question_tags_to_new_context(array $questions, context $newcontext): void {
565 // If the questions are moving to a new course/activity context then we need to
566 // find any existing tag instances from any unavailable course contexts and
567 // delete them because they will no longer be applicable (we don't support
568 // tagging questions across courses).
569 $instancestodelete = [];
570 $instancesfornewcontext = [];
571 $newcontextparentids = $newcontext->get_parent_context_ids();
572 $questionids = array_map(function($question) {
573 return $question->id;
574 }, $questions);
575 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
577 foreach ($questions as $question) {
578 $tagobjects = $questionstagobjects[$question->id] ?? [];
580 foreach ($tagobjects as $tagobject) {
581 $tagid = $tagobject->taginstanceid;
582 $tagcontextid = $tagobject->taginstancecontextid;
583 $istaginnewcontext = $tagcontextid == $newcontext->id;
584 $istaginquestioncontext = $tagcontextid == $question->contextid;
586 if ($istaginnewcontext) {
587 // This tag instance is already in the correct context so we can
588 // ignore it.
589 continue;
592 if ($istaginquestioncontext) {
593 // This tag instance is in the question context so it needs to be
594 // updated.
595 $instancesfornewcontext[] = $tagid;
596 continue;
599 // These tag instances are in neither the new context nor the
600 // question context so we need to determine what to do based on
601 // the context they are in and the new question context.
602 $tagcontext = context::instance_by_id($tagcontextid);
603 $tagcoursecontext = $tagcontext->get_course_context(false);
604 // The tag is in a course context if get_course_context() returns
605 // itself.
606 $istaginstancecontextcourse = !empty($tagcoursecontext)
607 && $tagcontext->id == $tagcoursecontext->id;
609 if ($istaginstancecontextcourse) {
610 // If the tag instance is in a course context we need to add some
611 // special handling.
612 $tagcontextparentids = $tagcontext->get_parent_context_ids();
613 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
614 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
616 if ($isnewcontextaparent) {
617 // If the tag instance is a course context tag and the new
618 // context is still a parent context to the tag context then
619 // we can leave this tag where it is.
620 continue;
621 } else if ($isnewcontextachild) {
622 // If the new context is a child context (e.g. activity) of this
623 // tag instance then we should move all of this tag instance
624 // down into the activity context along with the question.
625 $instancesfornewcontext[] = $tagid;
626 } else {
627 // If the tag is in a course context that is no longer a parent
628 // or child of the new context then this tag instance should be
629 // removed.
630 $instancestodelete[] = $tagid;
632 } else {
633 // This is a catch all for any tag instances not in the question
634 // context or a course context. These tag instances should be
635 // updated to the new context id. This will clean up old invalid
636 // data.
637 $instancesfornewcontext[] = $tagid;
642 if (!empty($instancestodelete)) {
643 // Delete any course context tags that may no longer be valid.
644 core_tag_tag::delete_instances_by_id($instancestodelete);
647 if (!empty($instancesfornewcontext)) {
648 // Update the tag instances to the new context id.
649 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
654 * Check if an idnumber exist in the category.
656 * @param int $questionidnumber
657 * @param int $categoryid
658 * @param int $limitfrom
659 * @param int $limitnum
660 * @return array
662 function idnumber_exist_in_question_category($questionidnumber, $categoryid, $limitfrom = 0, $limitnum = 1): array {
663 global $DB;
664 $response = false;
665 $record = [];
666 // Check if the idnumber exist in the category.
667 $sql = 'SELECT qbe.idnumber
668 FROM {question_bank_entries} qbe
669 WHERE qbe.idnumber LIKE ?
670 AND qbe.questioncategoryid = ?
671 ORDER BY qbe.idnumber DESC';
672 $questionrecord = $DB->record_exists_sql($sql, [$questionidnumber, $categoryid]);
673 if ((string) $questionidnumber !== '' && $questionrecord) {
674 $record = $DB->get_records_sql($sql, [$questionidnumber . '_%', $categoryid], 0, 1);
675 $response = true;
678 return [$response, $record];
682 * This function should be considered private to the question bank, it is called from
683 * question/editlib.php question/contextmoveq.php and a few similar places to to the
684 * work of actually moving questions and associated data. However, callers of this
685 * function also have to do other work, which is why you should not call this method
686 * directly from outside the questionbank.
688 * @param array $questionids of question ids.
689 * @param integer $newcategoryid the id of the category to move to.
690 * @return bool
692 function question_move_questions_to_category($questionids, $newcategoryid): bool {
693 global $DB;
695 $newcategorydata = $DB->get_record('question_categories', ['id' => $newcategoryid]);
696 if (!$newcategorydata) {
697 return false;
699 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
701 $sql = "SELECT qv.id as versionid,
702 qbe.id as entryid,
703 qc.id as category,
704 qc.contextid as contextid,
705 q.id,
706 q.qtype,
707 qbe.idnumber
708 FROM {question} q
709 JOIN {question_versions} qv ON qv.questionid = q.id
710 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
711 JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
712 WHERE q.id $questionidcondition
713 OR (q.parent <> 0 AND q.parent $questionidcondition)";
715 // Also, we need to move children questions.
716 $params = array_merge($params, $params);
717 $questions = $DB->get_records_sql($sql, $params);
718 foreach ($questions as $question) {
719 if ($newcategorydata->contextid != $question->contextid) {
720 question_bank::get_qtype($question->qtype)->move_files(
721 $question->id, $question->contextid, $newcategorydata->contextid);
723 // Check whether there could be a clash of idnumbers in the new category.
724 list($idnumberclash, $rec) = idnumber_exist_in_question_category($question->idnumber, $newcategoryid);
725 if ($idnumberclash) {
726 $unique = 1;
727 if (count($rec)) {
728 $rec = reset($rec);
729 $idnumber = $rec->idnumber;
730 if (strpos($idnumber, '_') !== false) {
731 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
734 // For the move process, add a numerical increment to the idnumber. This means that if a question is
735 // mistakenly moved then the idnumber will not be completely lost.
736 $qbankentry = new stdClass();
737 $qbankentry->id = $question->entryid;
738 $qbankentry->idnumber = $question->idnumber . '_' . $unique;
739 $DB->update_record('question_bank_entries', $qbankentry);
742 // Update the entry to the new category id.
743 $entry = new stdClass();
744 $entry->id = $question->entryid;
745 $entry->questioncategoryid = $newcategorydata->id;
746 $DB->update_record('question_bank_entries', $entry);
748 // Log this question move.
749 $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
750 ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategorydata->id]);
751 $event->trigger();
754 $newcontext = context::instance_by_id($newcategorydata->contextid);
755 question_move_question_tags_to_new_context($questions, $newcontext);
757 // TODO Deal with datasets.
759 // Purge these questions from the cache.
760 foreach ($questions as $question) {
761 question_bank::notify_question_edited($question->id);
764 return true;
768 * Update the questioncontextid field for all question_set_references records given a new context id
770 * @param int $oldcategoryid Old category to be moved.
771 * @param int $newcatgoryid New category that will receive the questions.
772 * @param int $oldcontextid Old context to be moved.
773 * @param int $newcontextid New context that will receive the questions.
774 * @param bool $delete If the action is delete.
775 * @throws dml_exception
777 function move_question_set_references(int $oldcategoryid, int $newcatgoryid,
778 int $oldcontextid, int $newcontextid, bool $delete = false): void {
779 global $DB;
781 if ($delete || $oldcontextid !== $newcontextid) {
782 $setreferences = $DB->get_recordset('question_set_references', ['questionscontextid' => $oldcontextid]);
783 foreach ($setreferences as $setreference) {
784 $filter = json_decode($setreference->filtercondition);
785 if (isset($filter->questioncategoryid)) {
786 if ((int)$filter->questioncategoryid === $oldcategoryid) {
787 $setreference->questionscontextid = $newcontextid;
788 if ($oldcategoryid !== $newcatgoryid) {
789 $filter->questioncategoryid = $newcatgoryid;
790 $setreference->filtercondition = json_encode($filter);
792 $DB->update_record('question_set_references', $setreference);
796 $setreferences->close();
801 * This function helps move a question cateogry to a new context by moving all
802 * the files belonging to all the questions to the new context.
803 * Also moves subcategories.
804 * @param integer $categoryid the id of the category being moved.
805 * @param integer $oldcontextid the old context id.
806 * @param integer $newcontextid the new context id.
808 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid): void {
809 global $DB;
811 $questions = [];
812 $sql = "SELECT q.id, q.qtype
813 FROM {question} q
814 JOIN {question_versions} qv ON qv.questionid = q.id
815 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
816 WHERE qbe.questioncategoryid = ?";
818 $questionids = $DB->get_records_sql_menu($sql, [$categoryid]);
819 foreach ($questionids as $questionid => $qtype) {
820 question_bank::get_qtype($qtype)->move_files($questionid, $oldcontextid, $newcontextid);
821 // Purge this question from the cache.
822 question_bank::notify_question_edited($questionid);
824 $questions[] = (object) [
825 'id' => $questionid,
826 'contextid' => $oldcontextid
830 $newcontext = context::instance_by_id($newcontextid);
831 question_move_question_tags_to_new_context($questions, $newcontext);
833 $subcatids = $DB->get_records_menu('question_categories', ['parent' => $categoryid], '', 'id,1');
834 foreach ($subcatids as $subcatid => $notused) {
835 $DB->set_field('question_categories', 'contextid', $newcontextid, ['id' => $subcatid]);
836 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
841 * Given a list of ids, load the basic information about a set of questions from
842 * the questions table. The $join and $extrafields arguments can be used together
843 * to pull in extra data. See, for example, the usage in {@see \mod_quiz\quiz_attempt}, and
844 * read the code below to see how the SQL is assembled. Throws exceptions on error.
846 * @param array $questionids array of question ids to load. If null, then all
847 * questions matched by $join will be loaded.
848 * @param string $extrafields extra SQL code to be added to the query.
849 * @param string $join extra SQL code to be added to the query.
850 * @param array $extraparams values for any placeholders in $join.
851 * You must use named placeholders.
852 * @param string $orderby what to order the results by. Optional, default is unspecified order.
854 * @return array partially complete question objects. You need to call get_question_options
855 * on them before they can be properly used.
857 function question_preload_questions($questionids = null, $extrafields = '', $join = '', $extraparams = [], $orderby = ''): array {
858 global $DB;
860 if ($questionids === null) {
861 $extracondition = '';
862 $params = [];
863 } else {
864 if (empty($questionids)) {
865 return [];
868 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED, 'qid0000');
869 $extracondition = 'WHERE q.id ' . $questionidcondition;
872 if ($join) {
873 $join = 'JOIN ' . $join;
876 if ($extrafields) {
877 $extrafields = ', ' . $extrafields;
880 if ($orderby) {
881 $orderby = 'ORDER BY ' . $orderby;
884 $sql = "SELECT q.*,
885 qc.id as category,
886 qv.status,
887 qv.id as versionid,
888 qv.version,
889 qv.questionbankentryid,
890 qc.contextid as contextid
891 {$extrafields}
892 FROM {question} q
893 JOIN {question_versions} qv
894 ON qv.questionid = q.id
895 JOIN {question_bank_entries} qbe
896 ON qbe.id = qv.questionbankentryid
897 JOIN {question_categories} qc
898 ON qc.id = qbe.questioncategoryid
899 {$join}
900 {$extracondition}
901 {$orderby}";
903 // Load the questions.
904 $questions = $DB->get_records_sql($sql, $extraparams + $params);
905 foreach ($questions as $question) {
906 $question->_partiallyloaded = true;
909 return $questions;
913 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
914 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
915 * read the code below to see how the SQL is assembled. Throws exceptions on error.
917 * @param array $questionids array of question ids.
918 * @param string $extrafields extra SQL code to be added to the query.
919 * @param string $join extra SQL code to be added to the query.
920 * @return array|string question objects.
922 function question_load_questions($questionids, $extrafields = '', $join = '') {
923 $questions = question_preload_questions($questionids, $extrafields, $join);
925 // Load the question type specific information.
926 if (!get_question_options($questions)) {
927 return get_string('questionloaderror', 'question');
930 return $questions;
934 * Private function to factor common code out of get_question_options().
936 * @param object $question the question to tidy.
937 * @param stdClass $category The question_categories record for the given $question.
938 * @param \core_tag_tag[]|null $tagobjects The tags for the given $question.
939 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
941 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null): void {
942 // Convert numeric fields to float. This prevents these being displayed as 1.0000000.
943 $question->defaultmark += 0;
944 $question->penalty += 0;
946 // Indicate the question is now fully initialised.
947 if (isset($question->_partiallyloaded)) {
948 unset($question->_partiallyloaded);
951 $question->categoryobject = $category;
953 // Add any tags we have been passed.
954 if (!is_null($tagobjects)) {
955 $categorycontext = context::instance_by_id($category->contextid);
956 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
957 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
958 $question->coursetags = $sortedtagobjects->coursetags;
959 $question->tagobjects = $sortedtagobjects->tagobjects;
960 $question->tags = $sortedtagobjects->tags;
963 // Load question-type specific fields.
964 if (question_bank::is_qtype_installed($question->qtype)) {
965 question_bank::get_qtype($question->qtype)->get_question_options($question);
966 } else {
967 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
968 'qtype_missingtype')) . $question->questiontext;
973 * Updates the question objects with question type specific
974 * information by calling {@see get_question_options()}
976 * Can be called either with an array of question objects or with a single
977 * question object.
979 * @param mixed $questions Either an array of question objects to be updated
980 * or just a single question object
981 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
982 * @param stdClass[] $filtercourses The courses to filter the course tags by.
983 * @return bool Indicates success or failure.
985 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
986 global $DB;
988 $questionlist = is_array($questions) ? $questions : [$questions];
989 $categoryids = [];
990 $questionids = [];
992 if (empty($questionlist)) {
993 return true;
996 foreach ($questionlist as $question) {
997 $questionids[] = $question->id;
998 if (isset($question->category)) {
999 $qcategoryid = $question->category;
1000 } else {
1001 $qcategoryid = get_question_bank_entry($question->id)->questioncategoryid;
1002 $question->questioncategoryid = $qcategoryid;
1005 if (!in_array($qcategoryid, $categoryids)) {
1006 $categoryids[] = $qcategoryid;
1010 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
1012 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
1013 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
1014 } else {
1015 $tagobjectsbyquestion = null;
1018 foreach ($questionlist as $question) {
1019 if (is_null($tagobjectsbyquestion)) {
1020 $tagobjects = null;
1021 } else {
1022 $tagobjects = $tagobjectsbyquestion[$question->id];
1024 $qcategoryid = $question->category ?? $question->questioncategoryid ??
1025 get_question_bank_entry($question->id)->questioncategoryid;
1027 _tidy_question($question, $categories[$qcategoryid], $tagobjects, $filtercourses);
1030 return true;
1034 * Sort question tags by course or normal tags.
1036 * This function also search tag instances that may have a context id that don't match either a course or
1037 * question context and fix the data setting the correct context id.
1039 * @param \core_tag_tag[] $tagobjects The tags for the given $question.
1040 * @param stdClass $categorycontext The question categories context.
1041 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1042 * @return stdClass $sortedtagobjects Sorted tag objects.
1044 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null): stdClass {
1046 // Questions can have two sets of tag instances. One set at the
1047 // course context level and another at the context the question
1048 // belongs to (e.g. course category, system etc).
1049 $sortedtagobjects = new stdClass();
1050 $sortedtagobjects->coursetagobjects = [];
1051 $sortedtagobjects->coursetags = [];
1052 $sortedtagobjects->tagobjects = [];
1053 $sortedtagobjects->tags = [];
1054 $taginstanceidstonormalise = [];
1055 $filtercoursecontextids = [];
1056 $hasfiltercourses = !empty($filtercourses);
1058 if ($hasfiltercourses) {
1059 // If we're being asked to filter the course tags by a set of courses
1060 // then get the context ids to filter below.
1061 $filtercoursecontextids = array_map(function($course) {
1062 $coursecontext = context_course::instance($course->id);
1063 return $coursecontext->id;
1064 }, $filtercourses);
1067 foreach ($tagobjects as $tagobject) {
1068 $tagcontextid = $tagobject->taginstancecontextid;
1069 $tagcontext = context::instance_by_id($tagcontextid);
1070 $tagcoursecontext = $tagcontext->get_course_context(false);
1071 // This is a course tag if the tag context is a course context which
1072 // doesn't match the question's context. Any tag in the question context
1073 // is not considered a course tag, it belongs to the question.
1074 $iscoursetag = $tagcoursecontext
1075 && $tagcontext->id == $tagcoursecontext->id
1076 && $tagcontext->id != $categorycontext->id;
1078 if ($iscoursetag) {
1079 // Any tag instance in a course context level is considered a course tag.
1080 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1081 // Add the tag to the list of course tags if we aren't being
1082 // asked to filter or if this tag is in the list of courses
1083 // we're being asked to filter by.
1084 $sortedtagobjects->coursetagobjects[] = $tagobject;
1085 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1087 } else {
1088 // All non course context level tag instances or tags in the question
1089 // context belong to the context that the question was created in.
1090 $sortedtagobjects->tagobjects[] = $tagobject;
1091 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1093 // Due to legacy tag implementations that don't force the recording
1094 // of a context id, some tag instances may have context ids that don't
1095 // match either a course context or the question context. In this case
1096 // we should take the opportunity to fix up the data and set the correct
1097 // context id.
1098 if ($tagcontext->id != $categorycontext->id) {
1099 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1100 // Update the object properties to reflect the DB update that will
1101 // happen below.
1102 $tagobject->taginstancecontextid = $categorycontext->id;
1107 if (!empty($taginstanceidstonormalise)) {
1108 // If we found any tag instances with incorrect context id data then we can
1109 // correct those values now by setting them to the question context id.
1110 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1113 return $sortedtagobjects;
1117 * Print the icon for the question type
1119 * @param object $question The question object for which the icon is required.
1120 * Only $question->qtype is used.
1121 * @return string the HTML for the img tag.
1123 function print_question_icon($question): string {
1124 global $PAGE;
1126 if (gettype($question->qtype) == 'object') {
1127 $qtype = $question->qtype->name();
1128 } else {
1129 // Assume string.
1130 $qtype = $question->qtype;
1133 return $PAGE->get_renderer('question', 'bank')->qtype_icon($qtype);
1136 // CATEGORY FUNCTIONS.
1139 * Returns the categories with their names ordered following parent-child relationships.
1140 * finally it tries to return pending categories (those being orphaned, whose parent is
1141 * incorrect) to avoid missing any category from original array.
1143 * @param array $categories
1144 * @param int $id
1145 * @param int $level
1146 * @return array
1148 function sort_categories_by_tree(&$categories, $id = 0, $level = 1): array {
1149 global $DB;
1151 $children = [];
1152 $keys = array_keys($categories);
1154 foreach ($keys as $key) {
1155 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1156 $children[$key] = $categories[$key];
1157 $categories[$key]->processed = true;
1158 $children = $children + sort_categories_by_tree(
1159 $categories, $children[$key]->id, $level + 1);
1162 // If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too.
1163 if ($level == 1) {
1164 foreach ($keys as $key) {
1165 // If not processed and it's a good candidate to start (because its parent doesn't exist in the course).
1166 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1167 array('contextid' => $categories[$key]->contextid,
1168 'id' => $categories[$key]->parent))) {
1169 $children[$key] = $categories[$key];
1170 $categories[$key]->processed = true;
1171 $children = $children + sort_categories_by_tree(
1172 $categories, $children[$key]->id, $level + 1);
1176 return $children;
1180 * Get the default category for the context.
1182 * @param integer $contextid a context id.
1183 * @return object|bool the default question category for that context, or false if none.
1185 function question_get_default_category($contextid) {
1186 global $DB;
1187 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1188 [$contextid], 'id', '*', 0, 1);
1189 if (!empty($category)) {
1190 return reset($category);
1191 } else {
1192 return false;
1197 * Gets the top category in the given context.
1198 * This function can optionally create the top category if it doesn't exist.
1200 * @param int $contextid A context id.
1201 * @param bool $create Whether create a top category if it doesn't exist.
1202 * @return bool|stdClass The top question category for that context, or false if none.
1204 function question_get_top_category($contextid, $create = false) {
1205 global $DB;
1206 $category = $DB->get_record('question_categories', ['contextid' => $contextid, 'parent' => 0]);
1208 if (!$category && $create) {
1209 // We need to make one.
1210 $category = new stdClass();
1211 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1212 $category->info = '';
1213 $category->contextid = $contextid;
1214 $category->parent = 0;
1215 $category->sortorder = 0;
1216 $category->stamp = make_unique_id_code();
1217 $category->id = $DB->insert_record('question_categories', $category);
1220 return $category;
1224 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1226 * @param array $contextids List of context ids
1227 * @return array
1229 function question_get_top_categories_for_contexts($contextids): array {
1230 global $DB;
1232 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1233 list($insql, $params) = $DB->get_in_or_equal($contextids);
1234 $sql = "SELECT $concatsql
1235 FROM {question_categories}
1236 WHERE contextid $insql
1237 AND parent = 0";
1239 $topcategories = $DB->get_fieldset_sql($sql, $params);
1241 return $topcategories;
1245 * Gets the default category in the most specific context.
1246 * If no categories exist yet then default ones are created in all contexts.
1248 * @param array $contexts The context objects for this context and all parent contexts.
1249 * @return object The default category - the category in the course context
1251 function question_make_default_categories($contexts): object {
1252 global $DB;
1253 static $preferredlevels = array(
1254 CONTEXT_COURSE => 4,
1255 CONTEXT_MODULE => 3,
1256 CONTEXT_COURSECAT => 2,
1257 CONTEXT_SYSTEM => 1,
1260 $toreturn = null;
1261 $preferredness = 0;
1262 // If it already exists, just return it.
1263 foreach ($contexts as $key => $context) {
1264 $topcategory = question_get_top_category($context->id, true);
1265 if (!$exists = $DB->record_exists("question_categories",
1266 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1267 // Otherwise, we need to make one.
1268 $category = new stdClass();
1269 $contextname = $context->get_context_name(false, true);
1270 // Max length of name field is 255.
1271 $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1272 $category->info = get_string('defaultinfofor', 'question', $contextname);
1273 $category->contextid = $context->id;
1274 $category->parent = $topcategory->id;
1275 // By default, all categories get this number, and are sorted alphabetically.
1276 $category->sortorder = 999;
1277 $category->stamp = make_unique_id_code();
1278 $category->id = $DB->insert_record('question_categories', $category);
1279 } else {
1280 $category = question_get_default_category($context->id);
1282 $thispreferredness = $preferredlevels[$context->contextlevel];
1283 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1284 $thispreferredness += 10;
1286 if ($thispreferredness > $preferredness) {
1287 $toreturn = $category;
1288 $preferredness = $thispreferredness;
1292 if (!is_null($toreturn)) {
1293 $toreturn = clone($toreturn);
1295 return $toreturn;
1299 * Get the list of categories.
1301 * @param int $categoryid
1302 * @return array of question category ids of the category and all subcategories.
1304 function question_categorylist($categoryid): array {
1305 global $DB;
1307 // Final list of category IDs.
1308 $categorylist = array();
1310 // A list of category IDs to check for any sub-categories.
1311 $subcategories = array($categoryid);
1313 while ($subcategories) {
1314 foreach ($subcategories as $subcategory) {
1315 // If anything from the temporary list was added already, then we have a loop.
1316 if (isset($categorylist[$subcategory])) {
1317 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1319 $categorylist[$subcategory] = $subcategory;
1322 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1324 $subcategories = $DB->get_records_select_menu('question_categories', "parent $in", $params,
1325 null, 'id,id AS id2');
1328 return $categorylist;
1332 * Get all parent categories of a given question category in decending order.
1333 * @param int $categoryid for which you want to find the parents.
1334 * @return array of question category ids of all parents categories.
1336 function question_categorylist_parents(int $categoryid): array {
1337 global $DB;
1338 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1339 if (!$parent) {
1340 return [];
1342 $categorylist = [$parent];
1343 $currentid = $parent;
1344 while ($currentid) {
1345 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1346 if ($currentid) {
1347 $categorylist[] = $currentid;
1350 // Present the list in decending order (the top category at the top).
1351 $categorylist = array_reverse($categorylist);
1352 return $categorylist;
1355 // Import/Export Functions.
1358 * Get list of available import or export formats
1359 * @param string $type 'import' if import list, otherwise export list assumed
1360 * @return array sorted list of import/export formats available
1362 function get_import_export_formats($type): array {
1363 global $CFG;
1364 require_once($CFG->dirroot . '/question/format.php');
1366 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1368 $fileformatname = array();
1369 foreach ($formatclasses as $component => $formatclass) {
1371 $format = new $formatclass();
1372 if ($type == 'import') {
1373 $provided = $format->provide_import();
1374 } else {
1375 $provided = $format->provide_export();
1378 if ($provided) {
1379 list($notused, $fileformat) = explode('_', $component, 2);
1380 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1384 core_collator::asort($fileformatnames);
1385 return $fileformatnames;
1390 * Create a reasonable default file name for exporting questions from a particular
1391 * category.
1392 * @param object $course the course the questions are in.
1393 * @param object $category the question category.
1394 * @return string the filename.
1396 function question_default_export_filename($course, $category): string {
1397 // We build a string that is an appropriate name (questions) from the lang pack,
1398 // then the corse shortname, then the question category name, then a timestamp.
1400 $base = clean_filename(get_string('exportfilename', 'question'));
1402 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1403 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1405 $shortname = clean_filename($course->shortname);
1406 if ($shortname == '' || $shortname == '_' ) {
1407 $shortname = $course->id;
1410 $categoryname = clean_filename(format_string($category->name));
1412 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1416 * Check capability on category.
1418 * @param int|stdClass|question_definition $questionorid object or id.
1419 * If an object is passed, it should include ->contextid and ->createdby.
1420 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1421 * @param int $notused no longer used.
1422 * @return bool this user has the capability $cap for this question $question?
1424 function question_has_capability_on($questionorid, $cap, $notused = -1): bool {
1425 global $USER, $DB;
1427 if (is_numeric($questionorid)) {
1428 $questionid = (int)$questionorid;
1429 } else if (is_object($questionorid)) {
1430 // All we really need in this function is the contextid and author of the question.
1431 // We won't bother fetching other details of the question if these 2 fields are provided.
1432 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1433 $question = $questionorid;
1434 } else if (!empty($questionorid->id)) {
1435 $questionid = $questionorid->id;
1439 // At this point, either $question or $questionid is expected to be set.
1440 if (isset($questionid)) {
1441 try {
1442 $question = question_bank::load_question_data($questionid);
1443 } catch (Exception $e) {
1444 // Let's log the exception for future debugging,
1445 // but not during Behat, or we can't test these cases.
1446 if (!defined('BEHAT_SITE_RUNNING')) {
1447 debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1450 $sql = 'SELECT q.id,
1451 q.createdby,
1452 qc.contextid
1453 FROM {question} q
1454 JOIN {question_versions} qv
1455 ON qv.questionid = q.id
1456 JOIN {question_bank_entries} qbe
1457 ON qbe.id = qv.questionbankentryid
1458 JOIN {question_categories} qc
1459 ON qc.id = qbe.questioncategoryid
1460 WHERE q.id = :id';
1462 // Well, at least we tried. Seems that we really have to read from DB.
1463 $question = $DB->get_record_sql($sql, ['id' => $questionid]);
1467 if (!isset($question)) {
1468 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1471 $context = context::instance_by_id($question->contextid);
1473 // These are existing questions capabilities that are set per category.
1474 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1475 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1477 if (!isset($capabilitieswithallandmine[$cap])) {
1478 return has_capability('moodle/question:' . $cap, $context);
1479 } else {
1480 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1481 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1486 * Require capability on question.
1488 * @param int|stdClass|question_definition $question object or id.
1489 * If an object is passed, it should include ->contextid and ->createdby.
1490 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1491 * @return bool true if the user has the capability. Throws exception if not.
1493 function question_require_capability_on($question, $cap): bool {
1494 if (!question_has_capability_on($question, $cap)) {
1495 throw new moodle_exception('nopermissions', '', '', $cap);
1497 return true;
1501 * Gets the question edit url.
1503 * @param object $context a context
1504 * @return string|bool A URL for editing questions in this context.
1506 function question_edit_url($context) {
1507 global $CFG, $SITE;
1508 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1509 return false;
1511 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1512 $defaultcategory = question_get_default_category($context->id);
1513 if ($defaultcategory) {
1514 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1516 switch ($context->contextlevel) {
1517 case CONTEXT_SYSTEM:
1518 return $baseurl . 'courseid=' . $SITE->id;
1519 case CONTEXT_COURSECAT:
1520 // This is nasty, becuase we can only edit questions in a course
1521 // context at the moment, so for now we just return false.
1522 return false;
1523 case CONTEXT_COURSE:
1524 return $baseurl . 'courseid=' . $context->instanceid;
1525 case CONTEXT_MODULE:
1526 return $baseurl . 'cmid=' . $context->instanceid;
1532 * Adds question bank setting links to the given navigation node if caps are met
1533 * and loads the navigation from the plugins.
1534 * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1535 * this method will help to autoload those nodes in the question bank navigation.
1537 * @param navigation_node $navigationnode The navigation node to add the question branch to
1538 * @param object $context
1539 * @param string $baseurl the url of the base where the api is implemented from
1540 * @return navigation_node Returns the question branch that was added
1542 function question_extend_settings_navigation(navigation_node $navigationnode, $context, $baseurl = '/question/edit.php') {
1543 global $PAGE;
1545 if ($context->contextlevel == CONTEXT_COURSE) {
1546 $params = ['courseid' => $context->instanceid];
1547 } else if ($context->contextlevel == CONTEXT_MODULE) {
1548 $params = ['cmid' => $context->instanceid];
1549 } else {
1550 return;
1553 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1554 $params['cat'] = $cat;
1557 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1558 new moodle_url($baseurl, $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1560 $corenavigations = [
1561 'questions' => [
1562 'title' => get_string('questions', 'question'),
1563 'url' => new moodle_url($baseurl)
1565 'categories' => [],
1566 'import' => [],
1567 'export' => []
1570 $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1571 foreach ($plugins as $componentname => $plugin) {
1572 $pluginentrypoint = new $plugin();
1573 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1574 // Don't need the plugins without navigation node.
1575 if ($pluginentrypointobject === null) {
1576 unset($plugins[$componentname]);
1577 continue;
1579 foreach ($corenavigations as $key => $corenavigation) {
1580 if ($pluginentrypointobject->get_navigation_key() === $key) {
1581 unset($plugins[$componentname]);
1582 if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1583 unset($corenavigations[$key]);
1584 break;
1586 $corenavigations[$key] = [
1587 'title' => $pluginentrypointobject->get_navigation_title(),
1588 'url' => $pluginentrypointobject->get_navigation_url()
1594 // Mitigate the risk of regression.
1595 foreach ($corenavigations as $node => $corenavigation) {
1596 if (empty($corenavigation)) {
1597 unset($corenavigations[$node]);
1601 // Community/additional plugins have navigation node.
1602 $pluginnavigations = [];
1603 foreach ($plugins as $componentname => $plugin) {
1604 $pluginentrypoint = new $plugin();
1605 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1606 // Don't need the plugins without navigation node.
1607 if ($pluginentrypointobject === null || !\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1608 unset($plugins[$componentname]);
1609 continue;
1611 $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1612 'title' => $pluginentrypointobject->get_navigation_title(),
1613 'url' => $pluginentrypointobject->get_navigation_url(),
1614 'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1618 $contexts = new core_question\local\bank\question_edit_contexts($context);
1619 foreach ($corenavigations as $key => $corenavigation) {
1620 if ($contexts->have_one_edit_tab_cap($key)) {
1621 $questionnode->add($corenavigation['title'], new moodle_url(
1622 $corenavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1626 foreach ($pluginnavigations as $key => $pluginnavigation) {
1627 if (is_array($pluginnavigation['capabilities'])) {
1628 if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1629 continue;
1632 $questionnode->add($pluginnavigation['title'], new moodle_url(
1633 $pluginnavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1636 return $questionnode;
1640 * Get the array of capabilities for question.
1642 * @return array all the capabilities that relate to accessing particular questions.
1644 function question_get_question_capabilities(): array {
1645 return [
1646 'moodle/question:add',
1647 'moodle/question:editmine',
1648 'moodle/question:editall',
1649 'moodle/question:viewmine',
1650 'moodle/question:viewall',
1651 'moodle/question:usemine',
1652 'moodle/question:useall',
1653 'moodle/question:movemine',
1654 'moodle/question:moveall',
1655 'moodle/question:tagmine',
1656 'moodle/question:tagall',
1657 'moodle/question:commentmine',
1658 'moodle/question:commentall',
1663 * Get the question bank caps.
1665 * @return array all the question bank capabilities.
1667 function question_get_all_capabilities(): array {
1668 $caps = question_get_question_capabilities();
1669 $caps[] = 'moodle/question:managecategory';
1670 $caps[] = 'moodle/question:flag';
1671 return $caps;
1675 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1677 * @package core_question
1678 * @category files
1679 * @param string $text text being processed
1680 * @param string $file the php script used to serve files
1681 * @param int $contextid context ID
1682 * @param string $component component
1683 * @param string $filearea filearea
1684 * @param array $ids other IDs will be used to check file permission
1685 * @param int $itemid item ID
1686 * @param array $options options
1687 * @return string
1689 function question_rewrite_question_urls($text, $file, $contextid, $component, $filearea,
1690 array $ids, $itemid, array $options=null): string {
1692 $idsstr = '';
1693 if (!empty($ids)) {
1694 $idsstr .= implode('/', $ids);
1696 if ($itemid !== null) {
1697 $idsstr .= '/' . $itemid;
1699 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1700 $filearea, $idsstr, $options);
1704 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1705 * viewing the question outside an attempt (for example, in the question bank
1706 * listing or in the quiz statistics report).
1708 * @param string $text the question text.
1709 * @param int $questionid the question id.
1710 * @param int $filecontextid the context id of the question being displayed.
1711 * @param string $filecomponent the component that owns the file area.
1712 * @param string $filearea the file area name.
1713 * @param int|null $itemid the file's itemid
1714 * @param int $previewcontextid the context id where the preview is being displayed.
1715 * @param string $previewcomponent component responsible for displaying the preview.
1716 * @param array $options text and file options ('forcehttps'=>false)
1717 * @return string $questiontext with URLs rewritten.
1719 function question_rewrite_question_preview_urls($text, $questionid, $filecontextid, $filecomponent, $filearea, $itemid,
1720 $previewcontextid, $previewcomponent, $options = null): string {
1722 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1723 if ($itemid) {
1724 $path .= '/' . $itemid;
1727 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1728 $filecomponent, $filearea, $path, $options);
1732 * Called by pluginfile.php to serve files related to the 'question' core
1733 * component and for files belonging to qtypes.
1735 * For files that relate to questions in a question_attempt, then we delegate to
1736 * a function in the component that owns the attempt (for example in the quiz,
1737 * or in core question preview) to get necessary inforation.
1739 * (Note that, at the moment, all question file areas relate to questions in
1740 * attempts, so the If at the start of the last paragraph is always true.)
1742 * Does not return, either calls send_file_not_found(); or serves the file.
1744 * @category files
1745 * @param stdClass $course course settings object
1746 * @param stdClass $context context object
1747 * @param string $component the name of the component we are serving files for.
1748 * @param string $filearea the name of the file area.
1749 * @param array $args the remaining bits of the file path.
1750 * @param bool $forcedownload whether the user must be forced to download the file.
1751 * @param array $options additional options affecting the file serving
1752 * @return array|bool
1754 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, $options = []) {
1755 global $DB, $CFG;
1757 // Special case, sending a question bank export.
1758 if ($filearea === 'export') {
1759 list($context, $course, $cm) = get_context_info_array($context->id);
1760 require_login($course, false, $cm);
1762 require_once($CFG->dirroot . '/question/editlib.php');
1763 $contexts = new core_question\local\bank\question_edit_contexts($context);
1764 // Check export capability.
1765 $contexts->require_one_edit_tab_cap('export');
1766 $categoryid = (int)array_shift($args);
1767 $format = array_shift($args);
1768 $cattofile = array_shift($args);
1769 $contexttofile = array_shift($args);
1770 $filename = array_shift($args);
1772 // Load parent class for import/export.
1773 require_once($CFG->dirroot . '/question/format.php');
1774 require_once($CFG->dirroot . '/question/editlib.php');
1775 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1777 $classname = 'qformat_' . $format;
1778 if (!class_exists($classname)) {
1779 send_file_not_found();
1782 $qformat = new $classname();
1784 if (!$category = $DB->get_record('question_categories', array('id' => $categoryid))) {
1785 send_file_not_found();
1788 $qformat->setCategory($category);
1789 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1790 $qformat->setCourse($course);
1792 if ($cattofile == 'withcategories') {
1793 $qformat->setCattofile(true);
1794 } else {
1795 $qformat->setCattofile(false);
1798 if ($contexttofile == 'withcontexts') {
1799 $qformat->setContexttofile(true);
1800 } else {
1801 $qformat->setContexttofile(false);
1804 if (!$qformat->exportpreprocess()) {
1805 send_file_not_found();
1806 throw new moodle_exception('exporterror', 'question', $thispageurl->out());
1809 // Export data to moodle file pool.
1810 if (!$content = $qformat->exportprocess()) {
1811 send_file_not_found();
1814 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1817 // Normal case, a file belonging to a question.
1818 $qubaidorpreview = array_shift($args);
1820 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1821 if ($qubaidorpreview === 'preview') {
1822 $previewcontextid = (int)array_shift($args);
1823 $previewcomponent = array_shift($args);
1824 $questionid = (int) array_shift($args);
1825 $previewcontext = context_helper::instance_by_id($previewcontextid);
1827 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1828 $previewcontext, $questionid,
1829 $context, $component, $filearea, $args,
1830 $forcedownload, $options), 'callbackmissing');
1832 if ($result === 'callbackmissing') {
1833 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1834 "{$previewcomponent}_question_preview_pluginfile callback. " .
1835 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
1838 send_file_not_found();
1841 // 2. A question being attempted in the normal way.
1842 $qubaid = (int)$qubaidorpreview;
1843 $slot = (int)array_shift($args);
1845 $module = $DB->get_field('question_usages', 'component',
1846 array('id' => $qubaid));
1847 if (!$module) {
1848 send_file_not_found();
1851 if ($module === 'core_question_preview') {
1852 return qbank_previewquestion\helper::question_preview_question_pluginfile($course, $context,
1853 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1855 } else {
1856 $dir = core_component::get_component_directory($module);
1857 if (!file_exists("$dir/lib.php")) {
1858 send_file_not_found();
1860 include_once("$dir/lib.php");
1862 $filefunction = $module . '_question_pluginfile';
1863 if (function_exists($filefunction)) {
1864 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1865 $args, $forcedownload, $options);
1868 // Okay, we're here so lets check for function without 'mod_'.
1869 if (strpos($module, 'mod_') === 0) {
1870 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1871 if (function_exists($filefunctionold)) {
1872 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1873 $args, $forcedownload, $options);
1877 send_file_not_found();
1882 * Serve questiontext files in the question text when they are displayed in this report.
1884 * @param context $previewcontext the context in which the preview is happening.
1885 * @param int $questionid the question id.
1886 * @param context $filecontext the file (question) context.
1887 * @param string $filecomponent the component the file belongs to.
1888 * @param string $filearea the file area.
1889 * @param array $args remaining file args.
1890 * @param bool $forcedownload
1891 * @param array $options additional options affecting the file serving.
1893 function core_question_question_preview_pluginfile($previewcontext, $questionid, $filecontext, $filecomponent,
1894 $filearea, $args, $forcedownload, $options = []): void {
1895 global $DB;
1896 $sql = 'SELECT q.*,
1897 qc.contextid
1898 FROM {question} q
1899 JOIN {question_versions} qv
1900 ON qv.questionid = q.id
1901 JOIN {question_bank_entries} qbe
1902 ON qbe.id = qv.questionbankentryid
1903 JOIN {question_categories} qc
1904 ON qc.id = qbe.questioncategoryid
1905 WHERE q.id = :id
1906 AND qc.contextid = :contextid';
1908 // Verify that contextid matches the question.
1909 $question = $DB->get_record_sql($sql, ['id' => $questionid, 'contextid' => $filecontext->id], MUST_EXIST);
1911 // Check the capability.
1912 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
1913 require_login($course, false, $cm);
1915 question_require_capability_on($question, 'use');
1917 $fs = get_file_storage();
1918 $relativepath = implode('/', $args);
1919 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1920 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1921 send_file_not_found();
1924 send_stored_file($file, 0, 0, $forcedownload, $options);
1928 * Return a list of page types
1929 * @param string $pagetype current page type
1930 * @param stdClass $parentcontext Block's parent context
1931 * @param stdClass $currentcontext Current context of block
1932 * @return array
1934 function question_page_type_list($pagetype, $parentcontext, $currentcontext): array {
1935 global $CFG;
1936 $types = [
1937 'question-*' => get_string('page-question-x', 'question'),
1938 'question-edit' => get_string('page-question-edit', 'question'),
1939 'question-category' => get_string('page-question-category', 'question'),
1940 'question-export' => get_string('page-question-export', 'question'),
1941 'question-import' => get_string('page-question-import', 'question')
1943 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1944 require_once($CFG->dirroot . '/course/lib.php');
1945 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1946 } else {
1947 return $types;
1952 * Does an activity module use the question bank?
1954 * @param string $modname The name of the module (without mod_ prefix).
1955 * @return bool true if the module uses questions.
1957 function question_module_uses_questions($modname): bool {
1958 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
1959 return true;
1962 $component = 'mod_'.$modname;
1963 if (component_callback_exists($component, 'question_pluginfile')) {
1964 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
1965 return true;
1968 return false;
1972 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
1974 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
1975 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
1977 * @param string|null $oldidnumber a question idnumber, or can be null.
1978 * @param int $categoryid a question category id.
1979 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
1981 function core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid): ?string {
1982 global $DB;
1984 // The the old idnumber is not of the right form, bail now.
1985 if ($oldidnumber === null || !preg_match('~\d+$~', $oldidnumber, $matches)) {
1986 return null;
1989 // Find all used idnumbers in one DB query.
1990 $usedidnumbers = $DB->get_records_select_menu('question_bank_entries', 'questioncategoryid = ? AND idnumber IS NOT NULL',
1991 [$categoryid], '', 'idnumber, 1');
1993 // Find the next unused idnumber.
1994 $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
1995 $stem = substr($oldidnumber, 0, -strlen($matches[0]));
1996 do {
1998 // If we have got to something9999, insert an extra digit before incrementing.
1999 if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2000 $numberbit = $matches[1] . '0' . $matches[2];
2002 $numberbit++;
2003 $newidnumber = $stem . substr($numberbit, 1);
2004 } while (isset($usedidnumbers[$newidnumber]));
2006 return (string) $newidnumber;
2010 * Get the question_bank_entry object given a question id.
2012 * @param int $questionid Question id.
2013 * @return false|mixed
2014 * @throws dml_exception
2016 function get_question_bank_entry(int $questionid): object {
2017 global $DB;
2019 $sql = "SELECT qbe.*
2020 FROM {question} q
2021 JOIN {question_versions} qv ON qv.questionid = q.id
2022 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2023 WHERE q.id = :id";
2025 $qbankentry = $DB->get_record_sql($sql, ['id' => $questionid]);
2027 return $qbankentry;
2031 * Get the question versions given a question id in a descending sort .
2033 * @param int $questionid Question id.
2034 * @return array
2035 * @throws dml_exception
2037 function get_question_version($questionid): array {
2038 global $DB;
2040 $version = $DB->get_records('question_versions', ['questionid' => $questionid]);
2041 krsort($version);
2043 return $version;
2047 * Get the next version number to create base on a Question bank entry id.
2049 * @param int $questionbankentryid Question bank entry id.
2050 * @return int next version number.
2051 * @throws dml_exception
2053 function get_next_version(int $questionbankentryid): int {
2054 global $DB;
2056 $sql = "SELECT MAX(qv.version)
2057 FROM {question_versions} qv
2058 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2059 WHERE qbe.id = :id";
2061 $nextversion = $DB->get_field_sql($sql, ['id' => $questionbankentryid]);
2063 if ($nextversion) {
2064 return (int)$nextversion + 1;
2067 return 1;
2071 * Checks if question is the latest version.
2073 * @param string $version Question version to check.
2074 * @param string $questionbankentryid Entry to check against.
2075 * @return bool
2077 function is_latest(string $version, string $questionbankentryid) : bool {
2078 global $DB;
2080 $sql = 'SELECT MAX(version) AS max
2081 FROM {question_versions}
2082 WHERE questionbankentryid = ?';
2083 $latestversion = $DB->get_record_sql($sql, [$questionbankentryid]);
2085 if (isset($latestversion->max)) {
2086 return ($version === $latestversion->max) ? true : false;
2088 return false;
2091 // Deprecated functions from Moodle 4.0.
2094 * Generate the URL for starting a new preview of a given question with the given options.
2095 * @param integer $questionid the question to preview.
2096 * @param string $preferredbehaviour the behaviour to use for the preview.
2097 * @param float $maxmark the maximum to mark the question out of.
2098 * @param question_display_options $displayoptions the display options to use.
2099 * @param int $variant the variant of the question to preview. If null, one will
2100 * be picked randomly.
2101 * @param object $context context to run the preview in (affects things like
2102 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
2103 * @return moodle_url the URL.
2104 * @deprecated since Moodle 4.0
2105 * @see qbank_previewquestion\helper::question_preview_url()
2106 * @todo Final deprecation on Moodle 4.4 MDL-72438
2108 function question_preview_url($questionid, $preferredbehaviour = null,
2109 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
2110 debugging('Function question_preview_url() has been deprecated and moved to qbank_previewquestion plugin,
2111 Please use qbank_previewquestion\previewquestion_helper::question_preview_url() instead.', DEBUG_DEVELOPER);
2113 return \qbank_previewquestion\helper::question_preview_url($questionid, $preferredbehaviour,
2114 $maxmark, $displayoptions, $variant, $context);
2118 * Popup params for the question preview.
2120 * @return array that can be passed as $params to the {@see popup_action()} constructor.
2121 * @deprecated since Moodle 4.0
2122 * @see qbank_previewquestion\previewquestion_helper::question_preview_popup_params()
2123 * @todo Final deprecation on Moodle 4.4 MDL-72438
2125 function question_preview_popup_params() {
2126 debugging('Function question_preview_popup_params() has been deprecated and moved to qbank_previewquestion plugin,
2127 Please use qbank_previewquestion\previewquestion_helper::question_preview_popup_params() instead.', DEBUG_DEVELOPER);
2129 return \qbank_previewquestion\helper::question_preview_popup_params();
2133 * Creates a stamp that uniquely identifies this version of the question
2135 * In future we want this to use a hash of the question data to guarantee that
2136 * identical versions have the same version stamp.
2138 * @param object $question
2139 * @return string A unique version stamp
2140 * @deprecated since Moodle 4.0
2141 * @todo Final deprecation on Moodle 4.4 MDL-72438
2143 function question_hash($question) {
2144 debugging('Function question_hash() has been deprecated without replacement.', DEBUG_DEVELOPER);
2145 return make_unique_id_code();
2149 * Create url for question export.
2151 * @param int $contextid
2152 * @param int $categoryid
2153 * @param string $format
2154 * @param string $withcategories
2155 * @param string $withcontexts
2156 * @param string $filename
2157 * @return moodle_url export file url
2158 * @deprecated since Moodle 4.0 MDL-71573
2159 * @see qbank_exportquestions\exportquestions_helper
2160 * @todo Final deprecation on Moodle 4.4 MDL-72438
2162 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2163 $withcontexts, $filename) {
2164 debugging('Function question_make_export_url() has been deprecated and moved to qbank_exportquestions plugin,
2165 Please use qbank_exportquestions\exportquestions_helper::question_make_export_url() instead.', DEBUG_DEVELOPER);
2167 return \qbank_exportquestions\exportquestions_helper::question_make_export_url($contextid, $categoryid, $format,
2168 $withcategories, $withcontexts, $filename);
2172 * Get the URL to export a single question (exportone.php).
2174 * @param stdClass|question_definition $question the question definition as obtained from
2175 * question_bank::load_question_data() or question_bank::make_question().
2176 * (Only ->id and ->contextid are used.)
2177 * @return moodle_url the requested URL.
2178 * @deprecated since Moodle 4.0
2179 * @see \qbank_exporttoxml\helper::question_get_export_single_question_url()
2180 * @todo Final deprecation on Moodle 4.4 MDL-72438
2182 function question_get_export_single_question_url($question) {
2183 debugging('Function question_get_export_single_question_url() has been deprecated and moved to qbank_exporttoxml plugin,
2184 please use qbank_exporttoxml\helper::question_get_export_single_question_url() instead.', DEBUG_DEVELOPER);
2185 qbank_exporttoxml\helper::question_get_export_single_question_url($question);
2189 * Remove stale questions from a category.
2191 * While questions should not be left behind when they are not used any more,
2192 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
2193 * this happens, the users are unable to delete the question category unless
2194 * they move those stale questions to another one category, but to them the
2195 * category is empty as it does not contain anything. The purpose of this function
2196 * is to detect the questions that may have gone stale and remove them.
2198 * You will typically use this prior to checking if the category contains questions.
2200 * The stale questions (unused and hidden to the user) handled are:
2201 * - hidden questions
2202 * - random questions
2204 * @param int $categoryid The category ID.
2205 * @deprecated since Moodle 4.0 MDL-71585
2206 * @see qbank_managecategories\helper
2207 * @todo Final deprecation on Moodle 4.4 MDL-72438
2209 function question_remove_stale_questions_from_category($categoryid) {
2210 debugging('Function question_remove_stale_questions_from_category()
2211 has been deprecated and moved to qbank_managecategories plugin,
2212 Please use qbank_managecategories\helper::question_remove_stale_questions_from_category() instead.',
2213 DEBUG_DEVELOPER);
2214 \qbank_managecategories\helper::question_remove_stale_questions_from_category($categoryid);
2218 * Private method, only for the use of add_indented_names().
2220 * Recursively adds an indentedname field to each category, starting with the category
2221 * with id $id, and dealing with that category and all its children, and
2222 * return a new array, with those categories in the right order.
2224 * @param array $categories an array of categories which has had childids
2225 * fields added by flatten_category_tree(). Passed by reference for
2226 * performance only. It is not modfied.
2227 * @param int $id the category to start the indenting process from.
2228 * @param int $depth the indent depth. Used in recursive calls.
2229 * @param int $nochildrenof
2230 * @return array a new array of categories, in the right order for the tree.
2231 * @deprecated since Moodle 4.0 MDL-71585
2232 * @see qbank_managecategories\helper
2233 * @todo Final deprecation on Moodle 4.4 MDL-72438
2235 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
2236 debugging('Function flatten_category_tree() has been deprecated and moved to qbank_managecategories plugin,
2237 Please use qbank_managecategories\helper::flatten_category_tree() instead.', DEBUG_DEVELOPER);
2238 return \qbank_managecategories\helper::flatten_category_tree($categories, $id, $depth, $nochildrenof);
2242 * Format categories into an indented list reflecting the tree structure.
2244 * @param array $categories An array of category objects, for example from the.
2245 * @param int $nochildrenof
2246 * @return array The formatted list of categories.
2247 * @deprecated since Moodle 4.0 MDL-71585
2248 * @see qbank_managecategories\helper
2249 * @todo Final deprecation on Moodle 4.4 MDL-72438
2251 function add_indented_names($categories, $nochildrenof = -1) {
2252 debugging('Function add_indented_names() has been deprecated and moved to qbank_managecategories plugin,
2253 Please use qbank_managecategories\helper::add_indented_names() instead.', DEBUG_DEVELOPER);
2254 return \qbank_managecategories\helper::add_indented_names($categories, $nochildrenof);
2258 * Output a select menu of question categories.
2259 * Categories from this course and (optionally) published categories from other courses
2260 * are included. Optionally, only categories the current user may edit can be included.
2262 * @param array $contexts
2263 * @param bool $top
2264 * @param int $currentcat
2265 * @param integer $selected optionally, the id of a category to be selected by
2266 * default in the dropdown.
2267 * @param int $nochildrenof
2268 * @deprecated since Moodle 4.0 MDL-71585
2269 * @see qbank_managecategories\helper
2270 * @todo Final deprecation on Moodle 4.4 MDL-72438
2272 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
2273 $selected = "", $nochildrenof = -1) {
2274 debugging('Function question_category_select_menu() has been deprecated and moved to qbank_managecategories plugin,
2275 Please use qbank_managecategories\helper::question_category_select_menu() instead.', DEBUG_DEVELOPER);
2276 \qbank_managecategories\helper::question_category_select_menu($contexts, $top, $currentcat, $selected, $nochildrenof);
2280 * Get all the category objects, including a count of the number of questions in that category,
2281 * for all the categories in the lists $contexts.
2283 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
2284 * @param string $sortorder used as the ORDER BY clause in the select statement.
2285 * @param bool $top Whether to return the top categories or not.
2286 * @return array of category objects.
2287 * @deprecated since Moodle 4.0 MDL-71585
2288 * @see qbank_managecategories\helper
2289 * @todo Final deprecation on Moodle 4.4 MDL-72438
2291 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
2292 debugging('Function get_categories_for_contexts() has been deprecated and moved to qbank_managecategories plugin,
2293 Please use qbank_managecategories\helper::get_categories_for_contexts() instead.', DEBUG_DEVELOPER);
2294 return \qbank_managecategories\helper::get_categories_for_contexts($contexts, $sortorder, $top);
2298 * Output an array of question categories.
2300 * @param array $contexts The list of contexts.
2301 * @param bool $top Whether to return the top categories or not.
2302 * @param int $currentcat
2303 * @param bool $popupform
2304 * @param int $nochildrenof
2305 * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
2306 * @return array
2307 * @deprecated since Moodle 4.0 MDL-71585
2308 * @see qbank_managecategories\helper
2309 * @todo Final deprecation on Moodle 4.4 MDL-72438
2311 function question_category_options($contexts, $top = false, $currentcat = 0,
2312 $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
2313 debugging('Function question_category_options() has been deprecated and moved to qbank_managecategories plugin,
2314 Please use qbank_managecategories\helper::question_category_options() instead.', DEBUG_DEVELOPER);
2315 return \qbank_managecategories\helper::question_category_options($contexts, $top, $currentcat,
2316 $popupform, $nochildrenof, $escapecontextnames);
2320 * Add context in categories key.
2322 * @param array $categories The list of categories.
2323 * @return array
2324 * @deprecated since Moodle 4.0 MDL-71585
2325 * @see qbank_managecategories\helper
2326 * @todo Final deprecation on Moodle 4.4 MDL-72438
2328 function question_add_context_in_key($categories) {
2329 debugging('Function question_add_context_in_key() has been deprecated and moved to qbank_managecategories plugin,
2330 Please use qbank_managecategories\helper::question_add_context_in_key() instead.', DEBUG_DEVELOPER);
2331 return \qbank_managecategories\helper::question_add_context_in_key($categories);
2335 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
2337 * @param array $categories An array of question categories.
2338 * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
2339 * @return array The same question category list given to the function, with the top category names being translated.
2340 * @deprecated since Moodle 4.0 MDL-71585
2341 * @see qbank_managecategories\helper
2342 * @todo Final deprecation on Moodle 4.4 MDL-72438
2344 function question_fix_top_names($categories, $escape = true) {
2345 debugging('Function question_fix_top_names() has been deprecated and moved to qbank_managecategories plugin,
2346 Please use qbank_managecategories\helper::question_fix_top_names() instead.', DEBUG_DEVELOPER);
2347 return \qbank_managecategories\helper::question_fix_top_names($categories, $escape);