2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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
32 defined('MOODLE_INTERNAL') ||
die();
34 require_once($CFG->dirroot
. '/question/engine/lib.php');
35 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 * Constant determines the number of answer boxes supplied in the editing
43 * form for multiple choice and similar question types.
45 define("QUESTION_NUMANS", 10);
48 * Constant determines the number of answer boxes supplied in the editing
49 * form for multiple choice and similar question types to start with, with
50 * the option of adding QUESTION_NUMANS_ADD more answers.
52 define("QUESTION_NUMANS_START", 3);
55 * Constant determines the number of answer boxes to add in the editing
56 * form for multiple choice and similar question types when the user presses
57 * 'add form fields button'.
59 define("QUESTION_NUMANS_ADD", 3);
62 * Move one question type in a list of question types. If you try to move one element
63 * off of the end, nothing will change.
65 * @param array $sortedqtypes An array $qtype => anything.
66 * @param string $tomove one of the keys from $sortedqtypes
67 * @param integer $direction +1 or -1
68 * @return array an array $index => $qtype, with $index from 0 to n in order, and
69 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
70 * have been moved one place.
72 function question_reorder_qtypes($sortedqtypes, $tomove, $direction): array {
73 $neworder = array_keys($sortedqtypes);
74 // Find the element to move.
75 $key = array_search($tomove, $neworder);
79 // Work out the other index.
80 $otherkey = $key +
$direction;
81 if (!isset($neworder[$otherkey])) {
85 $swap = $neworder[$otherkey];
86 $neworder[$otherkey] = $neworder[$key];
87 $neworder[$key] = $swap;
92 * Save a new question type order to the config_plugins table.
94 * @param array $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
95 * @param object $config get_config('question'), if you happen to have it around, to save one DB query.
97 function question_save_qtype_order($neworder, $config = null): void
{
98 if (is_null($config)) {
99 $config = get_config('question');
102 foreach ($neworder as $index => $qtype) {
103 $sortvar = $qtype . '_sortorder';
104 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
105 set_config($sortvar, $index +
1, 'question');
113 * Check if the question is used.
115 * @param array $questionids of question ids.
116 * @return boolean whether any of these questions are being used by any part of Moodle.
118 function questions_in_use($questionids): bool {
120 // Are they used by the core question system?
121 if (question_engine
::questions_in_use($questionids)) {
125 // Check if any plugins are using these questions.
126 $callbacksbytype = get_plugins_with_function('questions_in_use');
127 foreach ($callbacksbytype as $callbacks) {
128 foreach ($callbacks as $function) {
129 if ($function($questionids)) {
135 // Finally check legacy callback.
136 $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
137 foreach ($legacycallbacks as $plugin => $function) {
138 debugging($plugin . ' implements deprecated method ' . $function .
139 '. ' . $plugin . '_questions_in_use should be implemented instead.', DEBUG_DEVELOPER
);
141 if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
142 continue; // Already done.
145 foreach ($questionids as $questionid) {
146 if (!empty($function($questionid))) {
156 * Determine whether there are any questions belonging to this context, that is whether any of its
157 * question categories contain any questions. This will return true even if all the questions are
160 * @param mixed $context either a context object, or a context id.
161 * @return boolean whether any of the question categories beloning to this context have
162 * any questions in them.
164 function question_context_has_any_questions($context): bool {
166 if (is_object($context)) {
167 $contextid = $context->id
;
168 } else if (is_numeric($context)) {
169 $contextid = $context;
171 throw new moodle_exception('invalidcontextinhasanyquestions', 'question');
174 FROM {question_bank_entries} qbe
175 JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
176 WHERE qc.contextid = ?';
177 return $DB->record_exists_sql($sql, [$contextid]);
181 * Check whether a given grade is one of a list of allowed options. If not,
182 * depending on $matchgrades, either return the nearest match, or return false
183 * to signal an error.
185 * @param array $gradeoptionsfull list of valid options
186 * @param int $grade grade to be tested
187 * @param string $matchgrades 'error' or 'nearest'
188 * @return false|int|string either 'fixed' value or false if error.
190 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
192 if ($matchgrades == 'error') {
193 // ...(Almost) exact match, or an error.
194 foreach ($gradeoptionsfull as $value => $option) {
195 // Slightly fuzzy test, never check floats for equality.
196 if (abs($grade - $value) < 0.00001) {
197 return $value; // Be sure the return the proper value.
200 // Didn't find a match so that's an error.
203 } else if ($matchgrades == 'nearest') {
204 // Work out nearest value.
207 foreach ($gradeoptionsfull as $value => $option) {
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
211 $bestmismatch = $newmismatch;
217 // Unknow option passed.
218 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
219 ' passed to match_grade_options');
224 * Category is about to be deleted,
225 * 1/ All questions are deleted for this question category.
226 * 2/ Any questions that can't be deleted are moved to a new category
227 * NOTE: this function is called from lib/db/upgrade.php
229 * @param object|core_course_category $category course category object
231 function question_category_delete_safe($category): void
{
233 $criteria = ['questioncategoryid' => $category->id
];
234 $context = context
::instance_by_id($category->contextid
, IGNORE_MISSING
);
235 $rescue = null; // See the code around the call to question_save_from_deletion.
237 // Deal with any questions in the category.
238 if ($questionentries = $DB->get_records('question_bank_entries', $criteria, '', 'id')) {
240 foreach ($questionentries as $questionentry) {
241 $questionids = $DB->get_records('question_versions',
242 ['questionbankentryid' => $questionentry->id
], '', 'questionid');
244 // Try to delete each question.
245 foreach ($questionids as $questionid) {
246 question_delete_question($questionid->questionid
, $category->contextid
);
250 // Check to see if there were any questions that were kept because
251 // they are still in use somehow, even though quizzes in courses
252 // in this category will already have been deleted. This could
253 // happen, for example, if questions are added to a course,
254 // and then that course is moved to another category (MDL-14802).
256 foreach ($questionentries as $questionentry) {
257 $versions = $DB->get_records('question_versions', ['questionbankentryid' => $questionentry->id
], '', 'questionid');
258 foreach ($versions as $key => $version) {
259 $questionids[$key] = $version;
262 if (!empty($questionids)) {
263 $parentcontextid = SYSCONTEXTID
;
264 $name = get_string('unknown', 'question');
265 if ($context !== false) {
266 $name = $context->get_context_name();
267 $parentcontext = $context->get_parent_context();
268 if ($parentcontext) {
269 $parentcontextid = $parentcontext->id
;
272 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
276 // Now delete the category.
277 $DB->delete_records('question_categories', ['id' => $category->id
]);
281 * Tests whether any question in a category is used by any part of Moodle.
283 * @param integer $categoryid a question category id.
284 * @param boolean $recursive whether to check child categories too.
285 * @return boolean whether any question in this category is in use.
287 function question_category_in_use($categoryid, $recursive = false): bool {
290 // Look at each question in the category.
291 $questionids = question_bank
::get_finder()->get_questions_from_categories([$categoryid], null);
293 if (questions_in_use(array_keys($questionids))) {
301 // Look under child categories recursively.
302 if ($children = $DB->get_records('question_categories',
303 ['parent' => $categoryid], '', 'id, 1')) {
304 foreach ($children as $child) {
305 if (question_category_in_use($child->id
, $recursive)) {
315 * Check if there is more versions left for the entry.
316 * If not delete the entry.
318 * @param int $entryid
320 function delete_question_bank_entry($entryid): void
{
322 if (!$DB->record_exists('question_versions', ['questionbankentryid' => $entryid])) {
323 $DB->delete_records('question_bank_entries', ['id' => $entryid]);
328 * Deletes question and all associated data from the database
330 * It will not delete a question if it is used somewhere, instead it will just delete the reference.
332 * @param int $questionid The id of the question being deleted
334 function question_delete_question($questionid): void
{
337 $question = $DB->get_record('question', ['id' => $questionid]);
339 // In some situations, for example if this was a child of a
340 // Cloze question that was previously deleted, the question may already
341 // have gone. In this case, just do nothing.
345 $sql = 'SELECT qv.id as versionid,
349 qc.contextid as contextid
351 LEFT JOIN {question_versions} qv ON qv.questionid = q.id
352 LEFT JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
353 LEFT JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
355 $questiondata = $DB->get_record_sql($sql, [$question->id
]);
357 $questionstocheck = [$question->id
];
359 if ($question->parent
) {
360 $questionstocheck[] = $question->parent
;
363 // Do not delete a question if it is used by an activity module
364 if (questions_in_use($questionstocheck)) {
368 // This sometimes happens in old sites with bad data.
369 if (!$questiondata->contextid
) {
370 debugging('Deleting question ' . $question->id
. ' which is no longer linked to a context. ' .
371 'Assuming system context to avoid errors, but this may mean that some data like files, ' .
372 'tags, are not cleaned up.');
373 $questiondata->contextid
= context_system
::instance()->id
;
374 $questiondata->categoryid
= 0;
377 // Delete previews of the question.
378 $dm = new question_engine_data_mapper();
379 $dm->delete_previews($question->id
);
381 // Delete questiontype-specific data.
382 question_bank
::get_qtype($question->qtype
, false)->delete_question($question->id
, $questiondata->contextid
);
384 // Delete all tag instances.
385 core_tag_tag
::remove_all_item_tags('core_question', 'question', $question->id
);
387 // Delete the custom filed data for the question.
388 $customfieldhandler = qbank_customfields\customfield\question_handler
::create();
389 $customfieldhandler->delete_instance($question->id
);
391 // Now recursively delete all child questions
392 if ($children = $DB->get_records('question',
393 array('parent' => $questionid), '', 'id, qtype')) {
394 foreach ($children as $child) {
395 if ($child->id
!= $questionid) {
396 question_delete_question($child->id
);
401 // Delete question comments.
402 $DB->delete_records('comments', ['itemid' => $questionid, 'component' => 'qbank_comment',
403 'commentarea' => 'question']);
404 // Finally delete the question record itself.
405 $DB->delete_records('question', ['id' => $question->id
]);
406 $DB->delete_records('question_versions', ['id' => $questiondata->versionid
]);
407 $DB->delete_records('question_references',
409 'version' => $questiondata->version
,
410 'questionbankentryid' => $questiondata->entryid
,
412 delete_question_bank_entry($questiondata->entryid
);
413 question_bank
::notify_question_edited($question->id
);
415 // Log the deletion of this question.
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);
424 * All question categories and their questions are deleted for this context id.
426 * @param int $contextid The contextid to delete question categories from
427 * @return array only returns an empty array for backwards compatibility.
429 function question_delete_context($contextid): array {
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);
444 * All question categories and their questions are deleted for this course.
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.
450 function question_delete_course($course, $notused = false): bool {
451 $coursecontext = context_course
::instance($course->id
);
452 question_delete_context($coursecontext->id
);
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
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.
467 function question_delete_course_category($category, $newcategory, $notused=false): bool {
470 $context = context_coursecat
::instance($category->id
);
471 if (empty($newcategory)) {
472 question_delete_context($context->id
);
475 // Move question categories to the new context.
476 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
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);
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
]);
495 * Creates a new category to save the questions in use.
497 * @param array $questionids of question ids
498 * @param object $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
504 function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
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);
520 // Move any remaining questions to the 'saved' category.
521 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
528 * All question categories and their questions are deleted for this activity.
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.
534 function question_delete_activity($cm, $notused = false): bool {
535 $modcontext = context_module
::instance($cm->id
);
536 question_delete_context($modcontext->id
);
541 * This function will handle moving all tag instances to a new context for a
542 * given list of questions.
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.
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
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.
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.
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
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
;
576 $questionstagobjects = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
578 foreach ($questions as $question) {
579 $tagobjects = $questionstagobjects[$question->id
] ??
[];
581 foreach ($tagobjects as $tagobject) {
582 $tagid = $tagobject->taginstanceid
;
583 $tagcontextid = $tagobject->taginstancecontextid
;
584 $istaginnewcontext = $tagcontextid == $newcontext->id
;
585 $istaginquestioncontext = $tagcontextid == $question->contextid
;
587 if ($istaginnewcontext) {
588 // This tag instance is already in the correct context so we can
593 if ($istaginquestioncontext) {
594 // This tag instance is in the question context so it needs to be
596 $instancesfornewcontext[] = $tagid;
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
607 $istaginstancecontextcourse = !empty($tagcoursecontext)
608 && $tagcontext->id
== $tagcoursecontext->id
;
610 if ($istaginstancecontextcourse) {
611 // If the tag instance is in a course context we need to add some
613 $tagcontextparentids = $tagcontext->get_parent_context_ids();
614 $isnewcontextaparent = in_array($newcontext->id
, $tagcontextparentids);
615 $isnewcontextachild = in_array($tagcontext->id
, $newcontextparentids);
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.
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;
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
631 $instancestodelete[] = $tagid;
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
638 $instancesfornewcontext[] = $tagid;
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);
648 if (!empty($instancesfornewcontext)) {
649 // Update the tag instances to the new context id.
650 core_tag_tag
::change_instances_context($instancesfornewcontext, $newcontext);
655 * Check if an idnumber exist in the category.
657 * @param int $questionidnumber
658 * @param int $categoryid
659 * @param int $limitfrom
660 * @param int $limitnum
663 function idnumber_exist_in_question_category($questionidnumber, $categoryid, $limitfrom = 0, $limitnum = 1): array {
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);
679 return [$response, $record];
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.
689 * @param array $questionids of question ids.
690 * @param integer $newcategoryid the id of the category to move to.
693 function question_move_questions_to_category($questionids, $newcategoryid): bool {
696 $newcategorydata = $DB->get_record('question_categories', ['id' => $newcategoryid]);
697 if (!$newcategorydata) {
700 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
702 $sql = "SELECT qv.id as versionid,
705 qc.contextid as contextid,
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)";
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
);
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) {
730 $idnumber = $rec->idnumber
;
731 if (strpos($idnumber, '_') !== false) {
732 $unique = substr($idnumber, strpos($idnumber, '_') +
1) +
1;
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);
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);
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
]);
755 $newcontext = context
::instance_by_id($newcategorydata->contextid
);
756 question_move_question_tags_to_new_context($questions, $newcontext);
758 // TODO Deal with datasets.
760 // Purge these questions from the cache.
761 foreach ($questions as $question) {
762 question_bank
::notify_question_edited($question->id
);
769 * Update the questioncontextid field for all question_set_references records given a new context id
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
778 function move_question_set_references(int $oldcategoryid, int $newcatgoryid,
779 int $oldcontextid, int $newcontextid, bool $delete = false): void
{
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);
793 $DB->update_record('question_set_references', $setreference);
797 $setreferences->close();
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.
809 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid): void
{
813 $sql = "SELECT q.id, q.qtype
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 = ?";
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);
825 $questions[] = (object) [
827 'contextid' => $oldcontextid
831 $newcontext = context
::instance_by_id($newcontextid);
832 question_move_question_tags_to_new_context($questions, $newcontext);
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);
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 mod/quiz/attemptlib.php, and
845 * read the code below to see how the SQL is assembled. Throws exceptions on error.
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.
855 * @return array partially complete question objects. You need to call get_question_options
856 * on them before they can be properly used.
858 function question_preload_questions($questionids = null, $extrafields = '', $join = '', $extraparams = [], $orderby = ''): array {
861 if ($questionids === null) {
862 $extracondition = '';
865 if (empty($questionids)) {
869 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED
, 'qid0000');
870 $extracondition = 'WHERE q.id ' . $questionidcondition;
874 $join = 'JOIN ' . $join;
878 $extrafields = ', ' . $extrafields;
882 $orderby = 'ORDER BY ' . $orderby;
890 qv.questionbankentryid,
891 qc.contextid as contextid
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
904 // Load the questions.
905 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
906 foreach ($questions as $question) {
907 $question->_partiallyloaded
= true;
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.
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.
923 function question_load_questions($questionids, $extrafields = '', $join = '') {
924 $questions = question_preload_questions($questionids, $extrafields, $join);
926 // Load the question type specific information.
927 if (!get_question_options($questions)) {
928 return get_string('questionloaderror', 'question');
935 * Private function to factor common code out of get_question_options().
937 * @param object $question the question to tidy.
938 * @param stdClass $category The question_categories record for the given $question.
939 * @param stdClass[]|null $tagobjects The tags for the given $question.
940 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
942 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null): void
{
943 // Load question-type specific fields.
944 if (!question_bank
::is_qtype_installed($question->qtype
)) {
945 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
946 'qtype_missingtype')) . $question->questiontext
;
949 // Convert numeric fields to float (Prevents these being displayed as 1.0000000.).
950 $question->defaultmark +
= 0;
951 $question->penalty +
= 0;
953 if (isset($question->_partiallyloaded
)) {
954 unset($question->_partiallyloaded
);
957 $question->categoryobject
= $category;
958 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
960 if (!is_null($tagobjects)) {
961 $categorycontext = context
::instance_by_id($category->contextid
);
962 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
963 $question->coursetagobjects
= $sortedtagobjects->coursetagobjects
;
964 $question->coursetags
= $sortedtagobjects->coursetags
;
965 $question->tagobjects
= $sortedtagobjects->tagobjects
;
966 $question->tags
= $sortedtagobjects->tags
;
971 * Updates the question objects with question type specific
972 * information by calling {@see get_question_options()}
974 * Can be called either with an array of question objects or with a single
977 * @param mixed $questions Either an array of question objects to be updated
978 * or just a single question object
979 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
980 * @param stdClass[] $filtercourses The courses to filter the course tags by.
981 * @return bool Indicates success or failure.
983 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
986 $questionlist = is_array($questions) ?
$questions : [$questions];
990 if (empty($questionlist)) {
994 foreach ($questionlist as $question) {
995 $questionids[] = $question->id
;
996 if (isset($question->category
)) {
997 $qcategoryid = $question->category
;
999 $qcategoryid = get_question_bank_entry($question->id
)->questioncategoryid
;
1000 $question->questioncategoryid
= $qcategoryid;
1003 if (!in_array($qcategoryid, $categoryids)) {
1004 $categoryids[] = $qcategoryid;
1008 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
1010 if ($loadtags && core_tag_tag
::is_enabled('core_question', 'question')) {
1011 $tagobjectsbyquestion = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
1013 $tagobjectsbyquestion = null;
1016 foreach ($questionlist as $question) {
1017 if (is_null($tagobjectsbyquestion)) {
1020 $tagobjects = $tagobjectsbyquestion[$question->id
];
1022 $qcategoryid = $question->category ??
$question->questioncategoryid ??
1023 get_question_bank_entry($question->id
)->questioncategoryid
;
1025 _tidy_question($question, $categories[$qcategoryid], $tagobjects, $filtercourses);
1032 * Sort question tags by course or normal tags.
1034 * This function also search tag instances that may have a context id that don't match either a course or
1035 * question context and fix the data setting the correct context id.
1037 * @param stdClass[] $tagobjects The tags for the given $question.
1038 * @param stdClass $categorycontext The question categories context.
1039 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1040 * @return stdClass $sortedtagobjects Sorted tag objects.
1042 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null): stdClass
{
1044 // Questions can have two sets of tag instances. One set at the
1045 // course context level and another at the context the question
1046 // belongs to (e.g. course category, system etc).
1047 $sortedtagobjects = new stdClass();
1048 $sortedtagobjects->coursetagobjects
= [];
1049 $sortedtagobjects->coursetags
= [];
1050 $sortedtagobjects->tagobjects
= [];
1051 $sortedtagobjects->tags
= [];
1052 $taginstanceidstonormalise = [];
1053 $filtercoursecontextids = [];
1054 $hasfiltercourses = !empty($filtercourses);
1056 if ($hasfiltercourses) {
1057 // If we're being asked to filter the course tags by a set of courses
1058 // then get the context ids to filter below.
1059 $filtercoursecontextids = array_map(function($course) {
1060 $coursecontext = context_course
::instance($course->id
);
1061 return $coursecontext->id
;
1065 foreach ($tagobjects as $tagobject) {
1066 $tagcontextid = $tagobject->taginstancecontextid
;
1067 $tagcontext = context
::instance_by_id($tagcontextid);
1068 $tagcoursecontext = $tagcontext->get_course_context(false);
1069 // This is a course tag if the tag context is a course context which
1070 // doesn't match the question's context. Any tag in the question context
1071 // is not considered a course tag, it belongs to the question.
1072 $iscoursetag = $tagcoursecontext
1073 && $tagcontext->id
== $tagcoursecontext->id
1074 && $tagcontext->id
!= $categorycontext->id
;
1077 // Any tag instance in a course context level is considered a course tag.
1078 if (!$hasfiltercourses ||
in_array($tagcontextid, $filtercoursecontextids)) {
1079 // Add the tag to the list of course tags if we aren't being
1080 // asked to filter or if this tag is in the list of courses
1081 // we're being asked to filter by.
1082 $sortedtagobjects->coursetagobjects
[] = $tagobject;
1083 $sortedtagobjects->coursetags
[$tagobject->id
] = $tagobject->get_display_name();
1086 // All non course context level tag instances or tags in the question
1087 // context belong to the context that the question was created in.
1088 $sortedtagobjects->tagobjects
[] = $tagobject;
1089 $sortedtagobjects->tags
[$tagobject->id
] = $tagobject->get_display_name();
1091 // Due to legacy tag implementations that don't force the recording
1092 // of a context id, some tag instances may have context ids that don't
1093 // match either a course context or the question context. In this case
1094 // we should take the opportunity to fix up the data and set the correct
1096 if ($tagcontext->id
!= $categorycontext->id
) {
1097 $taginstanceidstonormalise[] = $tagobject->taginstanceid
;
1098 // Update the object properties to reflect the DB update that will
1100 $tagobject->taginstancecontextid
= $categorycontext->id
;
1105 if (!empty($taginstanceidstonormalise)) {
1106 // If we found any tag instances with incorrect context id data then we can
1107 // correct those values now by setting them to the question context id.
1108 core_tag_tag
::change_instances_context($taginstanceidstonormalise, $categorycontext);
1111 return $sortedtagobjects;
1115 * Print the icon for the question type
1117 * @param object $question The question object for which the icon is required.
1118 * Only $question->qtype is used.
1119 * @return string the HTML for the img tag.
1121 function print_question_icon($question): string {
1124 if (gettype($question->qtype
) == 'object') {
1125 $qtype = $question->qtype
->name();
1128 $qtype = $question->qtype
;
1131 return $PAGE->get_renderer('question', 'bank')->qtype_icon($qtype);
1134 // CATEGORY FUNCTIONS.
1137 * Returns the categories with their names ordered following parent-child relationships.
1138 * finally it tries to return pending categories (those being orphaned, whose parent is
1139 * incorrect) to avoid missing any category from original array.
1141 * @param array $categories
1146 function sort_categories_by_tree(&$categories, $id = 0, $level = 1): array {
1150 $keys = array_keys($categories);
1152 foreach ($keys as $key) {
1153 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1154 $children[$key] = $categories[$key];
1155 $categories[$key]->processed
= true;
1156 $children = $children +
sort_categories_by_tree(
1157 $categories, $children[$key]->id
, $level +
1);
1160 // If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too.
1162 foreach ($keys as $key) {
1163 // If not processed and it's a good candidate to start (because its parent doesn't exist in the course).
1164 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
1165 array('contextid' => $categories[$key]->contextid
,
1166 'id' => $categories[$key]->parent
))) {
1167 $children[$key] = $categories[$key];
1168 $categories[$key]->processed
= true;
1169 $children = $children +
sort_categories_by_tree(
1170 $categories, $children[$key]->id
, $level +
1);
1178 * Get the default category for the context.
1180 * @param integer $contextid a context id.
1181 * @return object|bool the default question category for that context, or false if none.
1183 function question_get_default_category($contextid) {
1185 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1186 [$contextid], 'id', '*', 0, 1);
1187 if (!empty($category)) {
1188 return reset($category);
1195 * Gets the top category in the given context.
1196 * This function can optionally create the top category if it doesn't exist.
1198 * @param int $contextid A context id.
1199 * @param bool $create Whether create a top category if it doesn't exist.
1200 * @return bool|stdClass The top question category for that context, or false if none.
1202 function question_get_top_category($contextid, $create = false) {
1204 $category = $DB->get_record('question_categories', ['contextid' => $contextid, 'parent' => 0]);
1206 if (!$category && $create) {
1207 // We need to make one.
1208 $category = new stdClass();
1209 $category->name
= 'top'; // A non-real name for the top category. It will be localised at the display time.
1210 $category->info
= '';
1211 $category->contextid
= $contextid;
1212 $category->parent
= 0;
1213 $category->sortorder
= 0;
1214 $category->stamp
= make_unique_id_code();
1215 $category->id
= $DB->insert_record('question_categories', $category);
1222 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1224 * @param array $contextids List of context ids
1227 function question_get_top_categories_for_contexts($contextids): array {
1230 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1231 list($insql, $params) = $DB->get_in_or_equal($contextids);
1232 $sql = "SELECT $concatsql
1233 FROM {question_categories}
1234 WHERE contextid $insql
1237 $topcategories = $DB->get_fieldset_sql($sql, $params);
1239 return $topcategories;
1243 * Gets the default category in the most specific context.
1244 * If no categories exist yet then default ones are created in all contexts.
1246 * @param array $contexts The context objects for this context and all parent contexts.
1247 * @return object The default category - the category in the course context
1249 function question_make_default_categories($contexts): object {
1251 static $preferredlevels = array(
1252 CONTEXT_COURSE
=> 4,
1253 CONTEXT_MODULE
=> 3,
1254 CONTEXT_COURSECAT
=> 2,
1255 CONTEXT_SYSTEM
=> 1,
1260 // If it already exists, just return it.
1261 foreach ($contexts as $key => $context) {
1262 $topcategory = question_get_top_category($context->id
, true);
1263 if (!$exists = $DB->record_exists("question_categories",
1264 array('contextid' => $context->id
, 'parent' => $topcategory->id
))) {
1265 // Otherwise, we need to make one.
1266 $category = new stdClass();
1267 $contextname = $context->get_context_name(false, true);
1268 // Max length of name field is 255.
1269 $category->name
= shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1270 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1271 $category->contextid
= $context->id
;
1272 $category->parent
= $topcategory->id
;
1273 // By default, all categories get this number, and are sorted alphabetically.
1274 $category->sortorder
= 999;
1275 $category->stamp
= make_unique_id_code();
1276 $category->id
= $DB->insert_record('question_categories', $category);
1278 $category = question_get_default_category($context->id
);
1280 $thispreferredness = $preferredlevels[$context->contextlevel
];
1281 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1282 $thispreferredness +
= 10;
1284 if ($thispreferredness > $preferredness) {
1285 $toreturn = $category;
1286 $preferredness = $thispreferredness;
1290 if (!is_null($toreturn)) {
1291 $toreturn = clone($toreturn);
1297 * Get the list of categories.
1299 * @param int $categoryid
1300 * @return array of question category ids of the category and all subcategories.
1302 function question_categorylist($categoryid): array {
1305 // Final list of category IDs.
1306 $categorylist = array();
1308 // A list of category IDs to check for any sub-categories.
1309 $subcategories = array($categoryid);
1311 while ($subcategories) {
1312 foreach ($subcategories as $subcategory) {
1313 // If anything from the temporary list was added already, then we have a loop.
1314 if (isset($categorylist[$subcategory])) {
1315 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1317 $categorylist[$subcategory] = $subcategory;
1320 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1322 $subcategories = $DB->get_records_select_menu('question_categories', "parent $in", $params,
1323 null, 'id,id AS id2');
1326 return $categorylist;
1330 * Get all parent categories of a given question category in decending order.
1331 * @param int $categoryid for which you want to find the parents.
1332 * @return array of question category ids of all parents categories.
1334 function question_categorylist_parents(int $categoryid): array {
1336 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1340 $categorylist = [$parent];
1341 $currentid = $parent;
1342 while ($currentid) {
1343 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1345 $categorylist[] = $currentid;
1348 // Present the list in decending order (the top category at the top).
1349 $categorylist = array_reverse($categorylist);
1350 return $categorylist;
1353 // Import/Export Functions.
1356 * Get list of available import or export formats
1357 * @param string $type 'import' if import list, otherwise export list assumed
1358 * @return array sorted list of import/export formats available
1360 function get_import_export_formats($type): array {
1362 require_once($CFG->dirroot
. '/question/format.php');
1364 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1366 $fileformatname = array();
1367 foreach ($formatclasses as $component => $formatclass) {
1369 $format = new $formatclass();
1370 if ($type == 'import') {
1371 $provided = $format->provide_import();
1373 $provided = $format->provide_export();
1377 list($notused, $fileformat) = explode('_', $component, 2);
1378 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1382 core_collator
::asort($fileformatnames);
1383 return $fileformatnames;
1388 * Create a reasonable default file name for exporting questions from a particular
1390 * @param object $course the course the questions are in.
1391 * @param object $category the question category.
1392 * @return string the filename.
1394 function question_default_export_filename($course, $category): string {
1395 // We build a string that is an appropriate name (questions) from the lang pack,
1396 // then the corse shortname, then the question category name, then a timestamp.
1398 $base = clean_filename(get_string('exportfilename', 'question'));
1400 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1401 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1403 $shortname = clean_filename($course->shortname
);
1404 if ($shortname == '' ||
$shortname == '_' ) {
1405 $shortname = $course->id
;
1408 $categoryname = clean_filename(format_string($category->name
));
1410 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1414 * Check capability on category.
1416 * @param int|stdClass|question_definition $questionorid object or id.
1417 * If an object is passed, it should include ->contextid and ->createdby.
1418 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1419 * @param int $notused no longer used.
1420 * @return bool this user has the capability $cap for this question $question?
1422 function question_has_capability_on($questionorid, $cap, $notused = -1): bool {
1425 if (is_numeric($questionorid)) {
1426 $questionid = (int)$questionorid;
1427 } else if (is_object($questionorid)) {
1428 // All we really need in this function is the contextid and author of the question.
1429 // We won't bother fetching other details of the question if these 2 fields are provided.
1430 if (isset($questionorid->contextid
) && isset($questionorid->createdby
)) {
1431 $question = $questionorid;
1432 } else if (!empty($questionorid->id
)) {
1433 $questionid = $questionorid->id
;
1437 // At this point, either $question or $questionid is expected to be set.
1438 if (isset($questionid)) {
1440 $question = question_bank
::load_question_data($questionid);
1441 } catch (Exception
$e) {
1442 // Let's log the exception for future debugging,
1443 // but not during Behat, or we can't test these cases.
1444 if (!defined('BEHAT_SITE_RUNNING')) {
1445 debugging($e->getMessage(), DEBUG_NORMAL
, $e->getTrace());
1448 $sql = 'SELECT q.id,
1452 JOIN {question_versions} qv
1453 ON qv.questionid = q.id
1454 JOIN {question_bank_entries} qbe
1455 ON qbe.id = qv.questionbankentryid
1456 JOIN {question_categories} qc
1457 ON qc.id = qbe.questioncategoryid
1460 // Well, at least we tried. Seems that we really have to read from DB.
1461 $question = $DB->get_record_sql($sql, ['id' => $questionid]);
1465 if (!isset($question)) {
1466 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1469 $context = context
::instance_by_id($question->contextid
);
1471 // These are existing questions capabilities that are set per category.
1472 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1473 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1475 if (!isset($capabilitieswithallandmine[$cap])) {
1476 return has_capability('moodle/question:' . $cap, $context);
1478 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1479 ($question->createdby
== $USER->id
&& has_capability('moodle/question:' . $cap . 'mine', $context));
1484 * Require capability on question.
1486 * @param object $question
1487 * @param string $cap
1490 function question_require_capability_on($question, $cap): bool {
1491 if (!question_has_capability_on($question, $cap)) {
1492 throw new moodle_exception('nopermissions', '', '', $cap);
1498 * Gets the question edit url.
1500 * @param object $context a context
1501 * @return string|bool A URL for editing questions in this context.
1503 function question_edit_url($context) {
1505 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1508 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1509 $defaultcategory = question_get_default_category($context->id
);
1510 if ($defaultcategory) {
1511 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1513 switch ($context->contextlevel
) {
1514 case CONTEXT_SYSTEM
:
1515 return $baseurl . 'courseid=' . $SITE->id
;
1516 case CONTEXT_COURSECAT
:
1517 // This is nasty, becuase we can only edit questions in a course
1518 // context at the moment, so for now we just return false.
1520 case CONTEXT_COURSE
:
1521 return $baseurl . 'courseid=' . $context->instanceid
;
1522 case CONTEXT_MODULE
:
1523 return $baseurl . 'cmid=' . $context->instanceid
;
1529 * Adds question bank setting links to the given navigation node if caps are met
1530 * and loads the navigation from the plugins.
1531 * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1532 * this method will help to autoload those nodes in the question bank navigation.
1534 * @param navigation_node $navigationnode The navigation node to add the question branch to
1535 * @param object $context
1536 * @param string $baseurl the url of the base where the api is implemented from
1537 * @return navigation_node Returns the question branch that was added
1539 function question_extend_settings_navigation(navigation_node
$navigationnode, $context, $baseurl = '/question/edit.php') {
1542 if ($context->contextlevel
== CONTEXT_COURSE
) {
1543 $params = ['courseid' => $context->instanceid
];
1544 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1545 $params = ['cmid' => $context->instanceid
];
1550 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1551 $params['cat'] = $cat;
1554 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1555 new moodle_url($baseurl, $params), navigation_node
::TYPE_CONTAINER
, null, 'questionbank');
1557 $corenavigations = [
1559 'title' => get_string('questions', 'question'),
1560 'url' => new moodle_url($baseurl)
1567 $plugins = \core_component
::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1568 foreach ($plugins as $componentname => $plugin) {
1569 $pluginentrypoint = new $plugin();
1570 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1571 // Don't need the plugins without navigation node.
1572 if ($pluginentrypointobject === null) {
1573 unset($plugins[$componentname]);
1576 foreach ($corenavigations as $key => $corenavigation) {
1577 if ($pluginentrypointobject->get_navigation_key() === $key) {
1578 unset($plugins[$componentname]);
1579 if (!\core\plugininfo\qbank
::is_plugin_enabled($componentname)) {
1580 unset($corenavigations[$key]);
1583 $corenavigations[$key] = [
1584 'title' => $pluginentrypointobject->get_navigation_title(),
1585 'url' => $pluginentrypointobject->get_navigation_url()
1591 // Mitigate the risk of regression.
1592 foreach ($corenavigations as $node => $corenavigation) {
1593 if (empty($corenavigation)) {
1594 unset($corenavigations[$node]);
1598 // Community/additional plugins have navigation node.
1599 $pluginnavigations = [];
1600 foreach ($plugins as $componentname => $plugin) {
1601 $pluginentrypoint = new $plugin();
1602 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1603 // Don't need the plugins without navigation node.
1604 if ($pluginentrypointobject === null ||
!\core\plugininfo\qbank
::is_plugin_enabled($componentname)) {
1605 unset($plugins[$componentname]);
1608 $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1609 'title' => $pluginentrypointobject->get_navigation_title(),
1610 'url' => $pluginentrypointobject->get_navigation_url(),
1611 'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1615 $contexts = new core_question\local\bank\
question_edit_contexts($context);
1616 foreach ($corenavigations as $key => $corenavigation) {
1617 if ($contexts->have_one_edit_tab_cap($key)) {
1618 $questionnode->add($corenavigation['title'], new moodle_url(
1619 $corenavigation['url'], $params), navigation_node
::TYPE_SETTING
, null, $key);
1623 foreach ($pluginnavigations as $key => $pluginnavigation) {
1624 if (is_array($pluginnavigation['capabilities'])) {
1625 if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1629 $questionnode->add($pluginnavigation['title'], new moodle_url(
1630 $pluginnavigation['url'], $params), navigation_node
::TYPE_SETTING
, null, $key);
1633 return $questionnode;
1637 * Get the array of capabilities for question.
1639 * @return array all the capabilities that relate to accessing particular questions.
1641 function question_get_question_capabilities(): array {
1643 'moodle/question:add',
1644 'moodle/question:editmine',
1645 'moodle/question:editall',
1646 'moodle/question:viewmine',
1647 'moodle/question:viewall',
1648 'moodle/question:usemine',
1649 'moodle/question:useall',
1650 'moodle/question:movemine',
1651 'moodle/question:moveall',
1652 'moodle/question:tagmine',
1653 'moodle/question:tagall',
1654 'moodle/question:commentmine',
1655 'moodle/question:commentall',
1660 * Get the question bank caps.
1662 * @return array all the question bank capabilities.
1664 function question_get_all_capabilities(): array {
1665 $caps = question_get_question_capabilities();
1666 $caps[] = 'moodle/question:managecategory';
1667 $caps[] = 'moodle/question:flag';
1672 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1674 * @package core_question
1676 * @param string $text text being processed
1677 * @param string $file the php script used to serve files
1678 * @param int $contextid context ID
1679 * @param string $component component
1680 * @param string $filearea filearea
1681 * @param array $ids other IDs will be used to check file permission
1682 * @param int $itemid item ID
1683 * @param array $options options
1686 function question_rewrite_question_urls($text, $file, $contextid, $component, $filearea,
1687 array $ids, $itemid, array $options=null): string {
1691 $idsstr .= implode('/', $ids);
1693 if ($itemid !== null) {
1694 $idsstr .= '/' . $itemid;
1696 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1697 $filearea, $idsstr, $options);
1701 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1702 * viewing the question outside an attempt (for example, in the question bank
1703 * listing or in the quiz statistics report).
1705 * @param string $text the question text.
1706 * @param int $questionid the question id.
1707 * @param int $filecontextid the context id of the question being displayed.
1708 * @param string $filecomponent the component that owns the file area.
1709 * @param string $filearea the file area name.
1710 * @param int|null $itemid the file's itemid
1711 * @param int $previewcontextid the context id where the preview is being displayed.
1712 * @param string $previewcomponent component responsible for displaying the preview.
1713 * @param array $options text and file options ('forcehttps'=>false)
1714 * @return string $questiontext with URLs rewritten.
1716 function question_rewrite_question_preview_urls($text, $questionid, $filecontextid, $filecomponent, $filearea, $itemid,
1717 $previewcontextid, $previewcomponent, $options = null): string {
1719 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1721 $path .= '/' . $itemid;
1724 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1725 $filecomponent, $filearea, $path, $options);
1729 * Called by pluginfile.php to serve files related to the 'question' core
1730 * component and for files belonging to qtypes.
1732 * For files that relate to questions in a question_attempt, then we delegate to
1733 * a function in the component that owns the attempt (for example in the quiz,
1734 * or in core question preview) to get necessary inforation.
1736 * (Note that, at the moment, all question file areas relate to questions in
1737 * attempts, so the If at the start of the last paragraph is always true.)
1739 * Does not return, either calls send_file_not_found(); or serves the file.
1742 * @param stdClass $course course settings object
1743 * @param stdClass $context context object
1744 * @param string $component the name of the component we are serving files for.
1745 * @param string $filearea the name of the file area.
1746 * @param array $args the remaining bits of the file path.
1747 * @param bool $forcedownload whether the user must be forced to download the file.
1748 * @param array $options additional options affecting the file serving
1749 * @return array|bool
1751 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, $options = []) {
1754 // Special case, sending a question bank export.
1755 if ($filearea === 'export') {
1756 list($context, $course, $cm) = get_context_info_array($context->id
);
1757 require_login($course, false, $cm);
1759 require_once($CFG->dirroot
. '/question/editlib.php');
1760 $contexts = new core_question\local\bank\
question_edit_contexts($context);
1761 // Check export capability.
1762 $contexts->require_one_edit_tab_cap('export');
1763 $categoryid = (int)array_shift($args);
1764 $format = array_shift($args);
1765 $cattofile = array_shift($args);
1766 $contexttofile = array_shift($args);
1767 $filename = array_shift($args);
1769 // Load parent class for import/export.
1770 require_once($CFG->dirroot
. '/question/format.php');
1771 require_once($CFG->dirroot
. '/question/editlib.php');
1772 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
1774 $classname = 'qformat_' . $format;
1775 if (!class_exists($classname)) {
1776 send_file_not_found();
1779 $qformat = new $classname();
1781 if (!$category = $DB->get_record('question_categories', array('id' => $categoryid))) {
1782 send_file_not_found();
1785 $qformat->setCategory($category);
1786 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1787 $qformat->setCourse($course);
1789 if ($cattofile == 'withcategories') {
1790 $qformat->setCattofile(true);
1792 $qformat->setCattofile(false);
1795 if ($contexttofile == 'withcontexts') {
1796 $qformat->setContexttofile(true);
1798 $qformat->setContexttofile(false);
1801 if (!$qformat->exportpreprocess()) {
1802 send_file_not_found();
1803 throw new moodle_exception('exporterror', 'question', $thispageurl->out());
1806 // Export data to moodle file pool.
1807 if (!$content = $qformat->exportprocess()) {
1808 send_file_not_found();
1811 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1814 // Normal case, a file belonging to a question.
1815 $qubaidorpreview = array_shift($args);
1817 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1818 if ($qubaidorpreview === 'preview') {
1819 $previewcontextid = (int)array_shift($args);
1820 $previewcomponent = array_shift($args);
1821 $questionid = (int) array_shift($args);
1822 $previewcontext = context_helper
::instance_by_id($previewcontextid);
1824 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1825 $previewcontext, $questionid,
1826 $context, $component, $filearea, $args,
1827 $forcedownload, $options), 'callbackmissing');
1829 if ($result === 'callbackmissing') {
1830 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1831 "{$previewcomponent}_question_preview_pluginfile callback. " .
1832 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER
);
1835 send_file_not_found();
1838 // 2. A question being attempted in the normal way.
1839 $qubaid = (int)$qubaidorpreview;
1840 $slot = (int)array_shift($args);
1842 $module = $DB->get_field('question_usages', 'component',
1843 array('id' => $qubaid));
1845 send_file_not_found();
1848 if ($module === 'core_question_preview') {
1849 return qbank_previewquestion\helper
::question_preview_question_pluginfile($course, $context,
1850 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1853 $dir = core_component
::get_component_directory($module);
1854 if (!file_exists("$dir/lib.php")) {
1855 send_file_not_found();
1857 include_once("$dir/lib.php");
1859 $filefunction = $module . '_question_pluginfile';
1860 if (function_exists($filefunction)) {
1861 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1862 $args, $forcedownload, $options);
1865 // Okay, we're here so lets check for function without 'mod_'.
1866 if (strpos($module, 'mod_') === 0) {
1867 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1868 if (function_exists($filefunctionold)) {
1869 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1870 $args, $forcedownload, $options);
1874 send_file_not_found();
1879 * Serve questiontext files in the question text when they are displayed in this report.
1881 * @param context $previewcontext the context in which the preview is happening.
1882 * @param int $questionid the question id.
1883 * @param context $filecontext the file (question) context.
1884 * @param string $filecomponent the component the file belongs to.
1885 * @param string $filearea the file area.
1886 * @param array $args remaining file args.
1887 * @param bool $forcedownload
1888 * @param array $options additional options affecting the file serving.
1890 function core_question_question_preview_pluginfile($previewcontext, $questionid, $filecontext, $filecomponent,
1891 $filearea, $args, $forcedownload, $options = []): void
{
1896 JOIN {question_versions} qv
1897 ON qv.questionid = q.id
1898 JOIN {question_bank_entries} qbe
1899 ON qbe.id = qv.questionbankentryid
1900 JOIN {question_categories} qc
1901 ON qc.id = qbe.questioncategoryid
1903 AND qc.contextid = :contextid';
1905 // Verify that contextid matches the question.
1906 $question = $DB->get_record_sql($sql, ['id' => $questionid, 'contextid' => $filecontext->id
], MUST_EXIST
);
1908 // Check the capability.
1909 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
1910 require_login($course, false, $cm);
1912 question_require_capability_on($question, 'use');
1914 $fs = get_file_storage();
1915 $relativepath = implode('/', $args);
1916 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1917 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1918 send_file_not_found();
1921 send_stored_file($file, 0, 0, $forcedownload, $options);
1925 * Return a list of page types
1926 * @param string $pagetype current page type
1927 * @param stdClass $parentcontext Block's parent context
1928 * @param stdClass $currentcontext Current context of block
1931 function question_page_type_list($pagetype, $parentcontext, $currentcontext): array {
1934 'question-*' => get_string('page-question-x', 'question'),
1935 'question-edit' => get_string('page-question-edit', 'question'),
1936 'question-category' => get_string('page-question-category', 'question'),
1937 'question-export' => get_string('page-question-export', 'question'),
1938 'question-import' => get_string('page-question-import', 'question')
1940 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
1941 require_once($CFG->dirroot
. '/course/lib.php');
1942 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1949 * Does an activity module use the question bank?
1951 * @param string $modname The name of the module (without mod_ prefix).
1952 * @return bool true if the module uses questions.
1954 function question_module_uses_questions($modname): bool {
1955 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
1959 $component = 'mod_'.$modname;
1960 if (component_callback_exists($component, 'question_pluginfile')) {
1961 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);
1969 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
1971 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
1972 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
1974 * @param string|null $oldidnumber a question idnumber, or can be null.
1975 * @param int $categoryid a question category id.
1976 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
1978 function core_question_find_next_unused_idnumber(?
string $oldidnumber, int $categoryid): ?
string {
1981 // The the old idnumber is not of the right form, bail now.
1982 if (!preg_match('~\d+$~', $oldidnumber, $matches)) {
1986 // Find all used idnumbers in one DB query.
1987 $usedidnumbers = $DB->get_records_select_menu('question_bank_entries', 'questioncategoryid = ? AND idnumber IS NOT NULL',
1988 [$categoryid], '', 'idnumber, 1');
1990 // Find the next unused idnumber.
1991 $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
1992 $stem = substr($oldidnumber, 0, -strlen($matches[0]));
1995 // If we have got to something9999, insert an extra digit before incrementing.
1996 if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
1997 $numberbit = $matches[1] . '0' . $matches[2];
2000 $newidnumber = $stem . substr($numberbit, 1);
2001 } while (isset($usedidnumbers[$newidnumber]));
2003 return (string) $newidnumber;
2007 * Get the question_bank_entry object given a question id.
2009 * @param int $questionid Question id.
2010 * @return false|mixed
2011 * @throws dml_exception
2013 function get_question_bank_entry(int $questionid): object {
2016 $sql = "SELECT qbe.*
2018 JOIN {question_versions} qv ON qv.questionid = q.id
2019 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2022 $qbankentry = $DB->get_record_sql($sql, ['id' => $questionid]);
2028 * Get the question versions given a question id in a descending sort .
2030 * @param int $questionid Question id.
2032 * @throws dml_exception
2034 function get_question_version($questionid): array {
2037 $version = $DB->get_records('question_versions', ['questionid' => $questionid]);
2044 * Get the next version number to create base on a Question bank entry id.
2046 * @param int $questionbankentryid Question bank entry id.
2047 * @return int next version number.
2048 * @throws dml_exception
2050 function get_next_version(int $questionbankentryid): int {
2053 $sql = "SELECT MAX(qv.version)
2054 FROM {question_versions} qv
2055 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2056 WHERE qbe.id = :id";
2058 $nextversion = $DB->get_field_sql($sql, ['id' => $questionbankentryid]);
2061 return (int)$nextversion +
1;
2068 * Checks if question is the latest version.
2070 * @param string $version Question version to check.
2071 * @param string $questionbankentryid Entry to check against.
2074 function is_latest(string $version, string $questionbankentryid) : bool {
2077 $sql = 'SELECT MAX(version) AS max
2078 FROM {question_versions}
2079 WHERE questionbankentryid = ?';
2080 $latestversion = $DB->get_record_sql($sql, [$questionbankentryid]);
2082 if (isset($latestversion->max
)) {
2083 return ($version === $latestversion->max
) ?
true : false;
2088 // Deprecated functions from Moodle 4.0.
2091 * Generate the URL for starting a new preview of a given question with the given options.
2092 * @param integer $questionid the question to preview.
2093 * @param string $preferredbehaviour the behaviour to use for the preview.
2094 * @param float $maxmark the maximum to mark the question out of.
2095 * @param question_display_options $displayoptions the display options to use.
2096 * @param int $variant the variant of the question to preview. If null, one will
2097 * be picked randomly.
2098 * @param object $context context to run the preview in (affects things like
2099 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
2100 * @return moodle_url the URL.
2101 * @deprecated since Moodle 4.0
2102 * @see qbank_previewquestion\helper::question_preview_url()
2103 * @todo Final deprecation on Moodle 4.4 MDL-72438
2105 function question_preview_url($questionid, $preferredbehaviour = null,
2106 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
2107 debugging('Function question_preview_url() has been deprecated and moved to qbank_previewquestion plugin,
2108 Please use qbank_previewquestion\previewquestion_helper::question_preview_url() instead.', DEBUG_DEVELOPER
);
2110 return \qbank_previewquestion\helper
::question_preview_url($questionid, $preferredbehaviour,
2111 $maxmark, $displayoptions, $variant, $context);
2115 * Popup params for the question preview.
2117 * @return array that can be passed as $params to the {@see popup_action()} constructor.
2118 * @deprecated since Moodle 4.0
2119 * @see qbank_previewquestion\previewquestion_helper::question_preview_popup_params()
2120 * @todo Final deprecation on Moodle 4.4 MDL-72438
2122 function question_preview_popup_params() {
2123 debugging('Function question_preview_popup_params() has been deprecated and moved to qbank_previewquestion plugin,
2124 Please use qbank_previewquestion\previewquestion_helper::question_preview_popup_params() instead.', DEBUG_DEVELOPER
);
2126 return \qbank_previewquestion\helper
::question_preview_popup_params();
2130 * Creates a stamp that uniquely identifies this version of the question
2132 * In future we want this to use a hash of the question data to guarantee that
2133 * identical versions have the same version stamp.
2135 * @param object $question
2136 * @return string A unique version stamp
2137 * @deprecated since Moodle 4.0
2138 * @todo Final deprecation on Moodle 4.4 MDL-72438
2140 function question_hash($question) {
2141 debugging('Function question_hash() has been deprecated without replacement.', DEBUG_DEVELOPER
);
2142 return make_unique_id_code();
2146 * Create url for question export.
2148 * @param int $contextid
2149 * @param int $categoryid
2150 * @param string $format
2151 * @param string $withcategories
2152 * @param string $withcontexts
2153 * @param string $filename
2154 * @return moodle_url export file url
2155 * @deprecated since Moodle 4.0 MDL-71573
2156 * @see qbank_exportquestions\exportquestions_helper
2157 * @todo Final deprecation on Moodle 4.4 MDL-72438
2159 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2160 $withcontexts, $filename) {
2161 debugging('Function question_make_export_url() has been deprecated and moved to qbank_exportquestions plugin,
2162 Please use qbank_exportquestions\exportquestions_helper::question_make_export_url() instead.', DEBUG_DEVELOPER
);
2164 return \qbank_exportquestions\exportquestions_helper
::question_make_export_url($contextid, $categoryid, $format,
2165 $withcategories, $withcontexts, $filename);
2169 * Get the URL to export a single question (exportone.php).
2171 * @param stdClass|question_definition $question the question definition as obtained from
2172 * question_bank::load_question_data() or question_bank::make_question().
2173 * (Only ->id and ->contextid are used.)
2174 * @return moodle_url the requested URL.
2175 * @deprecated since Moodle 4.0
2176 * @see \qbank_exporttoxml\helper::question_get_export_single_question_url()
2177 * @todo Final deprecation on Moodle 4.4 MDL-72438
2179 function question_get_export_single_question_url($question) {
2180 debugging('Function question_get_export_single_question_url() has been deprecated and moved to qbank_exporttoxml plugin,
2181 please use qbank_exporttoxml\helper::question_get_export_single_question_url() instead.', DEBUG_DEVELOPER
);
2182 qbank_exporttoxml\helper
::question_get_export_single_question_url($question);
2186 * Remove stale questions from a category.
2188 * While questions should not be left behind when they are not used any more,
2189 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
2190 * this happens, the users are unable to delete the question category unless
2191 * they move those stale questions to another one category, but to them the
2192 * category is empty as it does not contain anything. The purpose of this function
2193 * is to detect the questions that may have gone stale and remove them.
2195 * You will typically use this prior to checking if the category contains questions.
2197 * The stale questions (unused and hidden to the user) handled are:
2198 * - hidden questions
2199 * - random questions
2201 * @param int $categoryid The category ID.
2202 * @deprecated since Moodle 4.0 MDL-71585
2203 * @see qbank_managecategories\helper
2204 * @todo Final deprecation on Moodle 4.4 MDL-72438
2206 function question_remove_stale_questions_from_category($categoryid) {
2207 debugging('Function question_remove_stale_questions_from_category()
2208 has been deprecated and moved to qbank_managecategories plugin,
2209 Please use qbank_managecategories\helper::question_remove_stale_questions_from_category() instead.',
2211 \qbank_managecategories\helper
::question_remove_stale_questions_from_category($categoryid);
2215 * Private method, only for the use of add_indented_names().
2217 * Recursively adds an indentedname field to each category, starting with the category
2218 * with id $id, and dealing with that category and all its children, and
2219 * return a new array, with those categories in the right order.
2221 * @param array $categories an array of categories which has had childids
2222 * fields added by flatten_category_tree(). Passed by reference for
2223 * performance only. It is not modfied.
2224 * @param int $id the category to start the indenting process from.
2225 * @param int $depth the indent depth. Used in recursive calls.
2226 * @param int $nochildrenof
2227 * @return array a new array of categories, in the right order for the tree.
2228 * @deprecated since Moodle 4.0 MDL-71585
2229 * @see qbank_managecategories\helper
2230 * @todo Final deprecation on Moodle 4.4 MDL-72438
2232 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
2233 debugging('Function flatten_category_tree() has been deprecated and moved to qbank_managecategories plugin,
2234 Please use qbank_managecategories\helper::flatten_category_tree() instead.', DEBUG_DEVELOPER
);
2235 return \qbank_managecategories\helper
::flatten_category_tree($categories, $id, $depth, $nochildrenof);
2239 * Format categories into an indented list reflecting the tree structure.
2241 * @param array $categories An array of category objects, for example from the.
2242 * @param int $nochildrenof
2243 * @return array The formatted list of categories.
2244 * @deprecated since Moodle 4.0 MDL-71585
2245 * @see qbank_managecategories\helper
2246 * @todo Final deprecation on Moodle 4.4 MDL-72438
2248 function add_indented_names($categories, $nochildrenof = -1) {
2249 debugging('Function add_indented_names() has been deprecated and moved to qbank_managecategories plugin,
2250 Please use qbank_managecategories\helper::add_indented_names() instead.', DEBUG_DEVELOPER
);
2251 return \qbank_managecategories\helper
::add_indented_names($categories, $nochildrenof);
2255 * Output a select menu of question categories.
2256 * Categories from this course and (optionally) published categories from other courses
2257 * are included. Optionally, only categories the current user may edit can be included.
2259 * @param array $contexts
2261 * @param int $currentcat
2262 * @param integer $selected optionally, the id of a category to be selected by
2263 * default in the dropdown.
2264 * @param int $nochildrenof
2265 * @deprecated since Moodle 4.0 MDL-71585
2266 * @see qbank_managecategories\helper
2267 * @todo Final deprecation on Moodle 4.4 MDL-72438
2269 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
2270 $selected = "", $nochildrenof = -1) {
2271 debugging('Function question_category_select_menu() has been deprecated and moved to qbank_managecategories plugin,
2272 Please use qbank_managecategories\helper::question_category_select_menu() instead.', DEBUG_DEVELOPER
);
2273 \qbank_managecategories\helper
::question_category_select_menu($contexts, $top, $currentcat, $selected, $nochildrenof);
2277 * Get all the category objects, including a count of the number of questions in that category,
2278 * for all the categories in the lists $contexts.
2280 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
2281 * @param string $sortorder used as the ORDER BY clause in the select statement.
2282 * @param bool $top Whether to return the top categories or not.
2283 * @return array of category objects.
2284 * @deprecated since Moodle 4.0 MDL-71585
2285 * @see qbank_managecategories\helper
2286 * @todo Final deprecation on Moodle 4.4 MDL-72438
2288 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
2289 debugging('Function get_categories_for_contexts() has been deprecated and moved to qbank_managecategories plugin,
2290 Please use qbank_managecategories\helper::get_categories_for_contexts() instead.', DEBUG_DEVELOPER
);
2291 return \qbank_managecategories\helper
::get_categories_for_contexts($contexts, $sortorder, $top);
2295 * Output an array of question categories.
2297 * @param array $contexts The list of contexts.
2298 * @param bool $top Whether to return the top categories or not.
2299 * @param int $currentcat
2300 * @param bool $popupform
2301 * @param int $nochildrenof
2302 * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
2304 * @deprecated since Moodle 4.0 MDL-71585
2305 * @see qbank_managecategories\helper
2306 * @todo Final deprecation on Moodle 4.4 MDL-72438
2308 function question_category_options($contexts, $top = false, $currentcat = 0,
2309 $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
2310 debugging('Function question_category_options() has been deprecated and moved to qbank_managecategories plugin,
2311 Please use qbank_managecategories\helper::question_category_options() instead.', DEBUG_DEVELOPER
);
2312 return \qbank_managecategories\helper
::question_category_options($contexts, $top, $currentcat,
2313 $popupform, $nochildrenof, $escapecontextnames);
2317 * Add context in categories key.
2319 * @param array $categories The list of categories.
2321 * @deprecated since Moodle 4.0 MDL-71585
2322 * @see qbank_managecategories\helper
2323 * @todo Final deprecation on Moodle 4.4 MDL-72438
2325 function question_add_context_in_key($categories) {
2326 debugging('Function question_add_context_in_key() has been deprecated and moved to qbank_managecategories plugin,
2327 Please use qbank_managecategories\helper::question_add_context_in_key() instead.', DEBUG_DEVELOPER
);
2328 return \qbank_managecategories\helper
::question_add_context_in_key($categories);
2332 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
2334 * @param array $categories An array of question categories.
2335 * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
2336 * @return array The same question category list given to the function, with the top category names being translated.
2337 * @deprecated since Moodle 4.0 MDL-71585
2338 * @see qbank_managecategories\helper
2339 * @todo Final deprecation on Moodle 4.4 MDL-72438
2341 function question_fix_top_names($categories, $escape = true) {
2342 debugging('Function question_fix_top_names() has been deprecated and moved to qbank_managecategories plugin,
2343 Please use qbank_managecategories\helper::question_fix_top_names() instead.', DEBUG_DEVELOPER
);
2344 return \qbank_managecategories\helper
::question_fix_top_names($categories, $escape);