MDL-65799 enrol: Final deprecations
[moodle.git] / lib / questionlib.php
blob2ed3d79dcaa64498226720c1dbd0a344c146b8b5
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 // Now recursively delete all child questions
381 if ($children = $DB->get_records('question',
382 array('parent' => $questionid), '', 'id, qtype')) {
383 foreach ($children as $child) {
384 if ($child->id != $questionid) {
385 question_delete_question($child->id);
390 // Delete question comments.
391 $DB->delete_records('comments', ['itemid' => $questionid, 'component' => 'qbank_comment',
392 'commentarea' => 'question']);
393 // Finally delete the question record itself
394 $DB->delete_records('question', array('id' => $questionid));
395 question_bank::notify_question_edited($questionid);
397 // Log the deletion of this question.
398 $event = \core\event\question_deleted::create_from_question_instance($question);
399 $event->add_record_snapshot('question', $question);
400 $event->trigger();
404 * All question categories and their questions are deleted for this context id.
406 * @param int $contextid The contextid to delete question categories from
407 * @return array only returns an empty array for backwards compatibility.
409 function question_delete_context($contextid) {
410 global $DB;
412 $fields = 'id, parent, name, contextid';
413 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
414 //Sort categories following their tree (parent-child) relationships
415 //this will make the feedback more readable
416 $categories = sort_categories_by_tree($categories);
418 foreach ($categories as $category) {
419 question_category_delete_safe($category);
422 return [];
426 * All question categories and their questions are deleted for this course.
428 * @param stdClass $course an object representing the activity
429 * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
430 * @return bool always true.
432 function question_delete_course($course, $notused = false) {
433 $coursecontext = context_course::instance($course->id);
434 question_delete_context($coursecontext->id);
435 return true;
439 * Category is about to be deleted,
440 * 1/ All question categories and their questions are deleted for this course category.
441 * 2/ All questions are moved to new category
443 * @param stdClass|core_course_category $category course category object
444 * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
445 * category where content moved
446 * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
447 * @return boolean
449 function question_delete_course_category($category, $newcategory, $notused=false) {
450 global $DB;
452 $context = context_coursecat::instance($category->id);
453 if (empty($newcategory)) {
454 question_delete_context($context->id);
456 } else {
457 // Move question categories to the new context.
458 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
459 return false;
462 // Only move question categories if there is any question category at all!
463 if ($topcategory = question_get_top_category($context->id)) {
464 $newtopcategory = question_get_top_category($newcontext->id, true);
466 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
467 $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
468 // Now delete the top category.
469 $DB->delete_records('question_categories', array('id' => $topcategory->id));
473 return true;
477 * Enter description here...
479 * @param array $questionids of question ids
480 * @param object $newcontextid the context to create the saved category in.
481 * @param string $oldplace a textual description of the think being deleted,
482 * e.g. from get_context_name
483 * @param object $newcategory
484 * @return mixed false on
486 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
487 $newcategory = null) {
488 global $DB;
490 // Make a category in the parent context to move the questions to.
491 if (is_null($newcategory)) {
492 $newcategory = new stdClass();
493 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
494 $newcategory->contextid = $newcontextid;
495 // Max length of column name in question_categories is 255.
496 $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
497 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
498 $newcategory->sortorder = 999;
499 $newcategory->stamp = make_unique_id_code();
500 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
503 // Move any remaining questions to the 'saved' category.
504 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
505 return false;
507 return $newcategory;
511 * All question categories and their questions are deleted for this activity.
513 * @param object $cm the course module object representing the activity
514 * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
515 * @return boolean
517 function question_delete_activity($cm, $notused = false) {
518 global $DB;
520 $modcontext = context_module::instance($cm->id);
521 question_delete_context($modcontext->id);
522 return true;
526 * This function will handle moving all tag instances to a new context for a
527 * given list of questions.
529 * Questions can be tagged in up to two contexts:
530 * 1.) The context the question exists in.
531 * 2.) The course context (if the question context is a higher context.
532 * E.g. course category context or system context.
534 * This means a question that exists in a higher context (e.g. course cat or
535 * system context) may have multiple groups of tags in any number of child
536 * course contexts.
538 * Questions in the course category context can be move "down" a context level
539 * into one of their child course contexts or activity contexts which affects the
540 * availability of that question in other courses / activities.
542 * In this case it makes the questions no longer available in the other course or
543 * activity contexts so we need to make sure that the tag instances in those other
544 * contexts are removed.
546 * @param stdClass[] $questions The list of question being moved (must include
547 * the id and contextid)
548 * @param context $newcontext The Moodle context the questions are being moved to
550 function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
551 // If the questions are moving to a new course/activity context then we need to
552 // find any existing tag instances from any unavailable course contexts and
553 // delete them because they will no longer be applicable (we don't support
554 // tagging questions across courses).
555 $instancestodelete = [];
556 $instancesfornewcontext = [];
557 $newcontextparentids = $newcontext->get_parent_context_ids();
558 $questionids = array_map(function($question) {
559 return $question->id;
560 }, $questions);
561 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
563 foreach ($questions as $question) {
564 $tagobjects = $questionstagobjects[$question->id] ?? [];
566 foreach ($tagobjects as $tagobject) {
567 $tagid = $tagobject->taginstanceid;
568 $tagcontextid = $tagobject->taginstancecontextid;
569 $istaginnewcontext = $tagcontextid == $newcontext->id;
570 $istaginquestioncontext = $tagcontextid == $question->contextid;
572 if ($istaginnewcontext) {
573 // This tag instance is already in the correct context so we can
574 // ignore it.
575 continue;
578 if ($istaginquestioncontext) {
579 // This tag instance is in the question context so it needs to be
580 // updated.
581 $instancesfornewcontext[] = $tagid;
582 continue;
585 // These tag instances are in neither the new context nor the
586 // question context so we need to determine what to do based on
587 // the context they are in and the new question context.
588 $tagcontext = context::instance_by_id($tagcontextid);
589 $tagcoursecontext = $tagcontext->get_course_context(false);
590 // The tag is in a course context if get_course_context() returns
591 // itself.
592 $istaginstancecontextcourse = !empty($tagcoursecontext)
593 && $tagcontext->id == $tagcoursecontext->id;
595 if ($istaginstancecontextcourse) {
596 // If the tag instance is in a course context we need to add some
597 // special handling.
598 $tagcontextparentids = $tagcontext->get_parent_context_ids();
599 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
600 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
602 if ($isnewcontextaparent) {
603 // If the tag instance is a course context tag and the new
604 // context is still a parent context to the tag context then
605 // we can leave this tag where it is.
606 continue;
607 } else if ($isnewcontextachild) {
608 // If the new context is a child context (e.g. activity) of this
609 // tag instance then we should move all of this tag instance
610 // down into the activity context along with the question.
611 $instancesfornewcontext[] = $tagid;
612 } else {
613 // If the tag is in a course context that is no longer a parent
614 // or child of the new context then this tag instance should be
615 // removed.
616 $instancestodelete[] = $tagid;
618 } else {
619 // This is a catch all for any tag instances not in the question
620 // context or a course context. These tag instances should be
621 // updated to the new context id. This will clean up old invalid
622 // data.
623 $instancesfornewcontext[] = $tagid;
628 if (!empty($instancestodelete)) {
629 // Delete any course context tags that may no longer be valid.
630 core_tag_tag::delete_instances_by_id($instancestodelete);
633 if (!empty($instancesfornewcontext)) {
634 // Update the tag instances to the new context id.
635 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
640 * This function should be considered private to the question bank, it is called from
641 * question/editlib.php question/contextmoveq.php and a few similar places to to the
642 * work of actually moving questions and associated data. However, callers of this
643 * function also have to do other work, which is why you should not call this method
644 * directly from outside the questionbank.
646 * @param array $questionids of question ids.
647 * @param integer $newcategoryid the id of the category to move to.
649 function question_move_questions_to_category($questionids, $newcategoryid) {
650 global $DB;
652 $newcontextid = $DB->get_field('question_categories', 'contextid',
653 array('id' => $newcategoryid));
654 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
655 $questions = $DB->get_records_sql("
656 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
657 FROM {question} q
658 JOIN {question_categories} qc ON q.category = qc.id
659 WHERE q.id $questionidcondition", $params);
660 foreach ($questions as $question) {
661 if ($newcontextid != $question->contextid) {
662 question_bank::get_qtype($question->qtype)->move_files(
663 $question->id, $question->contextid, $newcontextid);
665 // Check whether there could be a clash of idnumbers in the new category.
666 if (((string) $question->idnumber !== '') &&
667 $DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $newcategoryid])) {
668 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
669 [$newcategoryid, $question->idnumber . '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
670 $unique = 1;
671 if (count($rec)) {
672 $rec = reset($rec);
673 $idnumber = $rec->idnumber;
674 if (strpos($idnumber, '_') !== false) {
675 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
678 // For the move process, add a numerical increment to the idnumber. This means that if a question is
679 // mistakenly moved then the idnumber will not be completely lost.
680 $q = new stdClass();
681 $q->id = $question->id;
682 $q->category = $newcategoryid;
683 $q->idnumber = $question->idnumber . '_' . $unique;
684 $DB->update_record('question', $q);
687 // Log this question move.
688 $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
689 ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategoryid]);
690 $event->trigger();
693 // Move the questions themselves.
694 $DB->set_field_select('question', 'category', $newcategoryid,
695 "id $questionidcondition", $params);
697 // Move any subquestions belonging to them.
698 $DB->set_field_select('question', 'category', $newcategoryid,
699 "parent $questionidcondition", $params);
701 $newcontext = context::instance_by_id($newcontextid);
702 question_move_question_tags_to_new_context($questions, $newcontext);
704 // TODO Deal with datasets.
706 // Purge these questions from the cache.
707 foreach ($questions as $question) {
708 question_bank::notify_question_edited($question->id);
711 return true;
715 * This function helps move a question cateogry to a new context by moving all
716 * the files belonging to all the questions to the new context.
717 * Also moves subcategories.
718 * @param integer $categoryid the id of the category being moved.
719 * @param integer $oldcontextid the old context id.
720 * @param integer $newcontextid the new context id.
722 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
723 global $DB;
725 $questions = [];
726 $questionids = $DB->get_records_menu('question',
727 array('category' => $categoryid), '', 'id,qtype');
728 foreach ($questionids as $questionid => $qtype) {
729 question_bank::get_qtype($qtype)->move_files(
730 $questionid, $oldcontextid, $newcontextid);
731 // Purge this question from the cache.
732 question_bank::notify_question_edited($questionid);
734 $questions[] = (object) [
735 'id' => $questionid,
736 'contextid' => $oldcontextid
740 $newcontext = context::instance_by_id($newcontextid);
741 question_move_question_tags_to_new_context($questions, $newcontext);
743 $subcatids = $DB->get_records_menu('question_categories',
744 array('parent' => $categoryid), '', 'id,1');
745 foreach ($subcatids as $subcatid => $notused) {
746 $DB->set_field('question_categories', 'contextid', $newcontextid,
747 array('id' => $subcatid));
748 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
753 * Generate the URL for starting a new preview of a given question with the given options.
754 * @param integer $questionid the question to preview.
755 * @param string $preferredbehaviour the behaviour to use for the preview.
756 * @param float $maxmark the maximum to mark the question out of.
757 * @param question_display_options $displayoptions the display options to use.
758 * @param int $variant the variant of the question to preview. If null, one will
759 * be picked randomly.
760 * @param object $context context to run the preview in (affects things like
761 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
762 * @return moodle_url the URL.
763 * @deprecated since Moodle 4.0
764 * @see qbank_previewquestion\helper::question_preview_url()
765 * @todo Final deprecation on Moodle 4.4 MDL-72438
767 function question_preview_url($questionid, $preferredbehaviour = null,
768 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
769 debugging('Function question_preview_url() has been deprecated and moved to qbank_previewquestion plugin,
770 Please use qbank_previewquestion\helper::question_preview_url() instead.', DEBUG_DEVELOPER);
772 return \qbank_previewquestion\helper::question_preview_url($questionid, $preferredbehaviour = null,
773 $maxmark = null, $displayoptions = null, $variant = null, $context = null);
777 * @return array that can be passed as $params to the {@link popup_action} constructor.
778 * @deprecated since Moodle 4.0
779 * @see qbank_previewquestion\helper::question_preview_popup_params()
780 * @todo Final deprecation on Moodle 4.4 MDL-72438
782 function question_preview_popup_params() {
783 debugging('Function question_preview_popup_params() has been deprecated and moved to qbank_previewquestion plugin,
784 Please use qbank_previewquestion\helper::question_preview_popup_params() instead.', DEBUG_DEVELOPER);
786 return \qbank_previewquestion\helper::question_preview_popup_params();
790 * Given a list of ids, load the basic information about a set of questions from
791 * the questions table. The $join and $extrafields arguments can be used together
792 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
793 * read the code below to see how the SQL is assembled. Throws exceptions on error.
795 * @param array $questionids array of question ids to load. If null, then all
796 * questions matched by $join will be loaded.
797 * @param string $extrafields extra SQL code to be added to the query.
798 * @param string $join extra SQL code to be added to the query.
799 * @param array $extraparams values for any placeholders in $join.
800 * You must use named placeholders.
801 * @param string $orderby what to order the results by. Optional, default is unspecified order.
803 * @return array partially complete question objects. You need to call get_question_options
804 * on them before they can be properly used.
806 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
807 $extraparams = array(), $orderby = '') {
808 global $DB;
810 if ($questionids === null) {
811 $where = '';
812 $params = array();
813 } else {
814 if (empty($questionids)) {
815 return array();
818 list($questionidcondition, $params) = $DB->get_in_or_equal(
819 $questionids, SQL_PARAMS_NAMED, 'qid0000');
820 $where = 'WHERE q.id ' . $questionidcondition;
823 if ($join) {
824 $join = 'JOIN ' . $join;
827 if ($extrafields) {
828 $extrafields = ', ' . $extrafields;
831 if ($orderby) {
832 $orderby = 'ORDER BY ' . $orderby;
835 $sql = "SELECT q.*, qc.contextid{$extrafields}
836 FROM {question} q
837 JOIN {question_categories} qc ON q.category = qc.id
838 {$join}
839 {$where}
840 {$orderby}";
842 // Load the questions.
843 $questions = $DB->get_records_sql($sql, $extraparams + $params);
844 foreach ($questions as $question) {
845 $question->_partiallyloaded = true;
848 return $questions;
852 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
853 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
854 * read the code below to see how the SQL is assembled. Throws exceptions on error.
856 * @param array $questionids array of question ids.
857 * @param string $extrafields extra SQL code to be added to the query.
858 * @param string $join extra SQL code to be added to the query.
859 * @param array $extraparams values for any placeholders in $join.
860 * You are strongly recommended to use named placeholder.
862 * @return array question objects.
864 function question_load_questions($questionids, $extrafields = '', $join = '') {
865 $questions = question_preload_questions($questionids, $extrafields, $join);
867 // Load the question type specific information
868 if (!get_question_options($questions)) {
869 return 'Could not load the question options';
872 return $questions;
876 * Private function to factor common code out of get_question_options().
878 * @param object $question the question to tidy.
879 * @param stdClass $category The question_categories record for the given $question.
880 * @param stdClass[]|null $tagobjects The tags for the given $question.
881 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
883 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
884 // Load question-type specific fields.
885 if (!question_bank::is_qtype_installed($question->qtype)) {
886 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
887 'qtype_missingtype')) . $question->questiontext;
889 question_bank::get_qtype($question->qtype)->get_question_options($question);
891 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
892 $question->defaultmark += 0;
893 $question->penalty += 0;
895 if (isset($question->_partiallyloaded)) {
896 unset($question->_partiallyloaded);
899 $question->categoryobject = $category;
901 if (!is_null($tagobjects)) {
902 $categorycontext = context::instance_by_id($category->contextid);
903 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
904 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
905 $question->coursetags = $sortedtagobjects->coursetags;
906 $question->tagobjects = $sortedtagobjects->tagobjects;
907 $question->tags = $sortedtagobjects->tags;
912 * Updates the question objects with question type specific
913 * information by calling {@link get_question_options()}
915 * Can be called either with an array of question objects or with a single
916 * question object.
918 * @param mixed $questions Either an array of question objects to be updated
919 * or just a single question object
920 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
921 * @param stdClass[] $filtercourses The courses to filter the course tags by.
922 * @return bool Indicates success or failure.
924 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
925 global $DB;
927 $questionlist = is_array($questions) ? $questions : [$questions];
928 $categoryids = [];
929 $questionids = [];
931 if (empty($questionlist)) {
932 return true;
935 foreach ($questionlist as $question) {
936 $questionids[] = $question->id;
938 if (!in_array($question->category, $categoryids)) {
939 $categoryids[] = $question->category;
943 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
945 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
946 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
947 } else {
948 $tagobjectsbyquestion = null;
951 foreach ($questionlist as $question) {
952 if (is_null($tagobjectsbyquestion)) {
953 $tagobjects = null;
954 } else {
955 $tagobjects = $tagobjectsbyquestion[$question->id];
958 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
961 return true;
965 * Sort question tags by course or normal tags.
967 * This function also search tag instances that may have a context id that don't match either a course or
968 * question context and fix the data setting the correct context id.
970 * @param stdClass[] $tagobjects The tags for the given $question.
971 * @param stdClass $categorycontext The question categories context.
972 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
973 * @return stdClass $sortedtagobjects Sorted tag objects.
975 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
977 // Questions can have two sets of tag instances. One set at the
978 // course context level and another at the context the question
979 // belongs to (e.g. course category, system etc).
980 $sortedtagobjects = new stdClass();
981 $sortedtagobjects->coursetagobjects = [];
982 $sortedtagobjects->coursetags = [];
983 $sortedtagobjects->tagobjects = [];
984 $sortedtagobjects->tags = [];
985 $taginstanceidstonormalise = [];
986 $filtercoursecontextids = [];
987 $hasfiltercourses = !empty($filtercourses);
989 if ($hasfiltercourses) {
990 // If we're being asked to filter the course tags by a set of courses
991 // then get the context ids to filter below.
992 $filtercoursecontextids = array_map(function($course) {
993 $coursecontext = context_course::instance($course->id);
994 return $coursecontext->id;
995 }, $filtercourses);
998 foreach ($tagobjects as $tagobject) {
999 $tagcontextid = $tagobject->taginstancecontextid;
1000 $tagcontext = context::instance_by_id($tagcontextid);
1001 $tagcoursecontext = $tagcontext->get_course_context(false);
1002 // This is a course tag if the tag context is a course context which
1003 // doesn't match the question's context. Any tag in the question context
1004 // is not considered a course tag, it belongs to the question.
1005 $iscoursetag = $tagcoursecontext
1006 && $tagcontext->id == $tagcoursecontext->id
1007 && $tagcontext->id != $categorycontext->id;
1009 if ($iscoursetag) {
1010 // Any tag instance in a course context level is considered a course tag.
1011 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1012 // Add the tag to the list of course tags if we aren't being
1013 // asked to filter or if this tag is in the list of courses
1014 // we're being asked to filter by.
1015 $sortedtagobjects->coursetagobjects[] = $tagobject;
1016 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1018 } else {
1019 // All non course context level tag instances or tags in the question
1020 // context belong to the context that the question was created in.
1021 $sortedtagobjects->tagobjects[] = $tagobject;
1022 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1024 // Due to legacy tag implementations that don't force the recording
1025 // of a context id, some tag instances may have context ids that don't
1026 // match either a course context or the question context. In this case
1027 // we should take the opportunity to fix up the data and set the correct
1028 // context id.
1029 if ($tagcontext->id != $categorycontext->id) {
1030 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1031 // Update the object properties to reflect the DB update that will
1032 // happen below.
1033 $tagobject->taginstancecontextid = $categorycontext->id;
1038 if (!empty($taginstanceidstonormalise)) {
1039 // If we found any tag instances with incorrect context id data then we can
1040 // correct those values now by setting them to the question context id.
1041 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1044 return $sortedtagobjects;
1048 * Print the icon for the question type
1050 * @param object $question The question object for which the icon is required.
1051 * Only $question->qtype is used.
1052 * @return string the HTML for the img tag.
1054 function print_question_icon($question) {
1055 global $PAGE;
1056 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
1060 * Creates a stamp that uniquely identifies this version of the question
1062 * In future we want this to use a hash of the question data to guarantee that
1063 * identical versions have the same version stamp.
1065 * @param object $question
1066 * @return string A unique version stamp
1068 function question_hash($question) {
1069 return make_unique_id_code();
1072 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1075 * returns the categories with their names ordered following parent-child relationships
1076 * finally it tries to return pending categories (those being orphaned, whose parent is
1077 * incorrect) to avoid missing any category from original array.
1079 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1080 global $DB;
1082 $children = array();
1083 $keys = array_keys($categories);
1085 foreach ($keys as $key) {
1086 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1087 $children[$key] = $categories[$key];
1088 $categories[$key]->processed = true;
1089 $children = $children + sort_categories_by_tree(
1090 $categories, $children[$key]->id, $level+1);
1093 //If level = 1, we have finished, try to look for non processed categories
1094 // (bad parent) and sort them too
1095 if ($level == 1) {
1096 foreach ($keys as $key) {
1097 // If not processed and it's a good candidate to start (because its
1098 // parent doesn't exist in the course)
1099 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1100 array('contextid' => $categories[$key]->contextid,
1101 'id' => $categories[$key]->parent))) {
1102 $children[$key] = $categories[$key];
1103 $categories[$key]->processed = true;
1104 $children = $children + sort_categories_by_tree(
1105 $categories, $children[$key]->id, $level + 1);
1109 return $children;
1113 * Private method, only for the use of add_indented_names().
1115 * Recursively adds an indentedname field to each category, starting with the category
1116 * with id $id, and dealing with that category and all its children, and
1117 * return a new array, with those categories in the right order.
1119 * @param array $categories an array of categories which has had childids
1120 * fields added by flatten_category_tree(). Passed by reference for
1121 * performance only. It is not modfied.
1122 * @param int $id the category to start the indenting process from.
1123 * @param int $depth the indent depth. Used in recursive calls.
1124 * @return array a new array of categories, in the right order for the tree.
1125 * @deprecated since Moodle 4.0 MDL-71585
1126 * @see qbank_managecategories\helper
1127 * @todo Final deprecation on Moodle 4.4 MDL-72438
1129 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1130 debugging('Function flatten_category_tree() has been deprecated and moved to qbank_managecategories plugin,
1131 Please use qbank_managecategories\helper::flatten_category_tree() instead.', DEBUG_DEVELOPER);
1132 return \qbank_managecategories\helper::flatten_category_tree($categories, $id, $depth, $nochildrenof);
1136 * Format categories into an indented list reflecting the tree structure.
1138 * @param array $categories An array of category objects, for example from the.
1139 * @return array The formatted list of categories.
1140 * @deprecated since Moodle 4.0 MDL-71585
1141 * @see qbank_managecategories\helper
1142 * @todo Final deprecation on Moodle 4.4 MDL-72438
1144 function add_indented_names($categories, $nochildrenof = -1) {
1145 debugging('Function add_indented_names() has been deprecated and moved to qbank_managecategories plugin,
1146 Please use qbank_managecategories\helper::add_indented_names() instead.', DEBUG_DEVELOPER);
1147 return \qbank_managecategories\helper::add_indented_names($categories, $nochildrenof);
1151 * Output a select menu of question categories.
1153 * Categories from this course and (optionally) published categories from other courses
1154 * are included. Optionally, only categories the current user may edit can be included.
1156 * @param integer $courseid the id of the course to get the categories for.
1157 * @param integer $published if true, include publised categories from other courses.
1158 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1159 * @param integer $selected optionally, the id of a category to be selected by
1160 * default in the dropdown.
1161 * @deprecated since Moodle 4.0 MDL-71585
1162 * @see qbank_managecategories\helper
1163 * @todo Final deprecation on Moodle 4.4 MDL-72438
1165 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1166 $selected = "", $nochildrenof = -1) {
1167 debugging('Function question_category_select_menu() has been deprecated and moved to qbank_managecategories plugin,
1168 Please use qbank_managecategories\helper::question_category_select_menu() instead.', DEBUG_DEVELOPER);
1169 \qbank_managecategories\helper::question_category_select_menu($contexts, $top, $currentcat, $selected, $nochildrenof);
1173 * @param integer $contextid a context id.
1174 * @return object the default question category for that context, or false if none.
1176 function question_get_default_category($contextid) {
1177 global $DB;
1178 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1179 array($contextid), 'id', '*', 0, 1);
1180 if (!empty($category)) {
1181 return reset($category);
1182 } else {
1183 return false;
1188 * Gets the top category in the given context.
1189 * This function can optionally create the top category if it doesn't exist.
1191 * @param int $contextid A context id.
1192 * @param bool $create Whether create a top category if it doesn't exist.
1193 * @return bool|stdClass The top question category for that context, or false if none.
1195 function question_get_top_category($contextid, $create = false) {
1196 global $DB;
1197 $category = $DB->get_record('question_categories',
1198 array('contextid' => $contextid, 'parent' => 0));
1200 if (!$category && $create) {
1201 // We need to make one.
1202 $category = new stdClass();
1203 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1204 $category->info = '';
1205 $category->contextid = $contextid;
1206 $category->parent = 0;
1207 $category->sortorder = 0;
1208 $category->stamp = make_unique_id_code();
1209 $category->id = $DB->insert_record('question_categories', $category);
1212 return $category;
1216 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1218 * @param array $contextids List of context ids
1219 * @return array
1221 function question_get_top_categories_for_contexts($contextids) {
1222 global $DB;
1224 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1225 list($insql, $params) = $DB->get_in_or_equal($contextids);
1226 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1227 $topcategories = $DB->get_fieldset_sql($sql, $params);
1229 return $topcategories;
1233 * Gets the default category in the most specific context.
1234 * If no categories exist yet then default ones are created in all contexts.
1236 * @param array $contexts The context objects for this context and all parent contexts.
1237 * @return object The default category - the category in the course context
1239 function question_make_default_categories($contexts) {
1240 global $DB;
1241 static $preferredlevels = array(
1242 CONTEXT_COURSE => 4,
1243 CONTEXT_MODULE => 3,
1244 CONTEXT_COURSECAT => 2,
1245 CONTEXT_SYSTEM => 1,
1248 $toreturn = null;
1249 $preferredness = 0;
1250 // If it already exists, just return it.
1251 foreach ($contexts as $key => $context) {
1252 $topcategory = question_get_top_category($context->id, true);
1253 if (!$exists = $DB->record_exists("question_categories",
1254 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1255 // Otherwise, we need to make one
1256 $category = new stdClass();
1257 $contextname = $context->get_context_name(false, true);
1258 // Max length of name field is 255.
1259 $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1260 $category->info = get_string('defaultinfofor', 'question', $contextname);
1261 $category->contextid = $context->id;
1262 $category->parent = $topcategory->id;
1263 // By default, all categories get this number, and are sorted alphabetically.
1264 $category->sortorder = 999;
1265 $category->stamp = make_unique_id_code();
1266 $category->id = $DB->insert_record('question_categories', $category);
1267 } else {
1268 $category = question_get_default_category($context->id);
1270 $thispreferredness = $preferredlevels[$context->contextlevel];
1271 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1272 $thispreferredness += 10;
1274 if ($thispreferredness > $preferredness) {
1275 $toreturn = $category;
1276 $preferredness = $thispreferredness;
1280 if (!is_null($toreturn)) {
1281 $toreturn = clone($toreturn);
1283 return $toreturn;
1287 * Get all the category objects, including a count of the number of questions in that category,
1288 * for all the categories in the lists $contexts.
1290 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1291 * @param string $sortorder used as the ORDER BY clause in the select statement.
1292 * @param bool $top Whether to return the top categories or not.
1293 * @return array of category objects.
1294 * @deprecated since Moodle 4.0 MDL-71585
1295 * @see qbank_managecategories\helper
1296 * @todo Final deprecation on Moodle 4.4 MDL-72438
1298 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1299 debugging('Function get_categories_for_contexts() has been deprecated and moved to qbank_managecategories plugin,
1300 Please use qbank_managecategories\helper::get_categories_for_contexts() instead.', DEBUG_DEVELOPER);
1301 return \qbank_managecategories\helper::get_categories_for_contexts($contexts, $sortorder, $top);
1305 * Output an array of question categories.
1307 * @param array $contexts The list of contexts.
1308 * @param bool $top Whether to return the top categories or not.
1309 * @param int $currentcat
1310 * @param bool $popupform
1311 * @param int $nochildrenof
1312 * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
1313 * @return array
1314 * @deprecated since Moodle 4.0 MDL-71585
1315 * @see qbank_managecategories\helper
1316 * @todo Final deprecation on Moodle 4.4 MDL-72438
1318 function question_category_options($contexts, $top = false, $currentcat = 0,
1319 $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
1320 debugging('Function question_category_options() has been deprecated and moved to qbank_managecategories plugin,
1321 Please use qbank_managecategories\helper::question_category_options() instead.', DEBUG_DEVELOPER);
1322 return \qbank_managecategories\helper::question_category_options($contexts, $top, $currentcat,
1323 $popupform, $nochildrenof, $escapecontextnames);
1327 * @deprecated since Moodle 4.0 MDL-71585
1328 * @see qbank_managecategories\helper
1329 * @todo Final deprecation on Moodle 4.4 MDL-72438
1331 function question_add_context_in_key($categories) {
1332 debugging('Function question_add_context_in_key() has been deprecated and moved to qbank_managecategories plugin,
1333 Please use qbank_managecategories\helper::question_add_context_in_key() instead.', DEBUG_DEVELOPER);
1334 return \qbank_managecategories\helper::question_add_context_in_key($categories);
1338 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1340 * @param array $categories An array of question categories.
1341 * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
1342 * @return array The same question category list given to the function, with the top category names being translated.
1343 * @deprecated since Moodle 4.0 MDL-71585
1344 * @see qbank_managecategories\helper
1345 * @todo Final deprecation on Moodle 4.4 MDL-72438
1347 function question_fix_top_names($categories, $escape = true) {
1348 debugging('Function question_fix_top_names() has been deprecated and moved to qbank_managecategories plugin,
1349 Please use qbank_managecategories\helper::question_fix_top_names() instead.', DEBUG_DEVELOPER);
1350 return \qbank_managecategories\helper::question_fix_top_names($categories, $escape);
1354 * @return array of question category ids of the category and all subcategories.
1356 function question_categorylist($categoryid) {
1357 global $DB;
1359 // final list of category IDs
1360 $categorylist = array();
1362 // a list of category IDs to check for any sub-categories
1363 $subcategories = array($categoryid);
1365 while ($subcategories) {
1366 foreach ($subcategories as $subcategory) {
1367 // if anything from the temporary list was added already, then we have a loop
1368 if (isset($categorylist[$subcategory])) {
1369 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1371 $categorylist[$subcategory] = $subcategory;
1374 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1376 $subcategories = $DB->get_records_select_menu('question_categories',
1377 "parent $in", $params, NULL, 'id,id AS id2');
1380 return $categorylist;
1384 * Get all parent categories of a given question category in decending order.
1385 * @param int $categoryid for which you want to find the parents.
1386 * @return array of question category ids of all parents categories.
1388 function question_categorylist_parents(int $categoryid) {
1389 global $DB;
1390 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1391 if (!$parent) {
1392 return [];
1394 $categorylist = [$parent];
1395 $currentid = $parent;
1396 while ($currentid) {
1397 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1398 if ($currentid) {
1399 $categorylist[] = $currentid;
1402 // Present the list in decending order (the top category at the top).
1403 $categorylist = array_reverse($categorylist);
1404 return $categorylist;
1407 //===========================
1408 // Import/Export Functions
1409 //===========================
1412 * Get list of available import or export formats
1413 * @param string $type 'import' if import list, otherwise export list assumed
1414 * @return array sorted list of import/export formats available
1416 function get_import_export_formats($type) {
1417 global $CFG;
1418 require_once($CFG->dirroot . '/question/format.php');
1420 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1422 $fileformatname = array();
1423 foreach ($formatclasses as $component => $formatclass) {
1425 $format = new $formatclass();
1426 if ($type == 'import') {
1427 $provided = $format->provide_import();
1428 } else {
1429 $provided = $format->provide_export();
1432 if ($provided) {
1433 list($notused, $fileformat) = explode('_', $component, 2);
1434 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1438 core_collator::asort($fileformatnames);
1439 return $fileformatnames;
1444 * Create a reasonable default file name for exporting questions from a particular
1445 * category.
1446 * @param object $course the course the questions are in.
1447 * @param object $category the question category.
1448 * @return string the filename.
1450 function question_default_export_filename($course, $category) {
1451 // We build a string that is an appropriate name (questions) from the lang pack,
1452 // then the corse shortname, then the question category name, then a timestamp.
1454 $base = clean_filename(get_string('exportfilename', 'question'));
1456 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1457 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1459 $shortname = clean_filename($course->shortname);
1460 if ($shortname == '' || $shortname == '_' ) {
1461 $shortname = $course->id;
1464 $categoryname = clean_filename(format_string($category->name));
1466 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1468 return $export_name;
1472 * Converts contextlevels to strings and back to help with reading/writing contexts
1473 * to/from import/export files.
1475 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1478 class context_to_string_translator{
1480 * @var array used to translate between contextids and strings for this context.
1482 protected $contexttostringarray = array();
1484 public function __construct($contexts) {
1485 $this->generate_context_to_string_array($contexts);
1488 public function context_to_string($contextid) {
1489 return $this->contexttostringarray[$contextid];
1492 public function string_to_context($contextname) {
1493 $contextid = array_search($contextname, $this->contexttostringarray);
1494 return $contextid;
1497 protected function generate_context_to_string_array($contexts) {
1498 if (!$this->contexttostringarray) {
1499 $catno = 1;
1500 foreach ($contexts as $context) {
1501 switch ($context->contextlevel) {
1502 case CONTEXT_MODULE :
1503 $contextstring = 'module';
1504 break;
1505 case CONTEXT_COURSE :
1506 $contextstring = 'course';
1507 break;
1508 case CONTEXT_COURSECAT :
1509 $contextstring = "cat$catno";
1510 $catno++;
1511 break;
1512 case CONTEXT_SYSTEM :
1513 $contextstring = 'system';
1514 break;
1516 $this->contexttostringarray[$context->id] = $contextstring;
1524 * Check capability on category
1526 * @param int|stdClass|question_definition $questionorid object or id.
1527 * If an object is passed, it should include ->contextid and ->createdby.
1528 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1529 * @param int $notused no longer used.
1530 * @return bool this user has the capability $cap for this question $question?
1531 * @throws coding_exception
1533 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1534 global $USER, $DB;
1536 if (is_numeric($questionorid)) {
1537 $questionid = (int)$questionorid;
1538 } else if (is_object($questionorid)) {
1539 // All we really need in this function is the contextid and author of the question.
1540 // We won't bother fetching other details of the question if these 2 fields are provided.
1541 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1542 $question = $questionorid;
1543 } else if (!empty($questionorid->id)) {
1544 $questionid = $questionorid->id;
1548 // At this point, either $question or $questionid is expected to be set.
1549 if (isset($questionid)) {
1550 try {
1551 $question = question_bank::load_question_data($questionid);
1552 } catch (Exception $e) {
1553 // Let's log the exception for future debugging,
1554 // but not during Behat, or we can't test these cases.
1555 if (!defined('BEHAT_SITE_RUNNING')) {
1556 debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1559 // Well, at least we tried. Seems that we really have to read from DB.
1560 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1561 FROM {question} q
1562 JOIN {question_categories} qc ON q.category = qc.id
1563 WHERE q.id = :id', ['id' => $questionid]);
1567 if (!isset($question)) {
1568 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1571 $context = context::instance_by_id($question->contextid);
1573 // These are existing questions capabilities that are set per category.
1574 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1575 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1577 if (!isset($capabilitieswithallandmine[$cap])) {
1578 return has_capability('moodle/question:' . $cap, $context);
1579 } else {
1580 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1581 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1586 * Require capability on question.
1588 function question_require_capability_on($question, $cap) {
1589 if (!question_has_capability_on($question, $cap)) {
1590 print_error('nopermissions', '', '', $cap);
1592 return true;
1596 * @param object $context a context
1597 * @return string A URL for editing questions in this context.
1599 function question_edit_url($context) {
1600 global $CFG, $SITE;
1601 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1602 return false;
1604 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1605 $defaultcategory = question_get_default_category($context->id);
1606 if ($defaultcategory) {
1607 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1609 switch ($context->contextlevel) {
1610 case CONTEXT_SYSTEM:
1611 return $baseurl . 'courseid=' . $SITE->id;
1612 case CONTEXT_COURSECAT:
1613 // This is nasty, becuase we can only edit questions in a course
1614 // context at the moment, so for now we just return false.
1615 return false;
1616 case CONTEXT_COURSE:
1617 return $baseurl . 'courseid=' . $context->instanceid;
1618 case CONTEXT_MODULE:
1619 return $baseurl . 'cmid=' . $context->instanceid;
1625 * Adds question bank setting links to the given navigation node if caps are met
1626 * and loads the navigation from the plugins.
1627 * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1628 * this method will help to autoload those nodes in the question bank navigation.
1630 * @param navigation_node $navigationnode The navigation node to add the question branch to
1631 * @param object $context
1632 * @param string $baseurl the url of the base where the api is implemented from
1633 * @return navigation_node Returns the question branch that was added
1635 function question_extend_settings_navigation(navigation_node $navigationnode, $context, $baseurl = '/question/edit.php') {
1636 global $PAGE;
1638 if ($context->contextlevel == CONTEXT_COURSE) {
1639 $params = ['courseid' => $context->instanceid];
1640 } else if ($context->contextlevel == CONTEXT_MODULE) {
1641 $params = ['cmid' => $context->instanceid];
1642 } else {
1643 return;
1646 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1647 $params['cat'] = $cat;
1650 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1651 new moodle_url($baseurl, $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1653 $corenavigations = [
1654 'questions' => [
1655 'title' => get_string('questions', 'question'),
1656 'url' => new moodle_url($baseurl)
1658 'categories' => [],
1659 'import' => [],
1660 'export' => []
1663 $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1664 foreach ($plugins as $componentname => $plugin) {
1665 $pluginentrypoint = new $plugin();
1666 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1667 // Don't need the plugins without navigation node.
1668 if ($pluginentrypointobject === null) {
1669 unset($plugins[$componentname]);
1670 continue;
1672 foreach ($corenavigations as $key => $corenavigation) {
1673 if ($pluginentrypointobject->get_navigation_key() === $key) {
1674 unset($plugins[$componentname]);
1675 if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1676 unset($corenavigations[$key]);
1677 break;
1679 $corenavigations[$key] = [
1680 'title' => $pluginentrypointobject->get_navigation_title(),
1681 'url' => $pluginentrypointobject->get_navigation_url()
1687 // Mitigate the risk of regression.
1688 foreach ($corenavigations as $node => $corenavigation) {
1689 if (empty($corenavigation)) {
1690 unset($corenavigations[$node]);
1694 // Community/additional plugins have navigation node.
1695 $pluginnavigations = [];
1696 foreach ($plugins as $componentname => $plugin) {
1697 $pluginentrypoint = new $plugin();
1698 $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1699 // Don't need the plugins without navigation node.
1700 if ($pluginentrypointobject === null || !\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1701 unset($plugins[$componentname]);
1702 continue;
1704 $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1705 'title' => $pluginentrypointobject->get_navigation_title(),
1706 'url' => $pluginentrypointobject->get_navigation_url(),
1707 'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1711 $contexts = new question_edit_contexts($context);
1712 foreach ($corenavigations as $key => $corenavigation) {
1713 if ($contexts->have_one_edit_tab_cap($key)) {
1714 $questionnode->add($corenavigation['title'], new moodle_url(
1715 $corenavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1719 foreach ($pluginnavigations as $key => $pluginnavigation) {
1720 if (is_array($pluginnavigation['capabilities'])) {
1721 if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1722 continue;
1725 $questionnode->add($pluginnavigation['title'], new moodle_url(
1726 $pluginnavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1729 return $questionnode;
1733 * @return array all the capabilities that relate to accessing particular questions.
1735 function question_get_question_capabilities() {
1736 return array(
1737 'moodle/question:add',
1738 'moodle/question:editmine',
1739 'moodle/question:editall',
1740 'moodle/question:viewmine',
1741 'moodle/question:viewall',
1742 'moodle/question:usemine',
1743 'moodle/question:useall',
1744 'moodle/question:movemine',
1745 'moodle/question:moveall',
1746 'moodle/question:tagmine',
1747 'moodle/question:tagall',
1748 'moodle/question:commentmine',
1749 'moodle/question:commentall',
1754 * @return array all the question bank capabilities.
1756 function question_get_all_capabilities() {
1757 $caps = question_get_question_capabilities();
1758 $caps[] = 'moodle/question:managecategory';
1759 $caps[] = 'moodle/question:flag';
1760 return $caps;
1765 * Tracks all the contexts related to the one where we are currently editing
1766 * questions, and provides helper methods to check permissions.
1768 * @copyright 2007 Jamie Pratt me@jamiep.org
1769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1771 class question_edit_contexts {
1773 public static $caps = array(
1774 'editq' => array('moodle/question:add',
1775 'moodle/question:editmine',
1776 'moodle/question:editall',
1777 'moodle/question:viewmine',
1778 'moodle/question:viewall',
1779 'moodle/question:usemine',
1780 'moodle/question:useall',
1781 'moodle/question:movemine',
1782 'moodle/question:moveall'),
1783 'questions'=>array('moodle/question:add',
1784 'moodle/question:editmine',
1785 'moodle/question:editall',
1786 'moodle/question:viewmine',
1787 'moodle/question:viewall',
1788 'moodle/question:movemine',
1789 'moodle/question:moveall'),
1790 'categories'=>array('moodle/question:managecategory'),
1791 'import'=>array('moodle/question:add'),
1792 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1794 protected $allcontexts;
1797 * Constructor
1798 * @param context the current context.
1800 public function __construct(context $thiscontext) {
1801 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1805 * @return context[] all parent contexts
1807 public function all() {
1808 return $this->allcontexts;
1812 * @return context lowest context which must be either the module or course context
1814 public function lowest() {
1815 return $this->allcontexts[0];
1819 * @param string $cap capability
1820 * @return context[] parent contexts having capability, zero based index
1822 public function having_cap($cap) {
1823 $contextswithcap = array();
1824 foreach ($this->allcontexts as $context) {
1825 if (has_capability($cap, $context)) {
1826 $contextswithcap[] = $context;
1829 return $contextswithcap;
1833 * @param array $caps capabilities
1834 * @return context[] parent contexts having at least one of $caps, zero based index
1836 public function having_one_cap($caps) {
1837 $contextswithacap = array();
1838 foreach ($this->allcontexts as $context) {
1839 foreach ($caps as $cap) {
1840 if (has_capability($cap, $context)) {
1841 $contextswithacap[] = $context;
1842 break; //done with caps loop
1846 return $contextswithacap;
1850 * @param string $tabname edit tab name
1851 * @return context[] parent contexts having at least one of $caps, zero based index
1853 public function having_one_edit_tab_cap($tabname) {
1854 return $this->having_one_cap(self::$caps[$tabname]);
1858 * @return context[] those contexts where a user can add a question and then use it.
1860 public function having_add_and_use() {
1861 $contextswithcap = array();
1862 foreach ($this->allcontexts as $context) {
1863 if (!has_capability('moodle/question:add', $context)) {
1864 continue;
1866 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1867 continue;
1869 $contextswithcap[] = $context;
1871 return $contextswithcap;
1875 * Has at least one parent context got the cap $cap?
1877 * @param string $cap capability
1878 * @return boolean
1880 public function have_cap($cap) {
1881 return (count($this->having_cap($cap)));
1885 * Has at least one parent context got one of the caps $caps?
1887 * @param array $caps capability
1888 * @return boolean
1890 public function have_one_cap($caps) {
1891 foreach ($caps as $cap) {
1892 if ($this->have_cap($cap)) {
1893 return true;
1896 return false;
1900 * Has at least one parent context got one of the caps for actions on $tabname
1902 * @param string $tabname edit tab name
1903 * @return boolean
1905 public function have_one_edit_tab_cap($tabname) {
1906 return $this->have_one_cap(self::$caps[$tabname]);
1910 * Throw error if at least one parent context hasn't got the cap $cap
1912 * @param string $cap capability
1914 public function require_cap($cap) {
1915 if (!$this->have_cap($cap)) {
1916 print_error('nopermissions', '', '', $cap);
1921 * Throw error if at least one parent context hasn't got one of the caps $caps
1923 * @param array $caps capabilities
1925 public function require_one_cap($caps) {
1926 if (!$this->have_one_cap($caps)) {
1927 $capsstring = join(', ', $caps);
1928 print_error('nopermissions', '', '', $capsstring);
1933 * Throw error if at least one parent context hasn't got one of the caps $caps
1935 * @param string $tabname edit tab name
1937 public function require_one_edit_tab_cap($tabname) {
1938 if (!$this->have_one_edit_tab_cap($tabname)) {
1939 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1946 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1948 * @package core_question
1949 * @category files
1950 * @param string $text text being processed
1951 * @param string $file the php script used to serve files
1952 * @param int $contextid context ID
1953 * @param string $component component
1954 * @param string $filearea filearea
1955 * @param array $ids other IDs will be used to check file permission
1956 * @param int $itemid item ID
1957 * @param array $options options
1958 * @return string
1960 function question_rewrite_question_urls($text, $file, $contextid, $component,
1961 $filearea, array $ids, $itemid, array $options=null) {
1963 $idsstr = '';
1964 if (!empty($ids)) {
1965 $idsstr .= implode('/', $ids);
1967 if ($itemid !== null) {
1968 $idsstr .= '/' . $itemid;
1970 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1971 $filearea, $idsstr, $options);
1975 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1976 * viewing the question outside an attempt (for example, in the question bank
1977 * listing or in the quiz statistics report).
1979 * @param string $text the question text.
1980 * @param int $questionid the question id.
1981 * @param int $filecontextid the context id of the question being displayed.
1982 * @param string $filecomponent the component that owns the file area.
1983 * @param string $filearea the file area name.
1984 * @param int|null $itemid the file's itemid
1985 * @param int $previewcontextid the context id where the preview is being displayed.
1986 * @param string $previewcomponent component responsible for displaying the preview.
1987 * @param array $options text and file options ('forcehttps'=>false)
1988 * @return string $questiontext with URLs rewritten.
1990 function question_rewrite_question_preview_urls($text, $questionid,
1991 $filecontextid, $filecomponent, $filearea, $itemid,
1992 $previewcontextid, $previewcomponent, $options = null) {
1994 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1995 if ($itemid) {
1996 $path .= '/' . $itemid;
1999 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2000 $filecomponent, $filearea, $path, $options);
2004 * Called by pluginfile.php to serve files related to the 'question' core
2005 * component and for files belonging to qtypes.
2007 * For files that relate to questions in a question_attempt, then we delegate to
2008 * a function in the component that owns the attempt (for example in the quiz,
2009 * or in core question preview) to get necessary inforation.
2011 * (Note that, at the moment, all question file areas relate to questions in
2012 * attempts, so the If at the start of the last paragraph is always true.)
2014 * Does not return, either calls send_file_not_found(); or serves the file.
2016 * @package core_question
2017 * @category files
2018 * @param stdClass $course course settings object
2019 * @param stdClass $context context object
2020 * @param string $component the name of the component we are serving files for.
2021 * @param string $filearea the name of the file area.
2022 * @param array $args the remaining bits of the file path.
2023 * @param bool $forcedownload whether the user must be forced to download the file.
2024 * @param array $options additional options affecting the file serving
2026 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2027 global $DB, $CFG;
2029 // Special case, sending a question bank export.
2030 if ($filearea === 'export') {
2031 list($context, $course, $cm) = get_context_info_array($context->id);
2032 require_login($course, false, $cm);
2034 require_once($CFG->dirroot . '/question/editlib.php');
2035 $contexts = new question_edit_contexts($context);
2036 // check export capability
2037 $contexts->require_one_edit_tab_cap('export');
2038 $category_id = (int)array_shift($args);
2039 $format = array_shift($args);
2040 $cattofile = array_shift($args);
2041 $contexttofile = array_shift($args);
2042 $filename = array_shift($args);
2044 // load parent class for import/export
2045 require_once($CFG->dirroot . '/question/format.php');
2046 require_once($CFG->dirroot . '/question/editlib.php');
2047 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2049 $classname = 'qformat_' . $format;
2050 if (!class_exists($classname)) {
2051 send_file_not_found();
2054 $qformat = new $classname();
2056 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2057 send_file_not_found();
2060 $qformat->setCategory($category);
2061 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2062 $qformat->setCourse($course);
2064 if ($cattofile == 'withcategories') {
2065 $qformat->setCattofile(true);
2066 } else {
2067 $qformat->setCattofile(false);
2070 if ($contexttofile == 'withcontexts') {
2071 $qformat->setContexttofile(true);
2072 } else {
2073 $qformat->setContexttofile(false);
2076 if (!$qformat->exportpreprocess()) {
2077 send_file_not_found();
2078 print_error('exporterror', 'question', $thispageurl->out());
2081 // export data to moodle file pool
2082 if (!$content = $qformat->exportprocess()) {
2083 send_file_not_found();
2086 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2089 // Normal case, a file belonging to a question.
2090 $qubaidorpreview = array_shift($args);
2092 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2093 if ($qubaidorpreview === 'preview') {
2094 $previewcontextid = (int)array_shift($args);
2095 $previewcomponent = array_shift($args);
2096 $questionid = (int) array_shift($args);
2097 $previewcontext = context_helper::instance_by_id($previewcontextid);
2099 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2100 $previewcontext, $questionid,
2101 $context, $component, $filearea, $args,
2102 $forcedownload, $options), 'callbackmissing');
2104 if ($result === 'callbackmissing') {
2105 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2106 "{$previewcomponent}_question_preview_pluginfile callback. " .
2107 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
2110 send_file_not_found();
2113 // 2. A question being attempted in the normal way.
2114 $qubaid = (int)$qubaidorpreview;
2115 $slot = (int)array_shift($args);
2117 $module = $DB->get_field('question_usages', 'component',
2118 array('id' => $qubaid));
2119 if (!$module) {
2120 send_file_not_found();
2123 if ($module === 'core_question_preview') {
2124 return qbank_previewquestion\helper::question_preview_question_pluginfile($course, $context,
2125 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2127 } else {
2128 $dir = core_component::get_component_directory($module);
2129 if (!file_exists("$dir/lib.php")) {
2130 send_file_not_found();
2132 include_once("$dir/lib.php");
2134 $filefunction = $module . '_question_pluginfile';
2135 if (function_exists($filefunction)) {
2136 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2137 $args, $forcedownload, $options);
2140 // Okay, we're here so lets check for function without 'mod_'.
2141 if (strpos($module, 'mod_') === 0) {
2142 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2143 if (function_exists($filefunctionold)) {
2144 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2145 $args, $forcedownload, $options);
2149 send_file_not_found();
2154 * Serve questiontext files in the question text when they are displayed in this report.
2156 * @package core_files
2157 * @category files
2158 * @param context $previewcontext the context in which the preview is happening.
2159 * @param int $questionid the question id.
2160 * @param context $filecontext the file (question) context.
2161 * @param string $filecomponent the component the file belongs to.
2162 * @param string $filearea the file area.
2163 * @param array $args remaining file args.
2164 * @param bool $forcedownload.
2165 * @param array $options additional options affecting the file serving.
2167 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2168 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2169 global $DB;
2171 // Verify that contextid matches the question.
2172 $question = $DB->get_record_sql('
2173 SELECT q.*, qc.contextid
2174 FROM {question} q
2175 JOIN {question_categories} qc ON qc.id = q.category
2176 WHERE q.id = :id AND qc.contextid = :contextid',
2177 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2179 // Check the capability.
2180 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2181 require_login($course, false, $cm);
2183 question_require_capability_on($question, 'use');
2185 $fs = get_file_storage();
2186 $relativepath = implode('/', $args);
2187 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2188 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2189 send_file_not_found();
2192 send_stored_file($file, 0, 0, $forcedownload, $options);
2196 * Create url for question export
2198 * @param int $contextid, current context
2199 * @param int $categoryid, categoryid
2200 * @param string $format
2201 * @param string $withcategories
2202 * @param string $ithcontexts
2203 * @param moodle_url export file url
2204 * @deprecated since Moodle 4.0 MDL-71573
2205 * @see qbank_exportquestions\exportquestions_helper
2207 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2208 $withcontexts, $filename) {
2209 debugging('Function question_make_export_url() has been deprecated and moved to qbank_exportquestions plugin,
2210 Please use qbank_exportquestions\exportquestions_helper::question_make_export_url() instead.', DEBUG_DEVELOPER);
2211 global $CFG;
2212 $urlbase = "$CFG->wwwroot/pluginfile.php";
2213 return moodle_url::make_file_url($urlbase,
2214 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2215 "/{$withcontexts}/{$filename}", true);
2219 * Get the URL to export a single question (exportone.php).
2221 * @param stdClass|question_definition $question the question definition as obtained from
2222 * question_bank::load_question_data() or question_bank::make_question().
2223 * (Only ->id and ->contextid are used.)
2224 * @return moodle_url the requested URL.
2225 * @deprecated since Moodle 4.0
2226 * @see \qbank_exporttoxml\helper::question_get_export_single_question_url()
2227 * @todo Final deprecation on Moodle 4.4 MDL-72438
2229 function question_get_export_single_question_url($question) {
2230 debugging('Function question_get_export_single_question_url() has been deprecated and moved to qbank_exporttoxml plugin,
2231 please use qbank_exporttoxml\helper::question_get_export_single_question_url() instead.', DEBUG_DEVELOPER);
2232 qbank_exporttoxml\helper::question_get_export_single_question_url($question);
2236 * Return a list of page types
2237 * @param string $pagetype current page type
2238 * @param stdClass $parentcontext Block's parent context
2239 * @param stdClass $currentcontext Current context of block
2241 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2242 global $CFG;
2243 $types = array(
2244 'question-*'=>get_string('page-question-x', 'question'),
2245 'question-edit'=>get_string('page-question-edit', 'question'),
2246 'question-category'=>get_string('page-question-category', 'question'),
2247 'question-export'=>get_string('page-question-export', 'question'),
2248 'question-import'=>get_string('page-question-import', 'question')
2250 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2251 require_once($CFG->dirroot . '/course/lib.php');
2252 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2253 } else {
2254 return $types;
2259 * Does an activity module use the question bank?
2261 * @param string $modname The name of the module (without mod_ prefix).
2262 * @return bool true if the module uses questions.
2264 function question_module_uses_questions($modname) {
2265 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2266 return true;
2269 $component = 'mod_'.$modname;
2270 if (component_callback_exists($component, 'question_pluginfile')) {
2271 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2272 return true;
2275 return false;
2279 * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
2281 * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
2282 * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
2284 * @param string|null $oldidnumber a question idnumber, or can be null.
2285 * @param int $categoryid a question category id.
2286 * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
2288 function core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid): ?string {
2289 global $DB;
2291 // The the old idnumber is not of the right form, bail now.
2292 if (!preg_match('~\d+$~', $oldidnumber, $matches)) {
2293 return null;
2296 // Find all used idnumbers in one DB query.
2297 $usedidnumbers = $DB->get_records_select_menu('question', 'category = ? AND idnumber IS NOT NULL',
2298 [$categoryid], '', 'idnumber, 1');
2300 // Find the next unused idnumber.
2301 $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
2302 $stem = substr($oldidnumber, 0, -strlen($matches[0]));
2303 do {
2305 // If we have got to something9999, insert an extra digit before incrementing.
2306 if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2307 $numberbit = $matches[1] . '0' . $matches[2];
2309 $numberbit++;
2310 $newidnumber = $stem . substr($numberbit, 1);
2311 } while (isset($usedidnumbers[$newidnumber]));
2313 return (string) $newidnumber;