Merge branch 'MDL-73502' of https://github.com/stronk7/moodle
[moodle.git] / lib / questionlib.php
blobec1853e231865d4fa2d0a6f1fe0b352a45593575
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
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.
28 * @package moodlecore
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 ///////////////////////////////////
44 /**
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);
50 /**
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);
57 /**
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);
64 /**
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);
79 if ($key === false) {
80 return $neworder;
82 // Work out the other index.
83 $otherkey = $key + $direction;
84 if (!isset($neworder[$otherkey])) {
85 return $neworder;
87 // Do the swap.
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
91 return $neworder;
94 /**
95 * Save a new question type order to the config_plugins table.
96 * @global object
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) {
101 global $DB;
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)) {
125 return true;
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)) {
133 return true;
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))) {
150 return true;
155 return false;
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
161 * hidden.
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) {
168 global $DB;
169 if (is_object($context)) {
170 $contextid = $context->id;
171 } else if (is_numeric($context)) {
172 $contextid = $context;
173 } else {
174 print_error('invalidcontextinhasanyquestions', 'question');
176 return $DB->record_exists_sql("SELECT *
177 FROM {question} q
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.
202 return false;
204 } else if ($matchgrades == 'nearest') {
205 // Work out nearest value
206 $best = false;
207 $bestmismatch = 2;
208 foreach ($gradeoptionsfull as $value => $option) {
209 $newmismatch = abs($grade - $value);
210 if ($newmismatch < $bestmismatch) {
211 $best = $value;
212 $bestmismatch = $newmismatch;
215 return $best;
217 } else {
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:
237 * - hidden questions
238 * - random questions
240 * @param int $categoryid The category ID.
241 * @deprecated since Moodle 4.0 MDL-71585
242 * @see qbank_managecategories\helper
243 * @todo Final deprecation on Moodle 4.4 MDL-72438
245 function question_remove_stale_questions_from_category($categoryid) {
246 debugging('Function question_remove_stale_questions_from_category()
247 has been deprecated and moved to qbank_managecategories plugin,
248 Please use qbank_managecategories\helper::question_remove_stale_questions_from_category() instead.',
249 DEBUG_DEVELOPER);
250 \qbank_managecategories\helper::question_remove_stale_questions_from_category($categoryid);
254 * Category is about to be deleted,
255 * 1/ All questions are deleted for this question category.
256 * 2/ Any questions that can't be deleted are moved to a new category
257 * NOTE: this function is called from lib/db/upgrade.php
259 * @param object|core_course_category $category course category object
261 function question_category_delete_safe($category) {
262 global $DB;
263 $criteria = array('category' => $category->id);
264 $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
265 $rescue = null; // See the code around the call to question_save_from_deletion.
267 // Deal with any questions in the category.
268 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
270 // Try to delete each question.
271 foreach ($questions as $question) {
272 question_delete_question($question->id);
275 // Check to see if there were any questions that were kept because
276 // they are still in use somehow, even though quizzes in courses
277 // in this category will already have been deleted. This could
278 // happen, for example, if questions are added to a course,
279 // and then that course is moved to another category (MDL-14802).
280 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
281 if (!empty($questionids)) {
282 $parentcontextid = SYSCONTEXTID;
283 $name = get_string('unknown', 'question');
284 if ($context !== false) {
285 $name = $context->get_context_name();
286 $parentcontext = $context->get_parent_context();
287 if ($parentcontext) {
288 $parentcontextid = $parentcontext->id;
291 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
295 // Now delete the category.
296 $DB->delete_records('question_categories', array('id' => $category->id));
300 * Tests whether any question in a category is used by any part of Moodle.
302 * @param integer $categoryid a question category id.
303 * @param boolean $recursive whether to check child categories too.
304 * @return boolean whether any question in this category is in use.
306 function question_category_in_use($categoryid, $recursive = false) {
307 global $DB;
309 //Look at each question in the category
310 if ($questions = $DB->get_records_menu('question',
311 array('category' => $categoryid), '', 'id, 1')) {
312 if (questions_in_use(array_keys($questions))) {
313 return true;
316 if (!$recursive) {
317 return false;
320 //Look under child categories recursively
321 if ($children = $DB->get_records('question_categories',
322 array('parent' => $categoryid), '', 'id, 1')) {
323 foreach ($children as $child) {
324 if (question_category_in_use($child->id, $recursive)) {
325 return true;
330 return false;
334 * Deletes question and all associated data from the database
336 * It will not delete a question if it is used somewhere.
338 * @param object $question The question being deleted
340 function question_delete_question($questionid) {
341 global $DB;
343 $question = $DB->get_record_sql('
344 SELECT q.*, ctx.id AS contextid
345 FROM {question} q
346 LEFT JOIN {question_categories} qc ON qc.id = q.category
347 LEFT JOIN {context} ctx ON ctx.id = qc.contextid
348 WHERE q.id = ?', array($questionid));
349 if (!$question) {
350 // In some situations, for example if this was a child of a
351 // Cloze question that was previously deleted, the question may already
352 // have gone. In this case, just do nothing.
353 return;
356 // Do not delete a question if it is used by an activity module
357 if (questions_in_use(array($questionid))) {
358 return;
361 // This sometimes happens in old sites with bad data.
362 if (!$question->contextid) {
363 debugging('Deleting question ' . $question->id . ' which is no longer linked to a context. ' .
364 'Assuming system context to avoid errors, but this may mean that some data like files, ' .
365 'tags, are not cleaned up.');
366 $question->contextid = context_system::instance()->id;
369 // Delete previews of the question.
370 $dm = new question_engine_data_mapper();
371 $dm->delete_previews($questionid);
373 // delete questiontype-specific data
374 question_bank::get_qtype($question->qtype, false)->delete_question(
375 $questionid, $question->contextid);
377 // Delete all tag instances.
378 core_tag_tag::remove_all_item_tags('core_question', 'question', $question->id);
380 // Delete the custom filed data for the question.
381 $customfieldhandler = qbank_customfields\customfield\question_handler::create();
382 $customfieldhandler->delete_instance($question->id);
384 // Now recursively delete all child questions
385 if ($children = $DB->get_records('question',
386 array('parent' => $questionid), '', 'id, qtype')) {
387 foreach ($children as $child) {
388 if ($child->id != $questionid) {
389 question_delete_question($child->id);
394 // Delete question comments.
395 $DB->delete_records('comments', ['itemid' => $questionid, 'component' => 'qbank_comment',
396 'commentarea' => 'question']);
397 // Finally delete the question record itself
398 $DB->delete_records('question', array('id' => $questionid));
399 question_bank::notify_question_edited($questionid);
401 // Log the deletion of this question.
402 $event = \core\event\question_deleted::create_from_question_instance($question);
403 $event->add_record_snapshot('question', $question);
404 $event->trigger();
408 * All question categories and their questions are deleted for this context id.
410 * @param int $contextid The contextid to delete question categories from
411 * @return array only returns an empty array for backwards compatibility.
413 function question_delete_context($contextid) {
414 global $DB;
416 $fields = 'id, parent, name, contextid';
417 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
418 //Sort categories following their tree (parent-child) relationships
419 //this will make the feedback more readable
420 $categories = sort_categories_by_tree($categories);
422 foreach ($categories as $category) {
423 question_category_delete_safe($category);
426 return [];
430 * All question categories and their questions are deleted for this course.
432 * @param stdClass $course an object representing the activity
433 * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
434 * @return bool always true.
436 function question_delete_course($course, $notused = false) {
437 $coursecontext = context_course::instance($course->id);
438 question_delete_context($coursecontext->id);
439 return true;
443 * Category is about to be deleted,
444 * 1/ All question categories and their questions are deleted for this course category.
445 * 2/ All questions are moved to new category
447 * @param stdClass|core_course_category $category course category object
448 * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
449 * category where content moved
450 * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
451 * @return boolean
453 function question_delete_course_category($category, $newcategory, $notused=false) {
454 global $DB;
456 $context = context_coursecat::instance($category->id);
457 if (empty($newcategory)) {
458 question_delete_context($context->id);
460 } else {
461 // Move question categories to the new context.
462 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
463 return false;
466 // Only move question categories if there is any question category at all!
467 if ($topcategory = question_get_top_category($context->id)) {
468 $newtopcategory = question_get_top_category($newcontext->id, true);
470 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
471 $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
472 // Now delete the top category.
473 $DB->delete_records('question_categories', array('id' => $topcategory->id));
477 return true;
481 * Enter description here...
483 * @param array $questionids of question ids
484 * @param object $newcontextid the context to create the saved category in.
485 * @param string $oldplace a textual description of the think being deleted,
486 * e.g. from get_context_name
487 * @param object $newcategory
488 * @return mixed false on
490 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
491 $newcategory = null) {
492 global $DB;
494 // Make a category in the parent context to move the questions to.
495 if (is_null($newcategory)) {
496 $newcategory = new stdClass();
497 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
498 $newcategory->contextid = $newcontextid;
499 // Max length of column name in question_categories is 255.
500 $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
501 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
502 $newcategory->sortorder = 999;
503 $newcategory->stamp = make_unique_id_code();
504 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
507 // Move any remaining questions to the 'saved' category.
508 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
509 return false;
511 return $newcategory;
515 * All question categories and their questions are deleted for this activity.
517 * @param object $cm the course module object representing the activity
518 * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
519 * @return boolean
521 function question_delete_activity($cm, $notused = false) {
522 global $DB;
524 $modcontext = context_module::instance($cm->id);
525 question_delete_context($modcontext->id);
526 return true;
530 * This function will handle moving all tag instances to a new context for a
531 * given list of questions.
533 * Questions can be tagged in up to two contexts:
534 * 1.) The context the question exists in.
535 * 2.) The course context (if the question context is a higher context.
536 * E.g. course category context or system context.
538 * This means a question that exists in a higher context (e.g. course cat or
539 * system context) may have multiple groups of tags in any number of child
540 * course contexts.
542 * Questions in the course category context can be move "down" a context level
543 * into one of their child course contexts or activity contexts which affects the
544 * availability of that question in other courses / activities.
546 * In this case it makes the questions no longer available in the other course or
547 * activity contexts so we need to make sure that the tag instances in those other
548 * contexts are removed.
550 * @param stdClass[] $questions The list of question being moved (must include
551 * the id and contextid)
552 * @param context $newcontext The Moodle context the questions are being moved to
554 function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
555 // If the questions are moving to a new course/activity context then we need to
556 // find any existing tag instances from any unavailable course contexts and
557 // delete them because they will no longer be applicable (we don't support
558 // tagging questions across courses).
559 $instancestodelete = [];
560 $instancesfornewcontext = [];
561 $newcontextparentids = $newcontext->get_parent_context_ids();
562 $questionids = array_map(function($question) {
563 return $question->id;
564 }, $questions);
565 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
567 foreach ($questions as $question) {
568 $tagobjects = $questionstagobjects[$question->id] ?? [];
570 foreach ($tagobjects as $tagobject) {
571 $tagid = $tagobject->taginstanceid;
572 $tagcontextid = $tagobject->taginstancecontextid;
573 $istaginnewcontext = $tagcontextid == $newcontext->id;
574 $istaginquestioncontext = $tagcontextid == $question->contextid;
576 if ($istaginnewcontext) {
577 // This tag instance is already in the correct context so we can
578 // ignore it.
579 continue;
582 if ($istaginquestioncontext) {
583 // This tag instance is in the question context so it needs to be
584 // updated.
585 $instancesfornewcontext[] = $tagid;
586 continue;
589 // These tag instances are in neither the new context nor the
590 // question context so we need to determine what to do based on
591 // the context they are in and the new question context.
592 $tagcontext = context::instance_by_id($tagcontextid);
593 $tagcoursecontext = $tagcontext->get_course_context(false);
594 // The tag is in a course context if get_course_context() returns
595 // itself.
596 $istaginstancecontextcourse = !empty($tagcoursecontext)
597 && $tagcontext->id == $tagcoursecontext->id;
599 if ($istaginstancecontextcourse) {
600 // If the tag instance is in a course context we need to add some
601 // special handling.
602 $tagcontextparentids = $tagcontext->get_parent_context_ids();
603 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
604 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
606 if ($isnewcontextaparent) {
607 // If the tag instance is a course context tag and the new
608 // context is still a parent context to the tag context then
609 // we can leave this tag where it is.
610 continue;
611 } else if ($isnewcontextachild) {
612 // If the new context is a child context (e.g. activity) of this
613 // tag instance then we should move all of this tag instance
614 // down into the activity context along with the question.
615 $instancesfornewcontext[] = $tagid;
616 } else {
617 // If the tag is in a course context that is no longer a parent
618 // or child of the new context then this tag instance should be
619 // removed.
620 $instancestodelete[] = $tagid;
622 } else {
623 // This is a catch all for any tag instances not in the question
624 // context or a course context. These tag instances should be
625 // updated to the new context id. This will clean up old invalid
626 // data.
627 $instancesfornewcontext[] = $tagid;
632 if (!empty($instancestodelete)) {
633 // Delete any course context tags that may no longer be valid.
634 core_tag_tag::delete_instances_by_id($instancestodelete);
637 if (!empty($instancesfornewcontext)) {
638 // Update the tag instances to the new context id.
639 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
644 * This function should be considered private to the question bank, it is called from
645 * question/editlib.php question/contextmoveq.php and a few similar places to to the
646 * work of actually moving questions and associated data. However, callers of this
647 * function also have to do other work, which is why you should not call this method
648 * directly from outside the questionbank.
650 * @param array $questionids of question ids.
651 * @param integer $newcategoryid the id of the category to move to.
653 function question_move_questions_to_category($questionids, $newcategoryid) {
654 global $DB;
656 $newcontextid = $DB->get_field('question_categories', 'contextid',
657 array('id' => $newcategoryid));
658 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
659 $questions = $DB->get_records_sql("
660 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
661 FROM {question} q
662 JOIN {question_categories} qc ON q.category = qc.id
663 WHERE q.id $questionidcondition", $params);
664 foreach ($questions as $question) {
665 if ($newcontextid != $question->contextid) {
666 question_bank::get_qtype($question->qtype)->move_files(
667 $question->id, $question->contextid, $newcontextid);
669 // Check whether there could be a clash of idnumbers in the new category.
670 if (((string) $question->idnumber !== '') &&
671 $DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $newcategoryid])) {
672 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
673 [$newcategoryid, $question->idnumber . '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
674 $unique = 1;
675 if (count($rec)) {
676 $rec = reset($rec);
677 $idnumber = $rec->idnumber;
678 if (strpos($idnumber, '_') !== false) {
679 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
682 // For the move process, add a numerical increment to the idnumber. This means that if a question is
683 // mistakenly moved then the idnumber will not be completely lost.
684 $q = new stdClass();
685 $q->id = $question->id;
686 $q->category = $newcategoryid;
687 $q->idnumber = $question->idnumber . '_' . $unique;
688 $DB->update_record('question', $q);
691 // Log this question move.
692 $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
693 ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategoryid]);
694 $event->trigger();
697 // Move the questions themselves.
698 $DB->set_field_select('question', 'category', $newcategoryid,
699 "id $questionidcondition", $params);
701 // Move any subquestions belonging to them.
702 $DB->set_field_select('question', 'category', $newcategoryid,
703 "parent $questionidcondition", $params);
705 $newcontext = context::instance_by_id($newcontextid);
706 question_move_question_tags_to_new_context($questions, $newcontext);
708 // TODO Deal with datasets.
710 // Purge these questions from the cache.
711 foreach ($questions as $question) {
712 question_bank::notify_question_edited($question->id);
715 return true;
719 * This function helps move a question cateogry to a new context by moving all
720 * the files belonging to all the questions to the new context.
721 * Also moves subcategories.
722 * @param integer $categoryid the id of the category being moved.
723 * @param integer $oldcontextid the old context id.
724 * @param integer $newcontextid the new context id.
726 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
727 global $DB;
729 $questions = [];
730 $questionids = $DB->get_records_menu('question',
731 array('category' => $categoryid), '', 'id,qtype');
732 foreach ($questionids as $questionid => $qtype) {
733 question_bank::get_qtype($qtype)->move_files(
734 $questionid, $oldcontextid, $newcontextid);
735 // Purge this question from the cache.
736 question_bank::notify_question_edited($questionid);
738 $questions[] = (object) [
739 'id' => $questionid,
740 'contextid' => $oldcontextid
744 $newcontext = context::instance_by_id($newcontextid);
745 question_move_question_tags_to_new_context($questions, $newcontext);
747 $subcatids = $DB->get_records_menu('question_categories',
748 array('parent' => $categoryid), '', 'id,1');
749 foreach ($subcatids as $subcatid => $notused) {
750 $DB->set_field('question_categories', 'contextid', $newcontextid,
751 array('id' => $subcatid));
752 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
757 * Generate the URL for starting a new preview of a given question with the given options.
758 * @param integer $questionid the question to preview.
759 * @param string $preferredbehaviour the behaviour to use for the preview.
760 * @param float $maxmark the maximum to mark the question out of.
761 * @param question_display_options $displayoptions the display options to use.
762 * @param int $variant the variant of the question to preview. If null, one will
763 * be picked randomly.
764 * @param object $context context to run the preview in (affects things like
765 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
766 * @return moodle_url the URL.
767 * @deprecated since Moodle 4.0
768 * @see qbank_previewquestion\helper::question_preview_url()
769 * @todo Final deprecation on Moodle 4.4 MDL-72438
771 function question_preview_url($questionid, $preferredbehaviour = null,
772 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
773 debugging('Function question_preview_url() has been deprecated and moved to qbank_previewquestion plugin,
774 Please use qbank_previewquestion\helper::question_preview_url() instead.', DEBUG_DEVELOPER);
776 return \qbank_previewquestion\helper::question_preview_url($questionid, $preferredbehaviour = null,
777 $maxmark = null, $displayoptions = null, $variant = null, $context = null);
781 * @return array that can be passed as $params to the {@link popup_action} constructor.
782 * @deprecated since Moodle 4.0
783 * @see qbank_previewquestion\helper::question_preview_popup_params()
784 * @todo Final deprecation on Moodle 4.4 MDL-72438
786 function question_preview_popup_params() {
787 debugging('Function question_preview_popup_params() has been deprecated and moved to qbank_previewquestion plugin,
788 Please use qbank_previewquestion\helper::question_preview_popup_params() instead.', DEBUG_DEVELOPER);
790 return \qbank_previewquestion\helper::question_preview_popup_params();
794 * Given a list of ids, load the basic information about a set of questions from
795 * the questions table. The $join and $extrafields arguments can be used together
796 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
797 * read the code below to see how the SQL is assembled. Throws exceptions on error.
799 * @param array $questionids array of question ids to load. If null, then all
800 * questions matched by $join will be loaded.
801 * @param string $extrafields extra SQL code to be added to the query.
802 * @param string $join extra SQL code to be added to the query.
803 * @param array $extraparams values for any placeholders in $join.
804 * You must use named placeholders.
805 * @param string $orderby what to order the results by. Optional, default is unspecified order.
807 * @return array partially complete question objects. You need to call get_question_options
808 * on them before they can be properly used.
810 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
811 $extraparams = array(), $orderby = '') {
812 global $DB;
814 if ($questionids === null) {
815 $where = '';
816 $params = array();
817 } else {
818 if (empty($questionids)) {
819 return array();
822 list($questionidcondition, $params) = $DB->get_in_or_equal(
823 $questionids, SQL_PARAMS_NAMED, 'qid0000');
824 $where = 'WHERE q.id ' . $questionidcondition;
827 if ($join) {
828 $join = 'JOIN ' . $join;
831 if ($extrafields) {
832 $extrafields = ', ' . $extrafields;
835 if ($orderby) {
836 $orderby = 'ORDER BY ' . $orderby;
839 $sql = "SELECT q.*, qc.contextid{$extrafields}
840 FROM {question} q
841 JOIN {question_categories} qc ON q.category = qc.id
842 {$join}
843 {$where}
844 {$orderby}";
846 // Load the questions.
847 $questions = $DB->get_records_sql($sql, $extraparams + $params);
848 foreach ($questions as $question) {
849 $question->_partiallyloaded = true;
852 return $questions;
856 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
857 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
858 * read the code below to see how the SQL is assembled. Throws exceptions on error.
860 * @param array $questionids array of question ids.
861 * @param string $extrafields extra SQL code to be added to the query.
862 * @param string $join extra SQL code to be added to the query.
863 * @param array $extraparams values for any placeholders in $join.
864 * You are strongly recommended to use named placeholder.
866 * @return array question objects.
868 function question_load_questions($questionids, $extrafields = '', $join = '') {
869 $questions = question_preload_questions($questionids, $extrafields, $join);
871 // Load the question type specific information
872 if (!get_question_options($questions)) {
873 return 'Could not load the question options';
876 return $questions;
880 * Private function to factor common code out of get_question_options().
882 * @param object $question the question to tidy.
883 * @param stdClass $category The question_categories record for the given $question.
884 * @param stdClass[]|null $tagobjects The tags for the given $question.
885 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
887 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
888 // Load question-type specific fields.
889 if (!question_bank::is_qtype_installed($question->qtype)) {
890 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
891 'qtype_missingtype')) . $question->questiontext;
893 question_bank::get_qtype($question->qtype)->get_question_options($question);
895 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
896 $question->defaultmark += 0;
897 $question->penalty += 0;
899 if (isset($question->_partiallyloaded)) {
900 unset($question->_partiallyloaded);
903 $question->categoryobject = $category;
905 if (!is_null($tagobjects)) {
906 $categorycontext = context::instance_by_id($category->contextid);
907 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
908 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
909 $question->coursetags = $sortedtagobjects->coursetags;
910 $question->tagobjects = $sortedtagobjects->tagobjects;
911 $question->tags = $sortedtagobjects->tags;
916 * Updates the question objects with question type specific
917 * information by calling {@link get_question_options()}
919 * Can be called either with an array of question objects or with a single
920 * question object.
922 * @param mixed $questions Either an array of question objects to be updated
923 * or just a single question object
924 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
925 * @param stdClass[] $filtercourses The courses to filter the course tags by.
926 * @return bool Indicates success or failure.
928 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
929 global $DB;
931 $questionlist = is_array($questions) ? $questions : [$questions];
932 $categoryids = [];
933 $questionids = [];
935 if (empty($questionlist)) {
936 return true;
939 foreach ($questionlist as $question) {
940 $questionids[] = $question->id;
942 if (!in_array($question->category, $categoryids)) {
943 $categoryids[] = $question->category;
947 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
949 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
950 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
951 } else {
952 $tagobjectsbyquestion = null;
955 foreach ($questionlist as $question) {
956 if (is_null($tagobjectsbyquestion)) {
957 $tagobjects = null;
958 } else {
959 $tagobjects = $tagobjectsbyquestion[$question->id];
962 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
965 return true;
969 * Sort question tags by course or normal tags.
971 * This function also search tag instances that may have a context id that don't match either a course or
972 * question context and fix the data setting the correct context id.
974 * @param stdClass[] $tagobjects The tags for the given $question.
975 * @param stdClass $categorycontext The question categories context.
976 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
977 * @return stdClass $sortedtagobjects Sorted tag objects.
979 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
981 // Questions can have two sets of tag instances. One set at the
982 // course context level and another at the context the question
983 // belongs to (e.g. course category, system etc).
984 $sortedtagobjects = new stdClass();
985 $sortedtagobjects->coursetagobjects = [];
986 $sortedtagobjects->coursetags = [];
987 $sortedtagobjects->tagobjects = [];
988 $sortedtagobjects->tags = [];
989 $taginstanceidstonormalise = [];
990 $filtercoursecontextids = [];
991 $hasfiltercourses = !empty($filtercourses);
993 if ($hasfiltercourses) {
994 // If we're being asked to filter the course tags by a set of courses
995 // then get the context ids to filter below.
996 $filtercoursecontextids = array_map(function($course) {
997 $coursecontext = context_course::instance($course->id);
998 return $coursecontext->id;
999 }, $filtercourses);
1002 foreach ($tagobjects as $tagobject) {
1003 $tagcontextid = $tagobject->taginstancecontextid;
1004 $tagcontext = context::instance_by_id($tagcontextid);
1005 $tagcoursecontext = $tagcontext->get_course_context(false);
1006 // This is a course tag if the tag context is a course context which
1007 // doesn't match the question's context. Any tag in the question context
1008 // is not considered a course tag, it belongs to the question.
1009 $iscoursetag = $tagcoursecontext
1010 && $tagcontext->id == $tagcoursecontext->id
1011 && $tagcontext->id != $categorycontext->id;
1013 if ($iscoursetag) {
1014 // Any tag instance in a course context level is considered a course tag.
1015 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1016 // Add the tag to the list of course tags if we aren't being
1017 // asked to filter or if this tag is in the list of courses
1018 // we're being asked to filter by.
1019 $sortedtagobjects->coursetagobjects[] = $tagobject;
1020 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1022 } else {
1023 // All non course context level tag instances or tags in the question
1024 // context belong to the context that the question was created in.
1025 $sortedtagobjects->tagobjects[] = $tagobject;
1026 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1028 // Due to legacy tag implementations that don't force the recording
1029 // of a context id, some tag instances may have context ids that don't
1030 // match either a course context or the question context. In this case
1031 // we should take the opportunity to fix up the data and set the correct
1032 // context id.
1033 if ($tagcontext->id != $categorycontext->id) {
1034 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1035 // Update the object properties to reflect the DB update that will
1036 // happen below.
1037 $tagobject->taginstancecontextid = $categorycontext->id;
1042 if (!empty($taginstanceidstonormalise)) {
1043 // If we found any tag instances with incorrect context id data then we can
1044 // correct those values now by setting them to the question context id.
1045 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1048 return $sortedtagobjects;
1052 * Print the icon for the question type
1054 * @param object $question The question object for which the icon is required.
1055 * Only $question->qtype is used.
1056 * @return string the HTML for the img tag.
1058 function print_question_icon($question) {
1059 global $PAGE;
1060 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
1064 * Creates a stamp that uniquely identifies this version of the question
1066 * In future we want this to use a hash of the question data to guarantee that
1067 * identical versions have the same version stamp.
1069 * @param object $question
1070 * @return string A unique version stamp
1072 function question_hash($question) {
1073 return make_unique_id_code();
1076 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1079 * returns the categories with their names ordered following parent-child relationships
1080 * finally it tries to return pending categories (those being orphaned, whose parent is
1081 * incorrect) to avoid missing any category from original array.
1083 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1084 global $DB;
1086 $children = array();
1087 $keys = array_keys($categories);
1089 foreach ($keys as $key) {
1090 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1091 $children[$key] = $categories[$key];
1092 $categories[$key]->processed = true;
1093 $children = $children + sort_categories_by_tree(
1094 $categories, $children[$key]->id, $level+1);
1097 //If level = 1, we have finished, try to look for non processed categories
1098 // (bad parent) and sort them too
1099 if ($level == 1) {
1100 foreach ($keys as $key) {
1101 // If not processed and it's a good candidate to start (because its
1102 // parent doesn't exist in the course)
1103 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1104 array('contextid' => $categories[$key]->contextid,
1105 'id' => $categories[$key]->parent))) {
1106 $children[$key] = $categories[$key];
1107 $categories[$key]->processed = true;
1108 $children = $children + sort_categories_by_tree(
1109 $categories, $children[$key]->id, $level + 1);
1113 return $children;
1117 * Private method, only for the use of add_indented_names().
1119 * Recursively adds an indentedname field to each category, starting with the category
1120 * with id $id, and dealing with that category and all its children, and
1121 * return a new array, with those categories in the right order.
1123 * @param array $categories an array of categories which has had childids
1124 * fields added by flatten_category_tree(). Passed by reference for
1125 * performance only. It is not modfied.
1126 * @param int $id the category to start the indenting process from.
1127 * @param int $depth the indent depth. Used in recursive calls.
1128 * @return array a new array of categories, in the right order for the tree.
1129 * @deprecated since Moodle 4.0 MDL-71585
1130 * @see qbank_managecategories\helper
1131 * @todo Final deprecation on Moodle 4.4 MDL-72438
1133 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1134 debugging('Function flatten_category_tree() has been deprecated and moved to qbank_managecategories plugin,
1135 Please use qbank_managecategories\helper::flatten_category_tree() instead.', DEBUG_DEVELOPER);
1136 return \qbank_managecategories\helper::flatten_category_tree($categories, $id, $depth, $nochildrenof);
1140 * Format categories into an indented list reflecting the tree structure.
1142 * @param array $categories An array of category objects, for example from the.
1143 * @return array The formatted list of categories.
1144 * @deprecated since Moodle 4.0 MDL-71585
1145 * @see qbank_managecategories\helper
1146 * @todo Final deprecation on Moodle 4.4 MDL-72438
1148 function add_indented_names($categories, $nochildrenof = -1) {
1149 debugging('Function add_indented_names() has been deprecated and moved to qbank_managecategories plugin,
1150 Please use qbank_managecategories\helper::add_indented_names() instead.', DEBUG_DEVELOPER);
1151 return \qbank_managecategories\helper::add_indented_names($categories, $nochildrenof);
1155 * Output a select menu of question categories.
1157 * Categories from this course and (optionally) published categories from other courses
1158 * are included. Optionally, only categories the current user may edit can be included.
1160 * @param integer $courseid the id of the course to get the categories for.
1161 * @param integer $published if true, include publised categories from other courses.
1162 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1163 * @param integer $selected optionally, the id of a category to be selected by
1164 * default in the dropdown.
1165 * @deprecated since Moodle 4.0 MDL-71585
1166 * @see qbank_managecategories\helper
1167 * @todo Final deprecation on Moodle 4.4 MDL-72438
1169 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1170 $selected = "", $nochildrenof = -1) {
1171 debugging('Function question_category_select_menu() has been deprecated and moved to qbank_managecategories plugin,
1172 Please use qbank_managecategories\helper::question_category_select_menu() instead.', DEBUG_DEVELOPER);
1173 \qbank_managecategories\helper::question_category_select_menu($contexts, $top, $currentcat, $selected, $nochildrenof);
1177 * @param integer $contextid a context id.
1178 * @return object the default question category for that context, or false if none.
1180 function question_get_default_category($contextid) {
1181 global $DB;
1182 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1183 array($contextid), 'id', '*', 0, 1);
1184 if (!empty($category)) {
1185 return reset($category);
1186 } else {
1187 return false;
1192 * Gets the top category in the given context.
1193 * This function can optionally create the top category if it doesn't exist.
1195 * @param int $contextid A context id.
1196 * @param bool $create Whether create a top category if it doesn't exist.
1197 * @return bool|stdClass The top question category for that context, or false if none.
1199 function question_get_top_category($contextid, $create = false) {
1200 global $DB;
1201 $category = $DB->get_record('question_categories',
1202 array('contextid' => $contextid, 'parent' => 0));
1204 if (!$category && $create) {
1205 // We need to make one.
1206 $category = new stdClass();
1207 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1208 $category->info = '';
1209 $category->contextid = $contextid;
1210 $category->parent = 0;
1211 $category->sortorder = 0;
1212 $category->stamp = make_unique_id_code();
1213 $category->id = $DB->insert_record('question_categories', $category);
1216 return $category;
1220 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1222 * @param array $contextids List of context ids
1223 * @return array
1225 function question_get_top_categories_for_contexts($contextids) {
1226 global $DB;
1228 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1229 list($insql, $params) = $DB->get_in_or_equal($contextids);
1230 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1231 $topcategories = $DB->get_fieldset_sql($sql, $params);
1233 return $topcategories;
1237 * Gets the default category in the most specific context.
1238 * If no categories exist yet then default ones are created in all contexts.
1240 * @param array $contexts The context objects for this context and all parent contexts.
1241 * @return object The default category - the category in the course context
1243 function question_make_default_categories($contexts) {
1244 global $DB;
1245 static $preferredlevels = array(
1246 CONTEXT_COURSE => 4,
1247 CONTEXT_MODULE => 3,
1248 CONTEXT_COURSECAT => 2,
1249 CONTEXT_SYSTEM => 1,
1252 $toreturn = null;
1253 $preferredness = 0;
1254 // If it already exists, just return it.
1255 foreach ($contexts as $key => $context) {
1256 $topcategory = question_get_top_category($context->id, true);
1257 if (!$exists = $DB->record_exists("question_categories",
1258 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1259 // Otherwise, we need to make one
1260 $category = new stdClass();
1261 $contextname = $context->get_context_name(false, true);
1262 // Max length of name field is 255.
1263 $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1264 $category->info = get_string('defaultinfofor', 'question', $contextname);
1265 $category->contextid = $context->id;
1266 $category->parent = $topcategory->id;
1267 // By default, all categories get this number, and are sorted alphabetically.
1268 $category->sortorder = 999;
1269 $category->stamp = make_unique_id_code();
1270 $category->id = $DB->insert_record('question_categories', $category);
1271 } else {
1272 $category = question_get_default_category($context->id);
1274 $thispreferredness = $preferredlevels[$context->contextlevel];
1275 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1276 $thispreferredness += 10;
1278 if ($thispreferredness > $preferredness) {
1279 $toreturn = $category;
1280 $preferredness = $thispreferredness;
1284 if (!is_null($toreturn)) {
1285 $toreturn = clone($toreturn);
1287 return $toreturn;
1291 * Get all the category objects, including a count of the number of questions in that category,
1292 * for all the categories in the lists $contexts.
1294 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1295 * @param string $sortorder used as the ORDER BY clause in the select statement.
1296 * @param bool $top Whether to return the top categories or not.
1297 * @return array of category objects.
1298 * @deprecated since Moodle 4.0 MDL-71585
1299 * @see qbank_managecategories\helper
1300 * @todo Final deprecation on Moodle 4.4 MDL-72438
1302 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1303 debugging('Function get_categories_for_contexts() has been deprecated and moved to qbank_managecategories plugin,
1304 Please use qbank_managecategories\helper::get_categories_for_contexts() instead.', DEBUG_DEVELOPER);
1305 return \qbank_managecategories\helper::get_categories_for_contexts($contexts, $sortorder, $top);
1309 * Output an array of question categories.
1311 * @param array $contexts The list of contexts.
1312 * @param bool $top Whether to return the top categories or not.
1313 * @param int $currentcat
1314 * @param bool $popupform
1315 * @param int $nochildrenof
1316 * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
1317 * @return array
1318 * @deprecated since Moodle 4.0 MDL-71585
1319 * @see qbank_managecategories\helper
1320 * @todo Final deprecation on Moodle 4.4 MDL-72438
1322 function question_category_options($contexts, $top = false, $currentcat = 0,
1323 $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
1324 debugging('Function question_category_options() has been deprecated and moved to qbank_managecategories plugin,
1325 Please use qbank_managecategories\helper::question_category_options() instead.', DEBUG_DEVELOPER);
1326 return \qbank_managecategories\helper::question_category_options($contexts, $top, $currentcat,
1327 $popupform, $nochildrenof, $escapecontextnames);
1331 * @deprecated since Moodle 4.0 MDL-71585
1332 * @see qbank_managecategories\helper
1333 * @todo Final deprecation on Moodle 4.4 MDL-72438
1335 function question_add_context_in_key($categories) {
1336 debugging('Function question_add_context_in_key() has been deprecated and moved to qbank_managecategories plugin,
1337 Please use qbank_managecategories\helper::question_add_context_in_key() instead.', DEBUG_DEVELOPER);
1338 return \qbank_managecategories\helper::question_add_context_in_key($categories);
1342 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1344 * @param array $categories An array of question categories.
1345 * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
1346 * @return array The same question category list given to the function, with the top category names being translated.
1347 * @deprecated since Moodle 4.0 MDL-71585
1348 * @see qbank_managecategories\helper
1349 * @todo Final deprecation on Moodle 4.4 MDL-72438
1351 function question_fix_top_names($categories, $escape = true) {
1352 debugging('Function question_fix_top_names() has been deprecated and moved to qbank_managecategories plugin,
1353 Please use qbank_managecategories\helper::question_fix_top_names() instead.', DEBUG_DEVELOPER);
1354 return \qbank_managecategories\helper::question_fix_top_names($categories, $escape);
1358 * @return array of question category ids of the category and all subcategories.
1360 function question_categorylist($categoryid) {
1361 global $DB;
1363 // final list of category IDs
1364 $categorylist = array();
1366 // a list of category IDs to check for any sub-categories
1367 $subcategories = array($categoryid);
1369 while ($subcategories) {
1370 foreach ($subcategories as $subcategory) {
1371 // if anything from the temporary list was added already, then we have a loop
1372 if (isset($categorylist[$subcategory])) {
1373 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1375 $categorylist[$subcategory] = $subcategory;
1378 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1380 $subcategories = $DB->get_records_select_menu('question_categories',
1381 "parent $in", $params, NULL, 'id,id AS id2');
1384 return $categorylist;
1388 * Get all parent categories of a given question category in decending order.
1389 * @param int $categoryid for which you want to find the parents.
1390 * @return array of question category ids of all parents categories.
1392 function question_categorylist_parents(int $categoryid) {
1393 global $DB;
1394 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1395 if (!$parent) {
1396 return [];
1398 $categorylist = [$parent];
1399 $currentid = $parent;
1400 while ($currentid) {
1401 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1402 if ($currentid) {
1403 $categorylist[] = $currentid;
1406 // Present the list in decending order (the top category at the top).
1407 $categorylist = array_reverse($categorylist);
1408 return $categorylist;
1411 //===========================
1412 // Import/Export Functions
1413 //===========================
1416 * Get list of available import or export formats
1417 * @param string $type 'import' if import list, otherwise export list assumed
1418 * @return array sorted list of import/export formats available
1420 function get_import_export_formats($type) {
1421 global $CFG;
1422 require_once($CFG->dirroot . '/question/format.php');
1424 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1426 $fileformatname = array();
1427 foreach ($formatclasses as $component => $formatclass) {
1429 $format = new $formatclass();
1430 if ($type == 'import') {
1431 $provided = $format->provide_import();
1432 } else {
1433 $provided = $format->provide_export();
1436 if ($provided) {
1437 list($notused, $fileformat) = explode('_', $component, 2);
1438 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1442 core_collator::asort($fileformatnames);
1443 return $fileformatnames;
1448 * Create a reasonable default file name for exporting questions from a particular
1449 * category.
1450 * @param object $course the course the questions are in.
1451 * @param object $category the question category.
1452 * @return string the filename.
1454 function question_default_export_filename($course, $category) {
1455 // We build a string that is an appropriate name (questions) from the lang pack,
1456 // then the corse shortname, then the question category name, then a timestamp.
1458 $base = clean_filename(get_string('exportfilename', 'question'));
1460 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1461 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1463 $shortname = clean_filename($course->shortname);
1464 if ($shortname == '' || $shortname == '_' ) {
1465 $shortname = $course->id;
1468 $categoryname = clean_filename(format_string($category->name));
1470 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1472 return $export_name;
1476 * Converts contextlevels to strings and back to help with reading/writing contexts
1477 * to/from import/export files.
1479 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1482 class context_to_string_translator{
1484 * @var array used to translate between contextids and strings for this context.
1486 protected $contexttostringarray = array();
1488 public function __construct($contexts) {
1489 $this->generate_context_to_string_array($contexts);
1492 public function context_to_string($contextid) {
1493 return $this->contexttostringarray[$contextid];
1496 public function string_to_context($contextname) {
1497 $contextid = array_search($contextname, $this->contexttostringarray);
1498 return $contextid;
1501 protected function generate_context_to_string_array($contexts) {
1502 if (!$this->contexttostringarray) {
1503 $catno = 1;
1504 foreach ($contexts as $context) {
1505 switch ($context->contextlevel) {
1506 case CONTEXT_MODULE :
1507 $contextstring = 'module';
1508 break;
1509 case CONTEXT_COURSE :
1510 $contextstring = 'course';
1511 break;
1512 case CONTEXT_COURSECAT :
1513 $contextstring = "cat$catno";
1514 $catno++;
1515 break;
1516 case CONTEXT_SYSTEM :
1517 $contextstring = 'system';
1518 break;
1520 $this->contexttostringarray[$context->id] = $contextstring;
1528 * Check capability on category
1530 * @param int|stdClass|question_definition $questionorid object or id.
1531 * If an object is passed, it should include ->contextid and ->createdby.
1532 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1533 * @param int $notused no longer used.
1534 * @return bool this user has the capability $cap for this question $question?
1535 * @throws coding_exception
1537 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1538 global $USER, $DB;
1540 if (is_numeric($questionorid)) {
1541 $questionid = (int)$questionorid;
1542 } else if (is_object($questionorid)) {
1543 // All we really need in this function is the contextid and author of the question.
1544 // We won't bother fetching other details of the question if these 2 fields are provided.
1545 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1546 $question = $questionorid;
1547 } else if (!empty($questionorid->id)) {
1548 $questionid = $questionorid->id;
1552 // At this point, either $question or $questionid is expected to be set.
1553 if (isset($questionid)) {
1554 try {
1555 $question = question_bank::load_question_data($questionid);
1556 } catch (Exception $e) {
1557 // Let's log the exception for future debugging,
1558 // but not during Behat, or we can't test these cases.
1559 if (!defined('BEHAT_SITE_RUNNING')) {
1560 debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1563 // Well, at least we tried. Seems that we really have to read from DB.
1564 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1565 FROM {question} q
1566 JOIN {question_categories} qc ON q.category = qc.id
1567 WHERE q.id = :id', ['id' => $questionid]);
1571 if (!isset($question)) {
1572 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1575 $context = context::instance_by_id($question->contextid);
1577 // These are existing questions capabilities that are set per category.
1578 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1579 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1581 if (!isset($capabilitieswithallandmine[$cap])) {
1582 return has_capability('moodle/question:' . $cap, $context);
1583 } else {
1584 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1585 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1590 * Require capability on question.
1592 function question_require_capability_on($question, $cap) {
1593 if (!question_has_capability_on($question, $cap)) {
1594 print_error('nopermissions', '', '', $cap);
1596 return true;
1600 * @param object $context a context
1601 * @return string A URL for editing questions in this context.
1603 function question_edit_url($context) {
1604 global $CFG, $SITE;
1605 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1606 return false;
1608 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1609 $defaultcategory = question_get_default_category($context->id);
1610 if ($defaultcategory) {
1611 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1613 switch ($context->contextlevel) {
1614 case CONTEXT_SYSTEM:
1615 return $baseurl . 'courseid=' . $SITE->id;
1616 case CONTEXT_COURSECAT:
1617 // This is nasty, becuase we can only edit questions in a course
1618 // context at the moment, so for now we just return false.
1619 return false;
1620 case CONTEXT_COURSE:
1621 return $baseurl . 'courseid=' . $context->instanceid;
1622 case CONTEXT_MODULE:
1623 return $baseurl . 'cmid=' . $context->instanceid;
1629 * Adds question bank setting links to the given navigation node if caps are met
1630 * and loads the navigation from the plugins.
1631 * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1632 * this method will help to autoload those nodes in the question bank navigation.
1634 * @param navigation_node $navigationnode The navigation node to add the question branch to
1635 * @param object $context
1636 * @param string $baseurl the url of the base where the api is implemented from
1637 * @return navigation_node Returns the question branch that was added
1639 function question_extend_settings_navigation(navigation_node $navigationnode, $context, $baseurl = '/question/edit.php') {
1640 global $PAGE;
1642 if ($context->contextlevel == CONTEXT_COURSE) {
1643 $params = ['courseid' => $context->instanceid];
1644 } else if ($context->contextlevel == CONTEXT_MODULE) {
1645 $params = ['cmid' => $context->instanceid];
1646 } else {
1647 return;
1650 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1651 $params['cat'] = $cat;
1654 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1655 new moodle_url($baseurl, $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1657 $corenavigations = [
1658 'questions' => [
1659 'title' => get_string('questions', 'question'),
1660 'url' => new moodle_url($baseurl)
1662 'categories' => [],
1663 'import' => [],
1664 'export' => []
1667 $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1668 foreach ($plugins as $componentname => $plugin) {
1669 $pluginentrypoint = new $plugin();
1670 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1671 // Don't need the plugins without navigation node.
1672 if ($pluginentrypointobject === null) {
1673 unset($plugins[$componentname]);
1674 continue;
1676 foreach ($corenavigations as $key => $corenavigation) {
1677 if ($pluginentrypointobject->get_navigation_key() === $key) {
1678 unset($plugins[$componentname]);
1679 if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1680 unset($corenavigations[$key]);
1681 break;
1683 $corenavigations[$key] = [
1684 'title' => $pluginentrypointobject->get_navigation_title(),
1685 'url' => $pluginentrypointobject->get_navigation_url()
1691 // Mitigate the risk of regression.
1692 foreach ($corenavigations as $node => $corenavigation) {
1693 if (empty($corenavigation)) {
1694 unset($corenavigations[$node]);
1698 // Community/additional plugins have navigation node.
1699 $pluginnavigations = [];
1700 foreach ($plugins as $componentname => $plugin) {
1701 $pluginentrypoint = new $plugin();
1702 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1703 // Don't need the plugins without navigation node.
1704 if ($pluginentrypointobject === null || !\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1705 unset($plugins[$componentname]);
1706 continue;
1708 $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1709 'title' => $pluginentrypointobject->get_navigation_title(),
1710 'url' => $pluginentrypointobject->get_navigation_url(),
1711 'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1715 $contexts = new question_edit_contexts($context);
1716 foreach ($corenavigations as $key => $corenavigation) {
1717 if ($contexts->have_one_edit_tab_cap($key)) {
1718 $questionnode->add($corenavigation['title'], new moodle_url(
1719 $corenavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1723 foreach ($pluginnavigations as $key => $pluginnavigation) {
1724 if (is_array($pluginnavigation['capabilities'])) {
1725 if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1726 continue;
1729 $questionnode->add($pluginnavigation['title'], new moodle_url(
1730 $pluginnavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1733 return $questionnode;
1737 * @return array all the capabilities that relate to accessing particular questions.
1739 function question_get_question_capabilities() {
1740 return array(
1741 'moodle/question:add',
1742 'moodle/question:editmine',
1743 'moodle/question:editall',
1744 'moodle/question:viewmine',
1745 'moodle/question:viewall',
1746 'moodle/question:usemine',
1747 'moodle/question:useall',
1748 'moodle/question:movemine',
1749 'moodle/question:moveall',
1750 'moodle/question:tagmine',
1751 'moodle/question:tagall',
1752 'moodle/question:commentmine',
1753 'moodle/question:commentall',
1758 * @return array all the question bank capabilities.
1760 function question_get_all_capabilities() {
1761 $caps = question_get_question_capabilities();
1762 $caps[] = 'moodle/question:managecategory';
1763 $caps[] = 'moodle/question:flag';
1764 return $caps;
1769 * Tracks all the contexts related to the one where we are currently editing
1770 * questions, and provides helper methods to check permissions.
1772 * @copyright 2007 Jamie Pratt me@jamiep.org
1773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1775 class question_edit_contexts {
1777 public static $caps = array(
1778 'editq' => array('moodle/question:add',
1779 'moodle/question:editmine',
1780 'moodle/question:editall',
1781 'moodle/question:viewmine',
1782 'moodle/question:viewall',
1783 'moodle/question:usemine',
1784 'moodle/question:useall',
1785 'moodle/question:movemine',
1786 'moodle/question:moveall'),
1787 'questions'=>array('moodle/question:add',
1788 'moodle/question:editmine',
1789 'moodle/question:editall',
1790 'moodle/question:viewmine',
1791 'moodle/question:viewall',
1792 'moodle/question:movemine',
1793 'moodle/question:moveall'),
1794 'categories'=>array('moodle/question:managecategory'),
1795 'import'=>array('moodle/question:add'),
1796 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1798 protected $allcontexts;
1801 * Constructor
1802 * @param context the current context.
1804 public function __construct(context $thiscontext) {
1805 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1809 * @return context[] all parent contexts
1811 public function all() {
1812 return $this->allcontexts;
1816 * @return context lowest context which must be either the module or course context
1818 public function lowest() {
1819 return $this->allcontexts[0];
1823 * @param string $cap capability
1824 * @return context[] parent contexts having capability, zero based index
1826 public function having_cap($cap) {
1827 $contextswithcap = array();
1828 foreach ($this->allcontexts as $context) {
1829 if (has_capability($cap, $context)) {
1830 $contextswithcap[] = $context;
1833 return $contextswithcap;
1837 * @param array $caps capabilities
1838 * @return context[] parent contexts having at least one of $caps, zero based index
1840 public function having_one_cap($caps) {
1841 $contextswithacap = array();
1842 foreach ($this->allcontexts as $context) {
1843 foreach ($caps as $cap) {
1844 if (has_capability($cap, $context)) {
1845 $contextswithacap[] = $context;
1846 break; //done with caps loop
1850 return $contextswithacap;
1854 * @param string $tabname edit tab name
1855 * @return context[] parent contexts having at least one of $caps, zero based index
1857 public function having_one_edit_tab_cap($tabname) {
1858 return $this->having_one_cap(self::$caps[$tabname]);
1862 * @return context[] those contexts where a user can add a question and then use it.
1864 public function having_add_and_use() {
1865 $contextswithcap = array();
1866 foreach ($this->allcontexts as $context) {
1867 if (!has_capability('moodle/question:add', $context)) {
1868 continue;
1870 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1871 continue;
1873 $contextswithcap[] = $context;
1875 return $contextswithcap;
1879 * Has at least one parent context got the cap $cap?
1881 * @param string $cap capability
1882 * @return boolean
1884 public function have_cap($cap) {
1885 return (count($this->having_cap($cap)));
1889 * Has at least one parent context got one of the caps $caps?
1891 * @param array $caps capability
1892 * @return boolean
1894 public function have_one_cap($caps) {
1895 foreach ($caps as $cap) {
1896 if ($this->have_cap($cap)) {
1897 return true;
1900 return false;
1904 * Has at least one parent context got one of the caps for actions on $tabname
1906 * @param string $tabname edit tab name
1907 * @return boolean
1909 public function have_one_edit_tab_cap($tabname) {
1910 return $this->have_one_cap(self::$caps[$tabname]);
1914 * Throw error if at least one parent context hasn't got the cap $cap
1916 * @param string $cap capability
1918 public function require_cap($cap) {
1919 if (!$this->have_cap($cap)) {
1920 print_error('nopermissions', '', '', $cap);
1925 * Throw error if at least one parent context hasn't got one of the caps $caps
1927 * @param array $caps capabilities
1929 public function require_one_cap($caps) {
1930 if (!$this->have_one_cap($caps)) {
1931 $capsstring = join(', ', $caps);
1932 print_error('nopermissions', '', '', $capsstring);
1937 * Throw error if at least one parent context hasn't got one of the caps $caps
1939 * @param string $tabname edit tab name
1941 public function require_one_edit_tab_cap($tabname) {
1942 if (!$this->have_one_edit_tab_cap($tabname)) {
1943 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1950 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1952 * @package core_question
1953 * @category files
1954 * @param string $text text being processed
1955 * @param string $file the php script used to serve files
1956 * @param int $contextid context ID
1957 * @param string $component component
1958 * @param string $filearea filearea
1959 * @param array $ids other IDs will be used to check file permission
1960 * @param int $itemid item ID
1961 * @param array $options options
1962 * @return string
1964 function question_rewrite_question_urls($text, $file, $contextid, $component,
1965 $filearea, array $ids, $itemid, array $options=null) {
1967 $idsstr = '';
1968 if (!empty($ids)) {
1969 $idsstr .= implode('/', $ids);
1971 if ($itemid !== null) {
1972 $idsstr .= '/' . $itemid;
1974 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1975 $filearea, $idsstr, $options);
1979 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1980 * viewing the question outside an attempt (for example, in the question bank
1981 * listing or in the quiz statistics report).
1983 * @param string $text the question text.
1984 * @param int $questionid the question id.
1985 * @param int $filecontextid the context id of the question being displayed.
1986 * @param string $filecomponent the component that owns the file area.
1987 * @param string $filearea the file area name.
1988 * @param int|null $itemid the file's itemid
1989 * @param int $previewcontextid the context id where the preview is being displayed.
1990 * @param string $previewcomponent component responsible for displaying the preview.
1991 * @param array $options text and file options ('forcehttps'=>false)
1992 * @return string $questiontext with URLs rewritten.
1994 function question_rewrite_question_preview_urls($text, $questionid,
1995 $filecontextid, $filecomponent, $filearea, $itemid,
1996 $previewcontextid, $previewcomponent, $options = null) {
1998 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1999 if ($itemid) {
2000 $path .= '/' . $itemid;
2003 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2004 $filecomponent, $filearea, $path, $options);
2008 * Called by pluginfile.php to serve files related to the 'question' core
2009 * component and for files belonging to qtypes.
2011 * For files that relate to questions in a question_attempt, then we delegate to
2012 * a function in the component that owns the attempt (for example in the quiz,
2013 * or in core question preview) to get necessary inforation.
2015 * (Note that, at the moment, all question file areas relate to questions in
2016 * attempts, so the If at the start of the last paragraph is always true.)
2018 * Does not return, either calls send_file_not_found(); or serves the file.
2020 * @package core_question
2021 * @category files
2022 * @param stdClass $course course settings object
2023 * @param stdClass $context context object
2024 * @param string $component the name of the component we are serving files for.
2025 * @param string $filearea the name of the file area.
2026 * @param array $args the remaining bits of the file path.
2027 * @param bool $forcedownload whether the user must be forced to download the file.
2028 * @param array $options additional options affecting the file serving
2030 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2031 global $DB, $CFG;
2033 // Special case, sending a question bank export.
2034 if ($filearea === 'export') {
2035 list($context, $course, $cm) = get_context_info_array($context->id);
2036 require_login($course, false, $cm);
2038 require_once($CFG->dirroot . '/question/editlib.php');
2039 $contexts = new question_edit_contexts($context);
2040 // check export capability
2041 $contexts->require_one_edit_tab_cap('export');
2042 $category_id = (int)array_shift($args);
2043 $format = array_shift($args);
2044 $cattofile = array_shift($args);
2045 $contexttofile = array_shift($args);
2046 $filename = array_shift($args);
2048 // load parent class for import/export
2049 require_once($CFG->dirroot . '/question/format.php');
2050 require_once($CFG->dirroot . '/question/editlib.php');
2051 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2053 $classname = 'qformat_' . $format;
2054 if (!class_exists($classname)) {
2055 send_file_not_found();
2058 $qformat = new $classname();
2060 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2061 send_file_not_found();
2064 $qformat->setCategory($category);
2065 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2066 $qformat->setCourse($course);
2068 if ($cattofile == 'withcategories') {
2069 $qformat->setCattofile(true);
2070 } else {
2071 $qformat->setCattofile(false);
2074 if ($contexttofile == 'withcontexts') {
2075 $qformat->setContexttofile(true);
2076 } else {
2077 $qformat->setContexttofile(false);
2080 if (!$qformat->exportpreprocess()) {
2081 send_file_not_found();
2082 print_error('exporterror', 'question', $thispageurl->out());
2085 // export data to moodle file pool
2086 if (!$content = $qformat->exportprocess()) {
2087 send_file_not_found();
2090 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2093 // Normal case, a file belonging to a question.
2094 $qubaidorpreview = array_shift($args);
2096 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2097 if ($qubaidorpreview === 'preview') {
2098 $previewcontextid = (int)array_shift($args);
2099 $previewcomponent = array_shift($args);
2100 $questionid = (int) array_shift($args);
2101 $previewcontext = context_helper::instance_by_id($previewcontextid);
2103 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2104 $previewcontext, $questionid,
2105 $context, $component, $filearea, $args,
2106 $forcedownload, $options), 'callbackmissing');
2108 if ($result === 'callbackmissing') {
2109 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2110 "{$previewcomponent}_question_preview_pluginfile callback. " .
2111 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
2114 send_file_not_found();
2117 // 2. A question being attempted in the normal way.
2118 $qubaid = (int)$qubaidorpreview;
2119 $slot = (int)array_shift($args);
2121 $module = $DB->get_field('question_usages', 'component',
2122 array('id' => $qubaid));
2123 if (!$module) {
2124 send_file_not_found();
2127 if ($module === 'core_question_preview') {
2128 return qbank_previewquestion\helper::question_preview_question_pluginfile($course, $context,
2129 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2131 } else {
2132 $dir = core_component::get_component_directory($module);
2133 if (!file_exists("$dir/lib.php")) {
2134 send_file_not_found();
2136 include_once("$dir/lib.php");
2138 $filefunction = $module . '_question_pluginfile';
2139 if (function_exists($filefunction)) {
2140 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2141 $args, $forcedownload, $options);
2144 // Okay, we're here so lets check for function without 'mod_'.
2145 if (strpos($module, 'mod_') === 0) {
2146 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2147 if (function_exists($filefunctionold)) {
2148 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2149 $args, $forcedownload, $options);
2153 send_file_not_found();
2158 * Serve questiontext files in the question text when they are displayed in this report.
2160 * @package core_files
2161 * @category files
2162 * @param context $previewcontext the context in which the preview is happening.
2163 * @param int $questionid the question id.
2164 * @param context $filecontext the file (question) context.
2165 * @param string $filecomponent the component the file belongs to.
2166 * @param string $filearea the file area.
2167 * @param array $args remaining file args.
2168 * @param bool $forcedownload.
2169 * @param array $options additional options affecting the file serving.
2171 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2172 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2173 global $DB;
2175 // Verify that contextid matches the question.
2176 $question = $DB->get_record_sql('
2177 SELECT q.*, qc.contextid
2178 FROM {question} q
2179 JOIN {question_categories} qc ON qc.id = q.category
2180 WHERE q.id = :id AND qc.contextid = :contextid',
2181 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2183 // Check the capability.
2184 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2185 require_login($course, false, $cm);
2187 question_require_capability_on($question, 'use');
2189 $fs = get_file_storage();
2190 $relativepath = implode('/', $args);
2191 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2192 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2193 send_file_not_found();
2196 send_stored_file($file, 0, 0, $forcedownload, $options);
2200 * Create url for question export
2202 * @param int $contextid, current context
2203 * @param int $categoryid, categoryid
2204 * @param string $format
2205 * @param string $withcategories
2206 * @param string $ithcontexts
2207 * @param moodle_url export file url
2208 * @deprecated since Moodle 4.0 MDL-71573
2209 * @see qbank_exportquestions\exportquestions_helper
2211 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2212 $withcontexts, $filename) {
2213 debugging('Function question_make_export_url() has been deprecated and moved to qbank_exportquestions plugin,
2214 Please use qbank_exportquestions\exportquestions_helper::question_make_export_url() instead.', DEBUG_DEVELOPER);
2215 global $CFG;
2216 $urlbase = "$CFG->wwwroot/pluginfile.php";
2217 return moodle_url::make_file_url($urlbase,
2218 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2219 "/{$withcontexts}/{$filename}", true);
2223 * Get the URL to export a single question (exportone.php).
2225 * @param stdClass|question_definition $question the question definition as obtained from
2226 * question_bank::load_question_data() or question_bank::make_question().
2227 * (Only ->id and ->contextid are used.)
2228 * @return moodle_url the requested URL.
2229 * @deprecated since Moodle 4.0
2230 * @see \qbank_exporttoxml\helper::question_get_export_single_question_url()
2231 * @todo Final deprecation on Moodle 4.4 MDL-72438
2233 function question_get_export_single_question_url($question) {
2234 debugging('Function question_get_export_single_question_url() has been deprecated and moved to qbank_exporttoxml plugin,
2235 please use qbank_exporttoxml\helper::question_get_export_single_question_url() instead.', DEBUG_DEVELOPER);
2236 qbank_exporttoxml\helper::question_get_export_single_question_url($question);
2240 * Return a list of page types
2241 * @param string $pagetype current page type
2242 * @param stdClass $parentcontext Block's parent context
2243 * @param stdClass $currentcontext Current context of block
2245 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2246 global $CFG;
2247 $types = array(
2248 'question-*'=>get_string('page-question-x', 'question'),
2249 'question-edit'=>get_string('page-question-edit', 'question'),
2250 'question-category'=>get_string('page-question-category', 'question'),
2251 'question-export'=>get_string('page-question-export', 'question'),
2252 'question-import'=>get_string('page-question-import', 'question')
2254 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2255 require_once($CFG->dirroot . '/course/lib.php');
2256 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2257 } else {
2258 return $types;
2263 * Does an activity module use the question bank?
2265 * @param string $modname The name of the module (without mod_ prefix).
2266 * @return bool true if the module uses questions.
2268 function question_module_uses_questions($modname) {
2269 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2270 return true;
2273 $component = 'mod_'.$modname;
2274 if (component_callback_exists($component, 'question_pluginfile')) {
2275 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2276 return true;
2279 return false;
2283 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
2285 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
2286 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
2288 * @param string|null $oldidnumber a question idnumber, or can be null.
2289 * @param int $categoryid a question category id.
2290 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
2292 function core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid): ?string {
2293 global $DB;
2295 // The the old idnumber is not of the right form, bail now.
2296 if (!preg_match('~\d+$~', $oldidnumber, $matches)) {
2297 return null;
2300 // Find all used idnumbers in one DB query.
2301 $usedidnumbers = $DB->get_records_select_menu('question', 'category = ? AND idnumber IS NOT NULL',
2302 [$categoryid], '', 'idnumber, 1');
2304 // Find the next unused idnumber.
2305 $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
2306 $stem = substr($oldidnumber, 0, -strlen($matches[0]));
2307 do {
2309 // If we have got to something9999, insert an extra digit before incrementing.
2310 if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2311 $numberbit = $matches[1] . '0' . $matches[2];
2313 $numberbit++;
2314 $newidnumber = $stem . substr($numberbit, 1);
2315 } while (isset($usedidnumbers[$newidnumber]));
2317 return (string) $newidnumber;