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, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
123 // Are they used by the core question system?
124 if (question_engine
::questions_in_use($questionids)) {
128 // Check if any plugins are using these questions.
129 $callbacksbytype = get_plugins_with_function('questions_in_use');
130 foreach ($callbacksbytype as $callbacks) {
131 foreach ($callbacks as $function) {
132 if ($function($questionids)) {
138 // Finally check legacy callback.
139 $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
140 foreach ($legacycallbacks as $plugin => $function) {
141 debugging($plugin . ' implements deprecated method ' . $function .
142 '. ' . $plugin . '_questions_in_use should be implemented instead.', DEBUG_DEVELOPER
);
144 if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
145 continue; // Already done.
148 foreach ($questionids as $questionid) {
149 if (!empty($function($questionid))) {
159 * Determine whether there arey any questions belonging to this context, that is whether any of its
160 * question categories contain any questions. This will return true even if all the questions are
163 * @param mixed $context either a context object, or a context id.
164 * @return boolean whether any of the question categories beloning to this context have
165 * any questions in them.
167 function question_context_has_any_questions($context) {
169 if (is_object($context)) {
170 $contextid = $context->id
;
171 } else if (is_numeric($context)) {
172 $contextid = $context;
174 print_error('invalidcontextinhasanyquestions', 'question');
176 return $DB->record_exists_sql("SELECT *
178 JOIN {question_categories} qc ON qc.id = q.category
179 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
183 * Check whether a given grade is one of a list of allowed options. If not,
184 * depending on $matchgrades, either return the nearest match, or return false
185 * to signal an error.
186 * @param array $gradeoptionsfull list of valid options
187 * @param int $grade grade to be tested
188 * @param string $matchgrades 'error' or 'nearest'
189 * @return mixed either 'fixed' value or false if error.
191 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
193 if ($matchgrades == 'error') {
194 // (Almost) exact match, or an error.
195 foreach ($gradeoptionsfull as $value => $option) {
196 // Slightly fuzzy test, never check floats for equality.
197 if (abs($grade - $value) < 0.00001) {
198 return $value; // Be sure the return the proper value.
201 // Didn't find a match so that's an error.
204 } else if ($matchgrades == 'nearest') {
205 // Work out nearest value
208 foreach ($gradeoptionsfull as $value => $option) {
209 $newmismatch = abs($grade - $value);
210 if ($newmismatch < $bestmismatch) {
212 $bestmismatch = $newmismatch;
218 // Unknow option passed.
219 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
220 ' passed to match_grade_options');
225 * Remove stale questions from a category.
227 * While questions should not be left behind when they are not used any more,
228 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
229 * this happens, the users are unable to delete the question category unless
230 * they move those stale questions to another one category, but to them the
231 * category is empty as it does not contain anything. The purpose of this function
232 * is to detect the questions that may have gone stale and remove them.
234 * You will typically use this prior to checking if the category contains questions.
236 * The stale questions (unused and hidden to the user) handled are:
240 * @param int $categoryid The category ID.
242 function question_remove_stale_questions_from_category($categoryid) {
245 $select = 'category = :categoryid AND (qtype = :qtype OR hidden = :hidden)';
246 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'hidden' => 1];
247 $questions = $DB->get_recordset_select("question", $select, $params, '', 'id');
248 foreach ($questions as $question) {
249 // The function question_delete_question does not delete questions in use.
250 question_delete_question($question->id
);
256 * Category is about to be deleted,
257 * 1/ All questions are deleted for this question category.
258 * 2/ Any questions that can't be deleted are moved to a new category
259 * NOTE: this function is called from lib/db/upgrade.php
261 * @param object|core_course_category $category course category object
263 function question_category_delete_safe($category) {
265 $criteria = array('category' => $category->id
);
266 $context = context
::instance_by_id($category->contextid
, IGNORE_MISSING
);
267 $rescue = null; // See the code around the call to question_save_from_deletion.
269 // Deal with any questions in the category.
270 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
272 // Try to delete each question.
273 foreach ($questions as $question) {
274 question_delete_question($question->id
);
277 // Check to see if there were any questions that were kept because
278 // they are still in use somehow, even though quizzes in courses
279 // in this category will already have been deleted. This could
280 // happen, for example, if questions are added to a course,
281 // and then that course is moved to another category (MDL-14802).
282 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
283 if (!empty($questionids)) {
284 $parentcontextid = SYSCONTEXTID
;
285 $name = get_string('unknown', 'question');
286 if ($context !== false) {
287 $name = $context->get_context_name();
288 $parentcontext = $context->get_parent_context();
289 if ($parentcontext) {
290 $parentcontextid = $parentcontext->id
;
293 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
297 // Now delete the category.
298 $DB->delete_records('question_categories', array('id' => $category->id
));
302 * Tests whether any question in a category is used by any part of Moodle.
304 * @param integer $categoryid a question category id.
305 * @param boolean $recursive whether to check child categories too.
306 * @return boolean whether any question in this category is in use.
308 function question_category_in_use($categoryid, $recursive = false) {
311 //Look at each question in the category
312 if ($questions = $DB->get_records_menu('question',
313 array('category' => $categoryid), '', 'id, 1')) {
314 if (questions_in_use(array_keys($questions))) {
322 //Look under child categories recursively
323 if ($children = $DB->get_records('question_categories',
324 array('parent' => $categoryid), '', 'id, 1')) {
325 foreach ($children as $child) {
326 if (question_category_in_use($child->id
, $recursive)) {
336 * Deletes question and all associated data from the database
338 * It will not delete a question if it is used somewhere.
340 * @param object $question The question being deleted
342 function question_delete_question($questionid) {
345 $question = $DB->get_record_sql('
346 SELECT q.*, ctx.id AS contextid
348 LEFT JOIN {question_categories} qc ON qc.id = q.category
349 LEFT JOIN {context} ctx ON ctx.id = qc.contextid
350 WHERE q.id = ?', array($questionid));
352 // In some situations, for example if this was a child of a
353 // Cloze question that was previously deleted, the question may already
354 // have gone. In this case, just do nothing.
358 // Do not delete a question if it is used by an activity module
359 if (questions_in_use(array($questionid))) {
363 // This sometimes happens in old sites with bad data.
364 if (!$question->contextid
) {
365 debugging('Deleting question ' . $question->id
. ' which is no longer linked to a context. ' .
366 'Assuming system context to avoid errors, but this may mean that some data like files, ' .
367 'tags, are not cleaned up.');
368 $question->contextid
= context_system
::instance()->id
;
371 // Delete previews of the question.
372 $dm = new question_engine_data_mapper();
373 $dm->delete_previews($questionid);
375 // delete questiontype-specific data
376 question_bank
::get_qtype($question->qtype
, false)->delete_question(
377 $questionid, $question->contextid
);
379 // Delete all tag instances.
380 core_tag_tag
::remove_all_item_tags('core_question', 'question', $question->id
);
382 // Now recursively delete all child questions
383 if ($children = $DB->get_records('question',
384 array('parent' => $questionid), '', 'id, qtype')) {
385 foreach ($children as $child) {
386 if ($child->id
!= $questionid) {
387 question_delete_question($child->id
);
392 // Finally delete the question record itself
393 $DB->delete_records('question', array('id' => $questionid));
394 question_bank
::notify_question_edited($questionid);
396 // Log the deletion of this question.
397 $event = \core\event\question_deleted
::create_from_question_instance($question);
398 $event->add_record_snapshot('question', $question);
403 * All question categories and their questions are deleted for this context id.
405 * @param int $contextid The contextid to delete question categories from
406 * @return array only returns an empty array for backwards compatibility.
408 function question_delete_context($contextid) {
411 $fields = 'id, parent, name, contextid';
412 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
413 //Sort categories following their tree (parent-child) relationships
414 //this will make the feedback more readable
415 $categories = sort_categories_by_tree($categories);
417 foreach ($categories as $category) {
418 question_category_delete_safe($category);
425 * All question categories and their questions are deleted for this course.
427 * @param stdClass $course an object representing the activity
428 * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
429 * @return bool always true.
431 function question_delete_course($course, $notused = false) {
432 $coursecontext = context_course
::instance($course->id
);
433 question_delete_context($coursecontext->id
);
438 * Category is about to be deleted,
439 * 1/ All question categories and their questions are deleted for this course category.
440 * 2/ All questions are moved to new category
442 * @param stdClass|core_course_category $category course category object
443 * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
444 * category where content moved
445 * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
448 function question_delete_course_category($category, $newcategory, $notused=false) {
451 $context = context_coursecat
::instance($category->id
);
452 if (empty($newcategory)) {
453 question_delete_context($context->id
);
456 // Move question categories to the new context.
457 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
461 // Only move question categories if there is any question category at all!
462 if ($topcategory = question_get_top_category($context->id
)) {
463 $newtopcategory = question_get_top_category($newcontext->id
, true);
465 question_move_category_to_context($topcategory->id
, $context->id
, $newcontext->id
);
466 $DB->set_field('question_categories', 'parent', $newtopcategory->id
, array('parent' => $topcategory->id
));
467 // Now delete the top category.
468 $DB->delete_records('question_categories', array('id' => $topcategory->id
));
476 * Enter description here...
478 * @param array $questionids of question ids
479 * @param object $newcontextid the context to create the saved category in.
480 * @param string $oldplace a textual description of the think being deleted,
481 * e.g. from get_context_name
482 * @param object $newcategory
483 * @return mixed false on
485 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
486 $newcategory = null) {
489 // Make a category in the parent context to move the questions to.
490 if (is_null($newcategory)) {
491 $newcategory = new stdClass();
492 $newcategory->parent
= question_get_top_category($newcontextid, true)->id
;
493 $newcategory->contextid
= $newcontextid;
494 // Max length of column name in question_categories is 255.
495 $newcategory->name
= shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
496 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
497 $newcategory->sortorder
= 999;
498 $newcategory->stamp
= make_unique_id_code();
499 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
502 // Move any remaining questions to the 'saved' category.
503 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
510 * All question categories and their questions are deleted for this activity.
512 * @param object $cm the course module object representing the activity
513 * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
516 function question_delete_activity($cm, $notused = false) {
519 $modcontext = context_module
::instance($cm->id
);
520 question_delete_context($modcontext->id
);
525 * This function will handle moving all tag instances to a new context for a
526 * given list of questions.
528 * Questions can be tagged in up to two contexts:
529 * 1.) The context the question exists in.
530 * 2.) The course context (if the question context is a higher context.
531 * E.g. course category context or system context.
533 * This means a question that exists in a higher context (e.g. course cat or
534 * system context) may have multiple groups of tags in any number of child
537 * Questions in the course category context can be move "down" a context level
538 * into one of their child course contexts or activity contexts which affects the
539 * availability of that question in other courses / activities.
541 * In this case it makes the questions no longer available in the other course or
542 * activity contexts so we need to make sure that the tag instances in those other
543 * contexts are removed.
545 * @param stdClass[] $questions The list of question being moved (must include
546 * the id and contextid)
547 * @param context $newcontext The Moodle context the questions are being moved to
549 function question_move_question_tags_to_new_context(array $questions, context
$newcontext) {
550 // If the questions are moving to a new course/activity context then we need to
551 // find any existing tag instances from any unavailable course contexts and
552 // delete them because they will no longer be applicable (we don't support
553 // tagging questions across courses).
554 $instancestodelete = [];
555 $instancesfornewcontext = [];
556 $newcontextparentids = $newcontext->get_parent_context_ids();
557 $questionids = array_map(function($question) {
558 return $question->id
;
560 $questionstagobjects = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
562 foreach ($questions as $question) {
563 $tagobjects = $questionstagobjects[$question->id
] ??
[];
565 foreach ($tagobjects as $tagobject) {
566 $tagid = $tagobject->taginstanceid
;
567 $tagcontextid = $tagobject->taginstancecontextid
;
568 $istaginnewcontext = $tagcontextid == $newcontext->id
;
569 $istaginquestioncontext = $tagcontextid == $question->contextid
;
571 if ($istaginnewcontext) {
572 // This tag instance is already in the correct context so we can
577 if ($istaginquestioncontext) {
578 // This tag instance is in the question context so it needs to be
580 $instancesfornewcontext[] = $tagid;
584 // These tag instances are in neither the new context nor the
585 // question context so we need to determine what to do based on
586 // the context they are in and the new question context.
587 $tagcontext = context
::instance_by_id($tagcontextid);
588 $tagcoursecontext = $tagcontext->get_course_context(false);
589 // The tag is in a course context if get_course_context() returns
591 $istaginstancecontextcourse = !empty($tagcoursecontext)
592 && $tagcontext->id
== $tagcoursecontext->id
;
594 if ($istaginstancecontextcourse) {
595 // If the tag instance is in a course context we need to add some
597 $tagcontextparentids = $tagcontext->get_parent_context_ids();
598 $isnewcontextaparent = in_array($newcontext->id
, $tagcontextparentids);
599 $isnewcontextachild = in_array($tagcontext->id
, $newcontextparentids);
601 if ($isnewcontextaparent) {
602 // If the tag instance is a course context tag and the new
603 // context is still a parent context to the tag context then
604 // we can leave this tag where it is.
606 } else if ($isnewcontextachild) {
607 // If the new context is a child context (e.g. activity) of this
608 // tag instance then we should move all of this tag instance
609 // down into the activity context along with the question.
610 $instancesfornewcontext[] = $tagid;
612 // If the tag is in a course context that is no longer a parent
613 // or child of the new context then this tag instance should be
615 $instancestodelete[] = $tagid;
618 // This is a catch all for any tag instances not in the question
619 // context or a course context. These tag instances should be
620 // updated to the new context id. This will clean up old invalid
622 $instancesfornewcontext[] = $tagid;
627 if (!empty($instancestodelete)) {
628 // Delete any course context tags that may no longer be valid.
629 core_tag_tag
::delete_instances_by_id($instancestodelete);
632 if (!empty($instancesfornewcontext)) {
633 // Update the tag instances to the new context id.
634 core_tag_tag
::change_instances_context($instancesfornewcontext, $newcontext);
639 * This function should be considered private to the question bank, it is called from
640 * question/editlib.php question/contextmoveq.php and a few similar places to to the
641 * work of actually moving questions and associated data. However, callers of this
642 * function also have to do other work, which is why you should not call this method
643 * directly from outside the questionbank.
645 * @param array $questionids of question ids.
646 * @param integer $newcategoryid the id of the category to move to.
648 function question_move_questions_to_category($questionids, $newcategoryid) {
651 $newcontextid = $DB->get_field('question_categories', 'contextid',
652 array('id' => $newcategoryid));
653 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
654 $questions = $DB->get_records_sql("
655 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
657 JOIN {question_categories} qc ON q.category = qc.id
658 WHERE q.id $questionidcondition", $params);
659 foreach ($questions as $question) {
660 if ($newcontextid != $question->contextid
) {
661 question_bank
::get_qtype($question->qtype
)->move_files(
662 $question->id
, $question->contextid
, $newcontextid);
664 // Check whether there could be a clash of idnumbers in the new category.
665 if (((string) $question->idnumber
!== '') &&
666 $DB->record_exists('question', ['idnumber' => $question->idnumber
, 'category' => $newcategoryid])) {
667 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
668 [$newcategoryid, $question->idnumber
. '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
672 $idnumber = $rec->idnumber
;
673 if (strpos($idnumber, '_') !== false) {
674 $unique = substr($idnumber, strpos($idnumber, '_') +
1) +
1;
677 // For the move process, add a numerical increment to the idnumber. This means that if a question is
678 // mistakenly moved then the idnumber will not be completely lost.
680 $q->id
= $question->id
;
681 $q->category
= $newcategoryid;
682 $q->idnumber
= $question->idnumber
. '_' . $unique;
683 $DB->update_record('question', $q);
686 // Log this question move.
687 $event = \core\event\question_moved
::create_from_question_instance($question, context
::instance_by_id($question->contextid
),
688 ['oldcategoryid' => $question->category
, 'newcategoryid' => $newcategoryid]);
692 // Move the questions themselves.
693 $DB->set_field_select('question', 'category', $newcategoryid,
694 "id $questionidcondition", $params);
696 // Move any subquestions belonging to them.
697 $DB->set_field_select('question', 'category', $newcategoryid,
698 "parent $questionidcondition", $params);
700 $newcontext = context
::instance_by_id($newcontextid);
701 question_move_question_tags_to_new_context($questions, $newcontext);
703 // TODO Deal with datasets.
705 // Purge these questions from the cache.
706 foreach ($questions as $question) {
707 question_bank
::notify_question_edited($question->id
);
714 * This function helps move a question cateogry to a new context by moving all
715 * the files belonging to all the questions to the new context.
716 * Also moves subcategories.
717 * @param integer $categoryid the id of the category being moved.
718 * @param integer $oldcontextid the old context id.
719 * @param integer $newcontextid the new context id.
721 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
725 $questionids = $DB->get_records_menu('question',
726 array('category' => $categoryid), '', 'id,qtype');
727 foreach ($questionids as $questionid => $qtype) {
728 question_bank
::get_qtype($qtype)->move_files(
729 $questionid, $oldcontextid, $newcontextid);
730 // Purge this question from the cache.
731 question_bank
::notify_question_edited($questionid);
733 $questions[] = (object) [
735 'contextid' => $oldcontextid
739 $newcontext = context
::instance_by_id($newcontextid);
740 question_move_question_tags_to_new_context($questions, $newcontext);
742 $subcatids = $DB->get_records_menu('question_categories',
743 array('parent' => $categoryid), '', 'id,1');
744 foreach ($subcatids as $subcatid => $notused) {
745 $DB->set_field('question_categories', 'contextid', $newcontextid,
746 array('id' => $subcatid));
747 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
752 * Generate the URL for starting a new preview of a given question with the given options.
753 * @param integer $questionid the question to preview.
754 * @param string $preferredbehaviour the behaviour to use for the preview.
755 * @param float $maxmark the maximum to mark the question out of.
756 * @param question_display_options $displayoptions the display options to use.
757 * @param int $variant the variant of the question to preview. If null, one will
758 * be picked randomly.
759 * @param object $context context to run the preview in (affects things like
760 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
761 * @return moodle_url the URL.
763 function question_preview_url($questionid, $preferredbehaviour = null,
764 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
766 $params = array('id' => $questionid);
768 if (is_null($context)) {
770 $context = $PAGE->context
;
772 if ($context->contextlevel
== CONTEXT_MODULE
) {
773 $params['cmid'] = $context->instanceid
;
774 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
775 $params['courseid'] = $context->instanceid
;
778 if (!is_null($preferredbehaviour)) {
779 $params['behaviour'] = $preferredbehaviour;
782 if (!is_null($maxmark)) {
783 $params['maxmark'] = format_float($maxmark, -1);
786 if (!is_null($displayoptions)) {
787 $params['correctness'] = $displayoptions->correctness
;
788 $params['marks'] = $displayoptions->marks
;
789 $params['markdp'] = $displayoptions->markdp
;
790 $params['feedback'] = (bool) $displayoptions->feedback
;
791 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
792 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
793 $params['history'] = (bool) $displayoptions->history
;
797 $params['variant'] = $variant;
800 return new moodle_url('/question/preview.php', $params);
804 * @return array that can be passed as $params to the {@link popup_action} constructor.
806 function question_preview_popup_params() {
814 * Given a list of ids, load the basic information about a set of questions from
815 * the questions table. The $join and $extrafields arguments can be used together
816 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
817 * read the code below to see how the SQL is assembled. Throws exceptions on error.
819 * @param array $questionids array of question ids to load. If null, then all
820 * questions matched by $join will be loaded.
821 * @param string $extrafields extra SQL code to be added to the query.
822 * @param string $join extra SQL code to be added to the query.
823 * @param array $extraparams values for any placeholders in $join.
824 * You must use named placeholders.
825 * @param string $orderby what to order the results by. Optional, default is unspecified order.
827 * @return array partially complete question objects. You need to call get_question_options
828 * on them before they can be properly used.
830 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
831 $extraparams = array(), $orderby = '') {
834 if ($questionids === null) {
838 if (empty($questionids)) {
842 list($questionidcondition, $params) = $DB->get_in_or_equal(
843 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
844 $where = 'WHERE q.id ' . $questionidcondition;
848 $join = 'JOIN ' . $join;
852 $extrafields = ', ' . $extrafields;
856 $orderby = 'ORDER BY ' . $orderby;
859 $sql = "SELECT q.*, qc.contextid{$extrafields}
861 JOIN {question_categories} qc ON q.category = qc.id
866 // Load the questions.
867 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
868 foreach ($questions as $question) {
869 $question->_partiallyloaded
= true;
876 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
877 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
878 * read the code below to see how the SQL is assembled. Throws exceptions on error.
880 * @param array $questionids array of question ids.
881 * @param string $extrafields extra SQL code to be added to the query.
882 * @param string $join extra SQL code to be added to the query.
883 * @param array $extraparams values for any placeholders in $join.
884 * You are strongly recommended to use named placeholder.
886 * @return array question objects.
888 function question_load_questions($questionids, $extrafields = '', $join = '') {
889 $questions = question_preload_questions($questionids, $extrafields, $join);
891 // Load the question type specific information
892 if (!get_question_options($questions)) {
893 return 'Could not load the question options';
900 * Private function to factor common code out of get_question_options().
902 * @param object $question the question to tidy.
903 * @param stdClass $category The question_categories record for the given $question.
904 * @param stdClass[]|null $tagobjects The tags for the given $question.
905 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
907 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
908 // Load question-type specific fields.
909 if (!question_bank
::is_qtype_installed($question->qtype
)) {
910 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
911 'qtype_missingtype')) . $question->questiontext
;
913 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
915 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
916 $question->defaultmark +
= 0;
917 $question->penalty +
= 0;
919 if (isset($question->_partiallyloaded
)) {
920 unset($question->_partiallyloaded
);
923 $question->categoryobject
= $category;
925 if (!is_null($tagobjects)) {
926 $categorycontext = context
::instance_by_id($category->contextid
);
927 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
928 $question->coursetagobjects
= $sortedtagobjects->coursetagobjects
;
929 $question->coursetags
= $sortedtagobjects->coursetags
;
930 $question->tagobjects
= $sortedtagobjects->tagobjects
;
931 $question->tags
= $sortedtagobjects->tags
;
936 * Updates the question objects with question type specific
937 * information by calling {@link get_question_options()}
939 * Can be called either with an array of question objects or with a single
942 * @param mixed $questions Either an array of question objects to be updated
943 * or just a single question object
944 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
945 * @param stdClass[] $filtercourses The courses to filter the course tags by.
946 * @return bool Indicates success or failure.
948 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
951 $questionlist = is_array($questions) ?
$questions : [$questions];
955 if (empty($questionlist)) {
959 foreach ($questionlist as $question) {
960 $questionids[] = $question->id
;
962 if (!in_array($question->category
, $categoryids)) {
963 $categoryids[] = $question->category
;
967 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
969 if ($loadtags && core_tag_tag
::is_enabled('core_question', 'question')) {
970 $tagobjectsbyquestion = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
972 $tagobjectsbyquestion = null;
975 foreach ($questionlist as $question) {
976 if (is_null($tagobjectsbyquestion)) {
979 $tagobjects = $tagobjectsbyquestion[$question->id
];
982 _tidy_question($question, $categories[$question->category
], $tagobjects, $filtercourses);
989 * Sort question tags by course or normal tags.
991 * This function also search tag instances that may have a context id that don't match either a course or
992 * question context and fix the data setting the correct context id.
994 * @param stdClass[] $tagobjects The tags for the given $question.
995 * @param stdClass $categorycontext The question categories context.
996 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
997 * @return stdClass $sortedtagobjects Sorted tag objects.
999 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
1001 // Questions can have two sets of tag instances. One set at the
1002 // course context level and another at the context the question
1003 // belongs to (e.g. course category, system etc).
1004 $sortedtagobjects = new stdClass();
1005 $sortedtagobjects->coursetagobjects
= [];
1006 $sortedtagobjects->coursetags
= [];
1007 $sortedtagobjects->tagobjects
= [];
1008 $sortedtagobjects->tags
= [];
1009 $taginstanceidstonormalise = [];
1010 $filtercoursecontextids = [];
1011 $hasfiltercourses = !empty($filtercourses);
1013 if ($hasfiltercourses) {
1014 // If we're being asked to filter the course tags by a set of courses
1015 // then get the context ids to filter below.
1016 $filtercoursecontextids = array_map(function($course) {
1017 $coursecontext = context_course
::instance($course->id
);
1018 return $coursecontext->id
;
1022 foreach ($tagobjects as $tagobject) {
1023 $tagcontextid = $tagobject->taginstancecontextid
;
1024 $tagcontext = context
::instance_by_id($tagcontextid);
1025 $tagcoursecontext = $tagcontext->get_course_context(false);
1026 // This is a course tag if the tag context is a course context which
1027 // doesn't match the question's context. Any tag in the question context
1028 // is not considered a course tag, it belongs to the question.
1029 $iscoursetag = $tagcoursecontext
1030 && $tagcontext->id
== $tagcoursecontext->id
1031 && $tagcontext->id
!= $categorycontext->id
;
1034 // Any tag instance in a course context level is considered a course tag.
1035 if (!$hasfiltercourses ||
in_array($tagcontextid, $filtercoursecontextids)) {
1036 // Add the tag to the list of course tags if we aren't being
1037 // asked to filter or if this tag is in the list of courses
1038 // we're being asked to filter by.
1039 $sortedtagobjects->coursetagobjects
[] = $tagobject;
1040 $sortedtagobjects->coursetags
[$tagobject->id
] = $tagobject->get_display_name();
1043 // All non course context level tag instances or tags in the question
1044 // context belong to the context that the question was created in.
1045 $sortedtagobjects->tagobjects
[] = $tagobject;
1046 $sortedtagobjects->tags
[$tagobject->id
] = $tagobject->get_display_name();
1048 // Due to legacy tag implementations that don't force the recording
1049 // of a context id, some tag instances may have context ids that don't
1050 // match either a course context or the question context. In this case
1051 // we should take the opportunity to fix up the data and set the correct
1053 if ($tagcontext->id
!= $categorycontext->id
) {
1054 $taginstanceidstonormalise[] = $tagobject->taginstanceid
;
1055 // Update the object properties to reflect the DB update that will
1057 $tagobject->taginstancecontextid
= $categorycontext->id
;
1062 if (!empty($taginstanceidstonormalise)) {
1063 // If we found any tag instances with incorrect context id data then we can
1064 // correct those values now by setting them to the question context id.
1065 core_tag_tag
::change_instances_context($taginstanceidstonormalise, $categorycontext);
1068 return $sortedtagobjects;
1072 * Print the icon for the question type
1074 * @param object $question The question object for which the icon is required.
1075 * Only $question->qtype is used.
1076 * @return string the HTML for the img tag.
1078 function print_question_icon($question) {
1080 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
1084 * Creates a stamp that uniquely identifies this version of the question
1086 * In future we want this to use a hash of the question data to guarantee that
1087 * identical versions have the same version stamp.
1089 * @param object $question
1090 * @return string A unique version stamp
1092 function question_hash($question) {
1093 return make_unique_id_code();
1096 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1099 * returns the categories with their names ordered following parent-child relationships
1100 * finally it tries to return pending categories (those being orphaned, whose parent is
1101 * incorrect) to avoid missing any category from original array.
1103 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1106 $children = array();
1107 $keys = array_keys($categories);
1109 foreach ($keys as $key) {
1110 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1111 $children[$key] = $categories[$key];
1112 $categories[$key]->processed
= true;
1113 $children = $children +
sort_categories_by_tree(
1114 $categories, $children[$key]->id
, $level+
1);
1117 //If level = 1, we have finished, try to look for non processed categories
1118 // (bad parent) and sort them too
1120 foreach ($keys as $key) {
1121 // If not processed and it's a good candidate to start (because its
1122 // parent doesn't exist in the course)
1123 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
1124 array('contextid' => $categories[$key]->contextid
,
1125 'id' => $categories[$key]->parent
))) {
1126 $children[$key] = $categories[$key];
1127 $categories[$key]->processed
= true;
1128 $children = $children +
sort_categories_by_tree(
1129 $categories, $children[$key]->id
, $level +
1);
1137 * Private method, only for the use of add_indented_names().
1139 * Recursively adds an indentedname field to each category, starting with the category
1140 * with id $id, and dealing with that category and all its children, and
1141 * return a new array, with those categories in the right order.
1143 * @param array $categories an array of categories which has had childids
1144 * fields added by flatten_category_tree(). Passed by reference for
1145 * performance only. It is not modfied.
1146 * @param int $id the category to start the indenting process from.
1147 * @param int $depth the indent depth. Used in recursive calls.
1148 * @return array a new array of categories, in the right order for the tree.
1150 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1152 // Indent the name of this category.
1153 $newcategories = array();
1154 $newcategories[$id] = $categories[$id];
1155 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
1156 $categories[$id]->name
;
1158 // Recursively indent the children.
1159 foreach ($categories[$id]->childids
as $childid) {
1160 if ($childid != $nochildrenof) {
1161 $newcategories = $newcategories +
flatten_category_tree(
1162 $categories, $childid, $depth +
1, $nochildrenof);
1166 // Remove the childids array that were temporarily added.
1167 unset($newcategories[$id]->childids
);
1169 return $newcategories;
1173 * Format categories into an indented list reflecting the tree structure.
1175 * @param array $categories An array of category objects, for example from the.
1176 * @return array The formatted list of categories.
1178 function add_indented_names($categories, $nochildrenof = -1) {
1180 // Add an array to each category to hold the child category ids. This array
1181 // will be removed again by flatten_category_tree(). It should not be used
1182 // outside these two functions.
1183 foreach (array_keys($categories) as $id) {
1184 $categories[$id]->childids
= array();
1187 // Build the tree structure, and record which categories are top-level.
1188 // We have to be careful, because the categories array may include published
1189 // categories from other courses, but not their parents.
1190 $toplevelcategoryids = array();
1191 foreach (array_keys($categories) as $id) {
1192 if (!empty($categories[$id]->parent
) &&
1193 array_key_exists($categories[$id]->parent
, $categories)) {
1194 $categories[$categories[$id]->parent
]->childids
[] = $id;
1196 $toplevelcategoryids[] = $id;
1200 // Flatten the tree to and add the indents.
1201 $newcategories = array();
1202 foreach ($toplevelcategoryids as $id) {
1203 $newcategories = $newcategories +
flatten_category_tree(
1204 $categories, $id, 0, $nochildrenof);
1207 return $newcategories;
1211 * Output a select menu of question categories.
1213 * Categories from this course and (optionally) published categories from other courses
1214 * are included. Optionally, only categories the current user may edit can be included.
1216 * @param integer $courseid the id of the course to get the categories for.
1217 * @param integer $published if true, include publised categories from other courses.
1218 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1219 * @param integer $selected optionally, the id of a category to be selected by
1220 * default in the dropdown.
1222 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1223 $selected = "", $nochildrenof = -1) {
1224 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1225 false, $nochildrenof, false);
1229 $choose = 'choosedots';
1232 foreach ($categoriesarray as $group => $opts) {
1233 $options[] = array($group => $opts);
1235 echo html_writer
::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1237 'id' => 'id_movetocategory',
1238 'class' => 'custom-select',
1239 'data-action' => 'toggle',
1240 'data-togglegroup' => 'qbank',
1241 'data-toggle' => 'action',
1244 echo html_writer
::select($options, 'category', $selected, $choose, $attrs);
1248 * @param integer $contextid a context id.
1249 * @return object the default question category for that context, or false if none.
1251 function question_get_default_category($contextid) {
1253 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1254 array($contextid), 'id', '*', 0, 1);
1255 if (!empty($category)) {
1256 return reset($category);
1263 * Gets the top category in the given context.
1264 * This function can optionally create the top category if it doesn't exist.
1266 * @param int $contextid A context id.
1267 * @param bool $create Whether create a top category if it doesn't exist.
1268 * @return bool|stdClass The top question category for that context, or false if none.
1270 function question_get_top_category($contextid, $create = false) {
1272 $category = $DB->get_record('question_categories',
1273 array('contextid' => $contextid, 'parent' => 0));
1275 if (!$category && $create) {
1276 // We need to make one.
1277 $category = new stdClass();
1278 $category->name
= 'top'; // A non-real name for the top category. It will be localised at the display time.
1279 $category->info
= '';
1280 $category->contextid
= $contextid;
1281 $category->parent
= 0;
1282 $category->sortorder
= 0;
1283 $category->stamp
= make_unique_id_code();
1284 $category->id
= $DB->insert_record('question_categories', $category);
1291 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1293 * @param array $contextids List of context ids
1296 function question_get_top_categories_for_contexts($contextids) {
1299 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1300 list($insql, $params) = $DB->get_in_or_equal($contextids);
1301 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1302 $topcategories = $DB->get_fieldset_sql($sql, $params);
1304 return $topcategories;
1308 * Gets the default category in the most specific context.
1309 * If no categories exist yet then default ones are created in all contexts.
1311 * @param array $contexts The context objects for this context and all parent contexts.
1312 * @return object The default category - the category in the course context
1314 function question_make_default_categories($contexts) {
1316 static $preferredlevels = array(
1317 CONTEXT_COURSE
=> 4,
1318 CONTEXT_MODULE
=> 3,
1319 CONTEXT_COURSECAT
=> 2,
1320 CONTEXT_SYSTEM
=> 1,
1325 // If it already exists, just return it.
1326 foreach ($contexts as $key => $context) {
1327 $topcategory = question_get_top_category($context->id
, true);
1328 if (!$exists = $DB->record_exists("question_categories",
1329 array('contextid' => $context->id
, 'parent' => $topcategory->id
))) {
1330 // Otherwise, we need to make one
1331 $category = new stdClass();
1332 $contextname = $context->get_context_name(false, true);
1333 // Max length of name field is 255.
1334 $category->name
= shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1335 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1336 $category->contextid
= $context->id
;
1337 $category->parent
= $topcategory->id
;
1338 // By default, all categories get this number, and are sorted alphabetically.
1339 $category->sortorder
= 999;
1340 $category->stamp
= make_unique_id_code();
1341 $category->id
= $DB->insert_record('question_categories', $category);
1343 $category = question_get_default_category($context->id
);
1345 $thispreferredness = $preferredlevels[$context->contextlevel
];
1346 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1347 $thispreferredness +
= 10;
1349 if ($thispreferredness > $preferredness) {
1350 $toreturn = $category;
1351 $preferredness = $thispreferredness;
1355 if (!is_null($toreturn)) {
1356 $toreturn = clone($toreturn);
1362 * Get all the category objects, including a count of the number of questions in that category,
1363 * for all the categories in the lists $contexts.
1365 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1366 * @param string $sortorder used as the ORDER BY clause in the select statement.
1367 * @param bool $top Whether to return the top categories or not.
1368 * @return array of category objects.
1370 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1372 $topwhere = $top ?
'' : 'AND c.parent <> 0';
1373 return $DB->get_records_sql("
1374 SELECT c.*, (SELECT count(1) FROM {question} q
1375 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1376 FROM {question_categories} c
1377 WHERE c.contextid IN ($contexts) $topwhere
1378 ORDER BY $sortorder");
1382 * Output an array of question categories.
1384 * @param array $contexts The list of contexts.
1385 * @param bool $top Whether to return the top categories or not.
1386 * @param int $currentcat
1387 * @param bool $popupform
1388 * @param int $nochildrenof
1389 * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
1392 function question_category_options($contexts, $top = false, $currentcat = 0,
1393 $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
1395 $pcontexts = array();
1396 foreach ($contexts as $context) {
1397 $pcontexts[] = $context->id
;
1399 $contextslist = join(', ', $pcontexts);
1401 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1404 $categories = question_fix_top_names($categories);
1407 $categories = question_add_context_in_key($categories);
1408 $categories = add_indented_names($categories, $nochildrenof);
1410 // sort cats out into different contexts
1411 $categoriesarray = array();
1412 foreach ($pcontexts as $contextid) {
1413 $context = context
::instance_by_id($contextid);
1414 $contextstring = $context->get_context_name(true, true, $escapecontextnames);
1415 foreach ($categories as $category) {
1416 if ($category->contextid
== $contextid) {
1417 $cid = $category->id
;
1418 if ($currentcat != $cid ||
$currentcat == 0) {
1420 $a->name
= format_string($category->indentedname
, true,
1421 array('context' => $context));
1422 if ($category->idnumber
!== null && $category->idnumber
!== '') {
1423 $a->idnumber
= s($category->idnumber
);
1425 if (!empty($category->questioncount
)) {
1426 $a->questioncount
= $category->questioncount
;
1428 if (isset($a->idnumber
) && isset($a->questioncount
)) {
1429 $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
1430 } else if (isset($a->idnumber
)) {
1431 $formattedname = get_string('categorynamewithidnumber', 'question', $a);
1432 } else if (isset($a->questioncount
)) {
1433 $formattedname = get_string('categorynamewithcount', 'question', $a);
1435 $formattedname = $a->name
;
1437 $categoriesarray[$contextstring][$cid] = $formattedname;
1443 $popupcats = array();
1444 foreach ($categoriesarray as $contextstring => $optgroup) {
1446 foreach ($optgroup as $key => $value) {
1447 $key = str_replace($CFG->wwwroot
, '', $key);
1448 $group[$key] = $value;
1450 $popupcats[] = array($contextstring => $group);
1454 return $categoriesarray;
1458 function question_add_context_in_key($categories) {
1459 $newcatarray = array();
1460 foreach ($categories as $id => $category) {
1461 $category->parent
= "$category->parent,$category->contextid";
1462 $category->id
= "$category->id,$category->contextid";
1463 $newcatarray["$id,$category->contextid"] = $category;
1465 return $newcatarray;
1469 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1471 * @param array $categories An array of question categories.
1472 * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
1473 * @return array The same question category list given to the function, with the top category names being translated.
1475 function question_fix_top_names($categories, $escape = true) {
1477 foreach ($categories as $id => $category) {
1478 if ($category->parent
== 0) {
1479 $context = context
::instance_by_id($category->contextid
);
1480 $categories[$id]->name
= get_string('topfor', 'question', $context->get_context_name(false, false, $escape));
1488 * @return array of question category ids of the category and all subcategories.
1490 function question_categorylist($categoryid) {
1493 // final list of category IDs
1494 $categorylist = array();
1496 // a list of category IDs to check for any sub-categories
1497 $subcategories = array($categoryid);
1499 while ($subcategories) {
1500 foreach ($subcategories as $subcategory) {
1501 // if anything from the temporary list was added already, then we have a loop
1502 if (isset($categorylist[$subcategory])) {
1503 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1505 $categorylist[$subcategory] = $subcategory;
1508 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1510 $subcategories = $DB->get_records_select_menu('question_categories',
1511 "parent $in", $params, NULL, 'id,id AS id2');
1514 return $categorylist;
1518 * Get all parent categories of a given question category in decending order.
1519 * @param int $categoryid for which you want to find the parents.
1520 * @return array of question category ids of all parents categories.
1522 function question_categorylist_parents(int $categoryid) {
1524 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1528 $categorylist = [$parent];
1529 $currentid = $parent;
1530 while ($currentid) {
1531 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1533 $categorylist[] = $currentid;
1536 // Present the list in decending order (the top category at the top).
1537 $categorylist = array_reverse($categorylist);
1538 return $categorylist;
1541 //===========================
1542 // Import/Export Functions
1543 //===========================
1546 * Get list of available import or export formats
1547 * @param string $type 'import' if import list, otherwise export list assumed
1548 * @return array sorted list of import/export formats available
1550 function get_import_export_formats($type) {
1552 require_once($CFG->dirroot
. '/question/format.php');
1554 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1556 $fileformatname = array();
1557 foreach ($formatclasses as $component => $formatclass) {
1559 $format = new $formatclass();
1560 if ($type == 'import') {
1561 $provided = $format->provide_import();
1563 $provided = $format->provide_export();
1567 list($notused, $fileformat) = explode('_', $component, 2);
1568 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1572 core_collator
::asort($fileformatnames);
1573 return $fileformatnames;
1578 * Create a reasonable default file name for exporting questions from a particular
1580 * @param object $course the course the questions are in.
1581 * @param object $category the question category.
1582 * @return string the filename.
1584 function question_default_export_filename($course, $category) {
1585 // We build a string that is an appropriate name (questions) from the lang pack,
1586 // then the corse shortname, then the question category name, then a timestamp.
1588 $base = clean_filename(get_string('exportfilename', 'question'));
1590 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1591 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1593 $shortname = clean_filename($course->shortname
);
1594 if ($shortname == '' ||
$shortname == '_' ) {
1595 $shortname = $course->id
;
1598 $categoryname = clean_filename(format_string($category->name
));
1600 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1602 return $export_name;
1606 * Converts contextlevels to strings and back to help with reading/writing contexts
1607 * to/from import/export files.
1609 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1612 class context_to_string_translator
{
1614 * @var array used to translate between contextids and strings for this context.
1616 protected $contexttostringarray = array();
1618 public function __construct($contexts) {
1619 $this->generate_context_to_string_array($contexts);
1622 public function context_to_string($contextid) {
1623 return $this->contexttostringarray
[$contextid];
1626 public function string_to_context($contextname) {
1627 $contextid = array_search($contextname, $this->contexttostringarray
);
1631 protected function generate_context_to_string_array($contexts) {
1632 if (!$this->contexttostringarray
) {
1634 foreach ($contexts as $context) {
1635 switch ($context->contextlevel
) {
1636 case CONTEXT_MODULE
:
1637 $contextstring = 'module';
1639 case CONTEXT_COURSE
:
1640 $contextstring = 'course';
1642 case CONTEXT_COURSECAT
:
1643 $contextstring = "cat$catno";
1646 case CONTEXT_SYSTEM
:
1647 $contextstring = 'system';
1650 $this->contexttostringarray
[$context->id
] = $contextstring;
1658 * Check capability on category
1660 * @param int|stdClass|question_definition $questionorid object or id.
1661 * If an object is passed, it should include ->contextid and ->createdby.
1662 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1663 * @param int $notused no longer used.
1664 * @return bool this user has the capability $cap for this question $question?
1665 * @throws coding_exception
1667 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1670 if (is_numeric($questionorid)) {
1671 $questionid = (int)$questionorid;
1672 } else if (is_object($questionorid)) {
1673 // All we really need in this function is the contextid and author of the question.
1674 // We won't bother fetching other details of the question if these 2 fields are provided.
1675 if (isset($questionorid->contextid
) && isset($questionorid->createdby
)) {
1676 $question = $questionorid;
1677 } else if (!empty($questionorid->id
)) {
1678 $questionid = $questionorid->id
;
1682 // At this point, either $question or $questionid is expected to be set.
1683 if (isset($questionid)) {
1685 $question = question_bank
::load_question_data($questionid);
1686 } catch (Exception
$e) {
1687 // Let's log the exception for future debugging,
1688 // but not during Behat, or we can't test these cases.
1689 if (!defined('BEHAT_SITE_RUNNING')) {
1690 debugging($e->getMessage(), DEBUG_NORMAL
, $e->getTrace());
1693 // Well, at least we tried. Seems that we really have to read from DB.
1694 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1696 JOIN {question_categories} qc ON q.category = qc.id
1697 WHERE q.id = :id', ['id' => $questionid]);
1701 if (!isset($question)) {
1702 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1705 $context = context
::instance_by_id($question->contextid
);
1707 // These are existing questions capabilities that are set per category.
1708 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1709 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1711 if (!isset($capabilitieswithallandmine[$cap])) {
1712 return has_capability('moodle/question:' . $cap, $context);
1714 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1715 ($question->createdby
== $USER->id
&& has_capability('moodle/question:' . $cap . 'mine', $context));
1720 * Require capability on question.
1722 function question_require_capability_on($question, $cap) {
1723 if (!question_has_capability_on($question, $cap)) {
1724 print_error('nopermissions', '', '', $cap);
1730 * @param object $context a context
1731 * @return string A URL for editing questions in this context.
1733 function question_edit_url($context) {
1735 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1738 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1739 $defaultcategory = question_get_default_category($context->id
);
1740 if ($defaultcategory) {
1741 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1743 switch ($context->contextlevel
) {
1744 case CONTEXT_SYSTEM
:
1745 return $baseurl . 'courseid=' . $SITE->id
;
1746 case CONTEXT_COURSECAT
:
1747 // This is nasty, becuase we can only edit questions in a course
1748 // context at the moment, so for now we just return false.
1750 case CONTEXT_COURSE
:
1751 return $baseurl . 'courseid=' . $context->instanceid
;
1752 case CONTEXT_MODULE
:
1753 return $baseurl . 'cmid=' . $context->instanceid
;
1759 * Adds question bank setting links to the given navigation node if caps are met.
1761 * @param navigation_node $navigationnode The navigation node to add the question branch to
1762 * @param object $context
1763 * @return navigation_node Returns the question branch that was added
1765 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1768 if ($context->contextlevel
== CONTEXT_COURSE
) {
1769 $params = array('courseid'=>$context->instanceid
);
1770 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1771 $params = array('cmid'=>$context->instanceid
);
1776 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1777 $params['cat'] = $cat;
1780 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1781 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
, null, 'questionbank');
1783 $contexts = new question_edit_contexts($context);
1784 if ($contexts->have_one_edit_tab_cap('questions')) {
1785 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1786 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
, null, 'questions');
1788 if ($contexts->have_one_edit_tab_cap('categories')) {
1789 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1790 '/question/category.php', $params), navigation_node
::TYPE_SETTING
, null, 'categories');
1792 if ($contexts->have_one_edit_tab_cap('import')) {
1793 $questionnode->add(get_string('import', 'question'), new moodle_url(
1794 '/question/import.php', $params), navigation_node
::TYPE_SETTING
, null, 'import');
1796 if ($contexts->have_one_edit_tab_cap('export')) {
1797 $questionnode->add(get_string('export', 'question'), new moodle_url(
1798 '/question/export.php', $params), navigation_node
::TYPE_SETTING
, null, 'export');
1801 return $questionnode;
1805 * @return array all the capabilities that relate to accessing particular questions.
1807 function question_get_question_capabilities() {
1809 'moodle/question:add',
1810 'moodle/question:editmine',
1811 'moodle/question:editall',
1812 'moodle/question:viewmine',
1813 'moodle/question:viewall',
1814 'moodle/question:usemine',
1815 'moodle/question:useall',
1816 'moodle/question:movemine',
1817 'moodle/question:moveall',
1818 'moodle/question:tagmine',
1819 'moodle/question:tagall',
1824 * @return array all the question bank capabilities.
1826 function question_get_all_capabilities() {
1827 $caps = question_get_question_capabilities();
1828 $caps[] = 'moodle/question:managecategory';
1829 $caps[] = 'moodle/question:flag';
1835 * Tracks all the contexts related to the one where we are currently editing
1836 * questions, and provides helper methods to check permissions.
1838 * @copyright 2007 Jamie Pratt me@jamiep.org
1839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1841 class question_edit_contexts
{
1843 public static $caps = array(
1844 'editq' => array('moodle/question:add',
1845 'moodle/question:editmine',
1846 'moodle/question:editall',
1847 'moodle/question:viewmine',
1848 'moodle/question:viewall',
1849 'moodle/question:usemine',
1850 'moodle/question:useall',
1851 'moodle/question:movemine',
1852 'moodle/question:moveall'),
1853 'questions'=>array('moodle/question:add',
1854 'moodle/question:editmine',
1855 'moodle/question:editall',
1856 'moodle/question:viewmine',
1857 'moodle/question:viewall',
1858 'moodle/question:movemine',
1859 'moodle/question:moveall'),
1860 'categories'=>array('moodle/question:managecategory'),
1861 'import'=>array('moodle/question:add'),
1862 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1864 protected $allcontexts;
1868 * @param context the current context.
1870 public function __construct(context
$thiscontext) {
1871 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1875 * @return context[] all parent contexts
1877 public function all() {
1878 return $this->allcontexts
;
1882 * @return context lowest context which must be either the module or course context
1884 public function lowest() {
1885 return $this->allcontexts
[0];
1889 * @param string $cap capability
1890 * @return context[] parent contexts having capability, zero based index
1892 public function having_cap($cap) {
1893 $contextswithcap = array();
1894 foreach ($this->allcontexts
as $context) {
1895 if (has_capability($cap, $context)) {
1896 $contextswithcap[] = $context;
1899 return $contextswithcap;
1903 * @param array $caps capabilities
1904 * @return context[] parent contexts having at least one of $caps, zero based index
1906 public function having_one_cap($caps) {
1907 $contextswithacap = array();
1908 foreach ($this->allcontexts
as $context) {
1909 foreach ($caps as $cap) {
1910 if (has_capability($cap, $context)) {
1911 $contextswithacap[] = $context;
1912 break; //done with caps loop
1916 return $contextswithacap;
1920 * @param string $tabname edit tab name
1921 * @return context[] parent contexts having at least one of $caps, zero based index
1923 public function having_one_edit_tab_cap($tabname) {
1924 return $this->having_one_cap(self
::$caps[$tabname]);
1928 * @return context[] those contexts where a user can add a question and then use it.
1930 public function having_add_and_use() {
1931 $contextswithcap = array();
1932 foreach ($this->allcontexts
as $context) {
1933 if (!has_capability('moodle/question:add', $context)) {
1936 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1939 $contextswithcap[] = $context;
1941 return $contextswithcap;
1945 * Has at least one parent context got the cap $cap?
1947 * @param string $cap capability
1950 public function have_cap($cap) {
1951 return (count($this->having_cap($cap)));
1955 * Has at least one parent context got one of the caps $caps?
1957 * @param array $caps capability
1960 public function have_one_cap($caps) {
1961 foreach ($caps as $cap) {
1962 if ($this->have_cap($cap)) {
1970 * Has at least one parent context got one of the caps for actions on $tabname
1972 * @param string $tabname edit tab name
1975 public function have_one_edit_tab_cap($tabname) {
1976 return $this->have_one_cap(self
::$caps[$tabname]);
1980 * Throw error if at least one parent context hasn't got the cap $cap
1982 * @param string $cap capability
1984 public function require_cap($cap) {
1985 if (!$this->have_cap($cap)) {
1986 print_error('nopermissions', '', '', $cap);
1991 * Throw error if at least one parent context hasn't got one of the caps $caps
1993 * @param array $caps capabilities
1995 public function require_one_cap($caps) {
1996 if (!$this->have_one_cap($caps)) {
1997 $capsstring = join(', ', $caps);
1998 print_error('nopermissions', '', '', $capsstring);
2003 * Throw error if at least one parent context hasn't got one of the caps $caps
2005 * @param string $tabname edit tab name
2007 public function require_one_edit_tab_cap($tabname) {
2008 if (!$this->have_one_edit_tab_cap($tabname)) {
2009 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
2016 * Helps call file_rewrite_pluginfile_urls with the right parameters.
2018 * @package core_question
2020 * @param string $text text being processed
2021 * @param string $file the php script used to serve files
2022 * @param int $contextid context ID
2023 * @param string $component component
2024 * @param string $filearea filearea
2025 * @param array $ids other IDs will be used to check file permission
2026 * @param int $itemid item ID
2027 * @param array $options options
2030 function question_rewrite_question_urls($text, $file, $contextid, $component,
2031 $filearea, array $ids, $itemid, array $options=null) {
2035 $idsstr .= implode('/', $ids);
2037 if ($itemid !== null) {
2038 $idsstr .= '/' . $itemid;
2040 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
2041 $filearea, $idsstr, $options);
2045 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
2046 * viewing the question outside an attempt (for example, in the question bank
2047 * listing or in the quiz statistics report).
2049 * @param string $text the question text.
2050 * @param int $questionid the question id.
2051 * @param int $filecontextid the context id of the question being displayed.
2052 * @param string $filecomponent the component that owns the file area.
2053 * @param string $filearea the file area name.
2054 * @param int|null $itemid the file's itemid
2055 * @param int $previewcontextid the context id where the preview is being displayed.
2056 * @param string $previewcomponent component responsible for displaying the preview.
2057 * @param array $options text and file options ('forcehttps'=>false)
2058 * @return string $questiontext with URLs rewritten.
2060 function question_rewrite_question_preview_urls($text, $questionid,
2061 $filecontextid, $filecomponent, $filearea, $itemid,
2062 $previewcontextid, $previewcomponent, $options = null) {
2064 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2066 $path .= '/' . $itemid;
2069 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2070 $filecomponent, $filearea, $path, $options);
2074 * Called by pluginfile.php to serve files related to the 'question' core
2075 * component and for files belonging to qtypes.
2077 * For files that relate to questions in a question_attempt, then we delegate to
2078 * a function in the component that owns the attempt (for example in the quiz,
2079 * or in core question preview) to get necessary inforation.
2081 * (Note that, at the moment, all question file areas relate to questions in
2082 * attempts, so the If at the start of the last paragraph is always true.)
2084 * Does not return, either calls send_file_not_found(); or serves the file.
2086 * @package core_question
2088 * @param stdClass $course course settings object
2089 * @param stdClass $context context object
2090 * @param string $component the name of the component we are serving files for.
2091 * @param string $filearea the name of the file area.
2092 * @param array $args the remaining bits of the file path.
2093 * @param bool $forcedownload whether the user must be forced to download the file.
2094 * @param array $options additional options affecting the file serving
2096 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2099 // Special case, sending a question bank export.
2100 if ($filearea === 'export') {
2101 list($context, $course, $cm) = get_context_info_array($context->id
);
2102 require_login($course, false, $cm);
2104 require_once($CFG->dirroot
. '/question/editlib.php');
2105 $contexts = new question_edit_contexts($context);
2106 // check export capability
2107 $contexts->require_one_edit_tab_cap('export');
2108 $category_id = (int)array_shift($args);
2109 $format = array_shift($args);
2110 $cattofile = array_shift($args);
2111 $contexttofile = array_shift($args);
2112 $filename = array_shift($args);
2114 // load parent class for import/export
2115 require_once($CFG->dirroot
. '/question/format.php');
2116 require_once($CFG->dirroot
. '/question/editlib.php');
2117 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
2119 $classname = 'qformat_' . $format;
2120 if (!class_exists($classname)) {
2121 send_file_not_found();
2124 $qformat = new $classname();
2126 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2127 send_file_not_found();
2130 $qformat->setCategory($category);
2131 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2132 $qformat->setCourse($course);
2134 if ($cattofile == 'withcategories') {
2135 $qformat->setCattofile(true);
2137 $qformat->setCattofile(false);
2140 if ($contexttofile == 'withcontexts') {
2141 $qformat->setContexttofile(true);
2143 $qformat->setContexttofile(false);
2146 if (!$qformat->exportpreprocess()) {
2147 send_file_not_found();
2148 print_error('exporterror', 'question', $thispageurl->out());
2151 // export data to moodle file pool
2152 if (!$content = $qformat->exportprocess()) {
2153 send_file_not_found();
2156 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2159 // Normal case, a file belonging to a question.
2160 $qubaidorpreview = array_shift($args);
2162 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2163 if ($qubaidorpreview === 'preview') {
2164 $previewcontextid = (int)array_shift($args);
2165 $previewcomponent = array_shift($args);
2166 $questionid = (int) array_shift($args);
2167 $previewcontext = context_helper
::instance_by_id($previewcontextid);
2169 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2170 $previewcontext, $questionid,
2171 $context, $component, $filearea, $args,
2172 $forcedownload, $options), 'callbackmissing');
2174 if ($result === 'callbackmissing') {
2175 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2176 "{$previewcomponent}_question_preview_pluginfile callback. " .
2177 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER
);
2180 send_file_not_found();
2183 // 2. A question being attempted in the normal way.
2184 $qubaid = (int)$qubaidorpreview;
2185 $slot = (int)array_shift($args);
2187 $module = $DB->get_field('question_usages', 'component',
2188 array('id' => $qubaid));
2190 send_file_not_found();
2193 if ($module === 'core_question_preview') {
2194 require_once($CFG->dirroot
. '/question/previewlib.php');
2195 return question_preview_question_pluginfile($course, $context,
2196 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2199 $dir = core_component
::get_component_directory($module);
2200 if (!file_exists("$dir/lib.php")) {
2201 send_file_not_found();
2203 include_once("$dir/lib.php");
2205 $filefunction = $module . '_question_pluginfile';
2206 if (function_exists($filefunction)) {
2207 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2208 $args, $forcedownload, $options);
2211 // Okay, we're here so lets check for function without 'mod_'.
2212 if (strpos($module, 'mod_') === 0) {
2213 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2214 if (function_exists($filefunctionold)) {
2215 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2216 $args, $forcedownload, $options);
2220 send_file_not_found();
2225 * Serve questiontext files in the question text when they are displayed in this report.
2227 * @package core_files
2229 * @param context $previewcontext the context in which the preview is happening.
2230 * @param int $questionid the question id.
2231 * @param context $filecontext the file (question) context.
2232 * @param string $filecomponent the component the file belongs to.
2233 * @param string $filearea the file area.
2234 * @param array $args remaining file args.
2235 * @param bool $forcedownload.
2236 * @param array $options additional options affecting the file serving.
2238 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2239 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2242 // Verify that contextid matches the question.
2243 $question = $DB->get_record_sql('
2244 SELECT q.*, qc.contextid
2246 JOIN {question_categories} qc ON qc.id = q.category
2247 WHERE q.id = :id AND qc.contextid = :contextid',
2248 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
2250 // Check the capability.
2251 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
2252 require_login($course, false, $cm);
2254 question_require_capability_on($question, 'use');
2256 $fs = get_file_storage();
2257 $relativepath = implode('/', $args);
2258 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2259 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2260 send_file_not_found();
2263 send_stored_file($file, 0, 0, $forcedownload, $options);
2267 * Create url for question export
2269 * @param int $contextid, current context
2270 * @param int $categoryid, categoryid
2271 * @param string $format
2272 * @param string $withcategories
2273 * @param string $ithcontexts
2274 * @param moodle_url export file url
2276 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2277 $withcontexts, $filename) {
2279 $urlbase = "$CFG->wwwroot/pluginfile.php";
2280 return moodle_url
::make_file_url($urlbase,
2281 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2282 "/{$withcontexts}/{$filename}", true);
2286 * Get the URL to export a single question (exportone.php).
2288 * @param stdClass|question_definition $question the question definition as obtained from
2289 * question_bank::load_question_data() or question_bank::make_question().
2290 * (Only ->id and ->contextid are used.)
2291 * @return moodle_url the requested URL.
2293 function question_get_export_single_question_url($question) {
2294 $params = ['id' => $question->id
, 'sesskey' => sesskey()];
2295 $context = context
::instance_by_id($question->contextid
);
2296 switch ($context->contextlevel
) {
2297 case CONTEXT_MODULE
:
2298 $params['cmid'] = $context->instanceid
;
2301 case CONTEXT_COURSE
:
2302 $params['courseid'] = $context->instanceid
;
2306 $params['courseid'] = SITEID
;
2309 return new moodle_url('/question/exportone.php', $params);
2313 * Return a list of page types
2314 * @param string $pagetype current page type
2315 * @param stdClass $parentcontext Block's parent context
2316 * @param stdClass $currentcontext Current context of block
2318 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2321 'question-*'=>get_string('page-question-x', 'question'),
2322 'question-edit'=>get_string('page-question-edit', 'question'),
2323 'question-category'=>get_string('page-question-category', 'question'),
2324 'question-export'=>get_string('page-question-export', 'question'),
2325 'question-import'=>get_string('page-question-import', 'question')
2327 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
2328 require_once($CFG->dirroot
. '/course/lib.php');
2329 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2336 * Does an activity module use the question bank?
2338 * @param string $modname The name of the module (without mod_ prefix).
2339 * @return bool true if the module uses questions.
2341 function question_module_uses_questions($modname) {
2342 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
2346 $component = 'mod_'.$modname;
2347 if (component_callback_exists($component, 'question_pluginfile')) {
2348 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);
2356 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
2358 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
2359 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
2361 * @param string|null $oldidnumber a question idnumber, or can be null.
2362 * @param int $categoryid a question category id.
2363 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
2365 function core_question_find_next_unused_idnumber(?
string $oldidnumber, int $categoryid): ?
string {
2368 // The the old idnumber is not of the right form, bail now.
2369 if (!preg_match('~\d+$~', $oldidnumber, $matches)) {
2373 // Find all used idnumbers in one DB query.
2374 $usedidnumbers = $DB->get_records_select_menu('question', 'category = ? AND idnumber IS NOT NULL',
2375 [$categoryid], '', 'idnumber, 1');
2377 // Find the next unused idnumber.
2378 $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
2379 $stem = substr($oldidnumber, 0, -strlen($matches[0]));
2382 // If we have got to something9999, insert an extra digit before incrementing.
2383 if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2384 $numberbit = $matches[1] . '0' . $matches[2];
2387 $newidnumber = $stem . substr($numberbit, 1);
2388 } while (isset($usedidnumbers[$newidnumber]));
2390 return (string) $newidnumber;