2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
123 // Are they used by the core question system?
124 if (question_engine
::questions_in_use($questionids)) {
128 // Check if any plugins are using these questions.
129 $callbacksbytype = get_plugins_with_function('questions_in_use');
130 foreach ($callbacksbytype as $callbacks) {
131 foreach ($callbacks as $function) {
132 if ($function($questionids)) {
138 // Finally check legacy callback.
139 $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
140 foreach ($legacycallbacks as $plugin => $function) {
141 if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
142 continue; // Already done.
145 foreach ($questionids as $questionid) {
146 if (!empty($function($questionid))) {
156 * Determine whether there arey any questions belonging to this context, that is whether any of its
157 * question categories contain any questions. This will return true even if all the questions are
160 * @param mixed $context either a context object, or a context id.
161 * @return boolean whether any of the question categories beloning to this context have
162 * any questions in them.
164 function question_context_has_any_questions($context) {
166 if (is_object($context)) {
167 $contextid = $context->id
;
168 } else if (is_numeric($context)) {
169 $contextid = $context;
171 print_error('invalidcontextinhasanyquestions', 'question');
173 return $DB->record_exists_sql("SELECT *
175 JOIN {question_categories} qc ON qc.id = q.category
176 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
180 * Check whether a given grade is one of a list of allowed options. If not,
181 * depending on $matchgrades, either return the nearest match, or return false
182 * to signal an error.
183 * @param array $gradeoptionsfull list of valid options
184 * @param int $grade grade to be tested
185 * @param string $matchgrades 'error' or 'nearest'
186 * @return mixed either 'fixed' value or false if error.
188 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
190 if ($matchgrades == 'error') {
191 // (Almost) exact match, or an error.
192 foreach ($gradeoptionsfull as $value => $option) {
193 // Slightly fuzzy test, never check floats for equality.
194 if (abs($grade - $value) < 0.00001) {
195 return $value; // Be sure the return the proper value.
198 // Didn't find a match so that's an error.
201 } else if ($matchgrades == 'nearest') {
202 // Work out nearest value
205 foreach ($gradeoptionsfull as $value => $option) {
206 $newmismatch = abs($grade - $value);
207 if ($newmismatch < $bestmismatch) {
209 $bestmismatch = $newmismatch;
215 // Unknow option passed.
216 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
217 ' passed to match_grade_options');
222 * Remove stale questions from a category.
224 * While questions should not be left behind when they are not used any more,
225 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
226 * this happens, the users are unable to delete the question category unless
227 * they move those stale questions to another one category, but to them the
228 * category is empty as it does not contain anything. The purpose of this function
229 * is to detect the questions that may have gone stale and remove them.
231 * You will typically use this prior to checking if the category contains questions.
233 * The stale questions (unused and hidden to the user) handled are:
237 * @param int $categoryid The category ID.
239 function question_remove_stale_questions_from_category($categoryid) {
242 $select = 'category = :categoryid AND (qtype = :qtype OR hidden = :hidden)';
243 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'hidden' => 1];
244 $questions = $DB->get_recordset_select("question", $select, $params, '', 'id');
245 foreach ($questions as $question) {
246 // The function question_delete_question does not delete questions in use.
247 question_delete_question($question->id
);
253 * Category is about to be deleted,
254 * 1/ All questions are deleted for this question category.
255 * 2/ Any questions that can't be deleted are moved to a new category
256 * NOTE: this function is called from lib/db/upgrade.php
258 * @param object|core_course_category $category course category object
260 function question_category_delete_safe($category) {
262 $criteria = array('category' => $category->id
);
263 $context = context
::instance_by_id($category->contextid
, IGNORE_MISSING
);
264 $rescue = null; // See the code around the call to question_save_from_deletion.
266 // Deal with any questions in the category.
267 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
269 // Try to delete each question.
270 foreach ($questions as $question) {
271 question_delete_question($question->id
);
274 // Check to see if there were any questions that were kept because
275 // they are still in use somehow, even though quizzes in courses
276 // in this category will already have been deleted. This could
277 // happen, for example, if questions are added to a course,
278 // and then that course is moved to another category (MDL-14802).
279 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
280 if (!empty($questionids)) {
281 $parentcontextid = SYSCONTEXTID
;
282 $name = get_string('unknown', 'question');
283 if ($context !== false) {
284 $name = $context->get_context_name();
285 $parentcontext = $context->get_parent_context();
286 if ($parentcontext) {
287 $parentcontextid = $parentcontext->id
;
290 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
294 // Now delete the category.
295 $DB->delete_records('question_categories', array('id' => $category->id
));
299 * Tests whether any question in a category is used by any part of Moodle.
301 * @param integer $categoryid a question category id.
302 * @param boolean $recursive whether to check child categories too.
303 * @return boolean whether any question in this category is in use.
305 function question_category_in_use($categoryid, $recursive = false) {
308 //Look at each question in the category
309 if ($questions = $DB->get_records_menu('question',
310 array('category' => $categoryid), '', 'id, 1')) {
311 if (questions_in_use(array_keys($questions))) {
319 //Look under child categories recursively
320 if ($children = $DB->get_records('question_categories',
321 array('parent' => $categoryid), '', 'id, 1')) {
322 foreach ($children as $child) {
323 if (question_category_in_use($child->id
, $recursive)) {
333 * Deletes question and all associated data from the database
335 * It will not delete a question if it is used somewhere.
337 * @param object $question The question being deleted
339 function question_delete_question($questionid) {
342 $question = $DB->get_record_sql('
343 SELECT q.*, ctx.id AS contextid
345 LEFT JOIN {question_categories} qc ON qc.id = q.category
346 LEFT JOIN {context} ctx ON ctx.id = qc.contextid
347 WHERE q.id = ?', array($questionid));
349 // In some situations, for example if this was a child of a
350 // Cloze question that was previously deleted, the question may already
351 // have gone. In this case, just do nothing.
355 // Do not delete a question if it is used by an activity module
356 if (questions_in_use(array($questionid))) {
360 // This sometimes happens in old sites with bad data.
361 if (!$question->contextid
) {
362 debugging('Deleting question ' . $question->id
. ' which is no longer linked to a context. ' .
363 'Assuming system context to avoid errors, but this may mean that some data like files, ' .
364 'tags, are not cleaned up.');
365 $question->contextid
= context_system
::instance()->id
;
368 // Delete previews of the question.
369 $dm = new question_engine_data_mapper();
370 $dm->delete_previews($questionid);
372 // delete questiontype-specific data
373 question_bank
::get_qtype($question->qtype
, false)->delete_question(
374 $questionid, $question->contextid
);
376 // Delete all tag instances.
377 core_tag_tag
::remove_all_item_tags('core_question', 'question', $question->id
);
379 // Now recursively delete all child questions
380 if ($children = $DB->get_records('question',
381 array('parent' => $questionid), '', 'id, qtype')) {
382 foreach ($children as $child) {
383 if ($child->id
!= $questionid) {
384 question_delete_question($child->id
);
389 // Finally delete the question record itself
390 $DB->delete_records('question', array('id' => $questionid));
391 question_bank
::notify_question_edited($questionid);
393 // Log the deletion of this question.
394 $event = \core\event\question_deleted
::create_from_question_instance($question);
395 $event->add_record_snapshot('question', $question);
400 * All question categories and their questions are deleted for this context id.
402 * @param object $contextid The contextid to delete question categories from
403 * @return array Feedback from deletes (if any)
405 function question_delete_context($contextid) {
408 //To store feedback to be showed at the end of the process
409 $feedbackdata = array();
412 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
413 $fields = 'id, parent, name, contextid';
414 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
415 //Sort categories following their tree (parent-child) relationships
416 //this will make the feedback more readable
417 $categories = sort_categories_by_tree($categories);
419 foreach ($categories as $category) {
420 question_category_delete_safe($category);
423 $feedbackdata[] = array($category->name
, $strcatdeleted);
426 return $feedbackdata;
430 * All question categories and their questions are deleted for this course.
432 * @param stdClass $course an object representing the activity
433 * @param boolean $feedback to specify if the process must output a summary of its work
436 function question_delete_course($course, $feedback=true) {
437 $coursecontext = context_course
::instance($course->id
);
438 $feedbackdata = question_delete_context($coursecontext->id
, $feedback);
440 // Inform about changes performed if feedback is enabled.
441 if ($feedback && $feedbackdata) {
442 $table = new html_table();
443 $table->head
= array(get_string('category', 'question'), get_string('action'));
444 $table->data
= $feedbackdata;
445 echo html_writer
::table($table);
451 * Category is about to be deleted,
452 * 1/ All question categories and their questions are deleted for this course category.
453 * 2/ All questions are moved to new category
455 * @param object|core_course_category $category course category object
456 * @param object|core_course_category $newcategory empty means everything deleted, otherwise id of
457 * category where content moved
458 * @param boolean $feedback to specify if the process must output a summary of its work
461 function question_delete_course_category($category, $newcategory, $feedback=true) {
464 $context = context_coursecat
::instance($category->id
);
465 if (empty($newcategory)) {
466 $feedbackdata = question_delete_context($context->id
, $feedback);
468 // Output feedback if requested.
469 if ($feedback && $feedbackdata) {
470 $table = new html_table();
471 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
472 $table->data
= $feedbackdata;
473 echo html_writer
::table($table);
477 // Move question categories to the new context.
478 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
482 // Only move question categories if there is any question category at all!
483 if ($topcategory = question_get_top_category($context->id
)) {
484 $newtopcategory = question_get_top_category($newcontext->id
, true);
486 question_move_category_to_context($topcategory->id
, $context->id
, $newcontext->id
);
487 $DB->set_field('question_categories', 'parent', $newtopcategory->id
, array('parent' => $topcategory->id
));
488 // Now delete the top category.
489 $DB->delete_records('question_categories', array('id' => $topcategory->id
));
494 $a->oldplace
= $context->get_context_name();
495 $a->newplace
= $newcontext->get_context_name();
496 echo $OUTPUT->notification(
497 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
505 * Enter description here...
507 * @param array $questionids of question ids
508 * @param object $newcontextid the context to create the saved category in.
509 * @param string $oldplace a textual description of the think being deleted,
510 * e.g. from get_context_name
511 * @param object $newcategory
512 * @return mixed false on
514 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
515 $newcategory = null) {
518 // Make a category in the parent context to move the questions to.
519 if (is_null($newcategory)) {
520 $newcategory = new stdClass();
521 $newcategory->parent
= question_get_top_category($newcontextid, true)->id
;
522 $newcategory->contextid
= $newcontextid;
523 // Max length of column name in question_categories is 255.
524 $newcategory->name
= shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
525 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
526 $newcategory->sortorder
= 999;
527 $newcategory->stamp
= make_unique_id_code();
528 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
531 // Move any remaining questions to the 'saved' category.
532 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
539 * All question categories and their questions are deleted for this activity.
541 * @param object $cm the course module object representing the activity
542 * @param boolean $feedback to specify if the process must output a summary of its work
545 function question_delete_activity($cm, $feedback=true) {
548 $modcontext = context_module
::instance($cm->id
);
549 $feedbackdata = question_delete_context($modcontext->id
, $feedback);
550 // Inform about changes performed if feedback is enabled.
551 if ($feedback && $feedbackdata) {
552 $table = new html_table();
553 $table->head
= array(get_string('category', 'question'), get_string('action'));
554 $table->data
= $feedbackdata;
555 echo html_writer
::table($table);
561 * This function will handle moving all tag instances to a new context for a
562 * given list of questions.
564 * Questions can be tagged in up to two contexts:
565 * 1.) The context the question exists in.
566 * 2.) The course context (if the question context is a higher context.
567 * E.g. course category context or system context.
569 * This means a question that exists in a higher context (e.g. course cat or
570 * system context) may have multiple groups of tags in any number of child
573 * Questions in the course category context can be move "down" a context level
574 * into one of their child course contexts or activity contexts which affects the
575 * availability of that question in other courses / activities.
577 * In this case it makes the questions no longer available in the other course or
578 * activity contexts so we need to make sure that the tag instances in those other
579 * contexts are removed.
581 * @param stdClass[] $questions The list of question being moved (must include
582 * the id and contextid)
583 * @param context $newcontext The Moodle context the questions are being moved to
585 function question_move_question_tags_to_new_context(array $questions, context
$newcontext) {
586 // If the questions are moving to a new course/activity context then we need to
587 // find any existing tag instances from any unavailable course contexts and
588 // delete them because they will no longer be applicable (we don't support
589 // tagging questions across courses).
590 $instancestodelete = [];
591 $instancesfornewcontext = [];
592 $newcontextparentids = $newcontext->get_parent_context_ids();
593 $questionids = array_map(function($question) {
594 return $question->id
;
596 $questionstagobjects = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
598 foreach ($questions as $question) {
599 $tagobjects = $questionstagobjects[$question->id
] ??
[];
601 foreach ($tagobjects as $tagobject) {
602 $tagid = $tagobject->taginstanceid
;
603 $tagcontextid = $tagobject->taginstancecontextid
;
604 $istaginnewcontext = $tagcontextid == $newcontext->id
;
605 $istaginquestioncontext = $tagcontextid == $question->contextid
;
607 if ($istaginnewcontext) {
608 // This tag instance is already in the correct context so we can
613 if ($istaginquestioncontext) {
614 // This tag instance is in the question context so it needs to be
616 $instancesfornewcontext[] = $tagid;
620 // These tag instances are in neither the new context nor the
621 // question context so we need to determine what to do based on
622 // the context they are in and the new question context.
623 $tagcontext = context
::instance_by_id($tagcontextid);
624 $tagcoursecontext = $tagcontext->get_course_context(false);
625 // The tag is in a course context if get_course_context() returns
627 $istaginstancecontextcourse = !empty($tagcoursecontext)
628 && $tagcontext->id
== $tagcoursecontext->id
;
630 if ($istaginstancecontextcourse) {
631 // If the tag instance is in a course context we need to add some
633 $tagcontextparentids = $tagcontext->get_parent_context_ids();
634 $isnewcontextaparent = in_array($newcontext->id
, $tagcontextparentids);
635 $isnewcontextachild = in_array($tagcontext->id
, $newcontextparentids);
637 if ($isnewcontextaparent) {
638 // If the tag instance is a course context tag and the new
639 // context is still a parent context to the tag context then
640 // we can leave this tag where it is.
642 } else if ($isnewcontextachild) {
643 // If the new context is a child context (e.g. activity) of this
644 // tag instance then we should move all of this tag instance
645 // down into the activity context along with the question.
646 $instancesfornewcontext[] = $tagid;
648 // If the tag is in a course context that is no longer a parent
649 // or child of the new context then this tag instance should be
651 $instancestodelete[] = $tagid;
654 // This is a catch all for any tag instances not in the question
655 // context or a course context. These tag instances should be
656 // updated to the new context id. This will clean up old invalid
658 $instancesfornewcontext[] = $tagid;
663 if (!empty($instancestodelete)) {
664 // Delete any course context tags that may no longer be valid.
665 core_tag_tag
::delete_instances_by_id($instancestodelete);
668 if (!empty($instancesfornewcontext)) {
669 // Update the tag instances to the new context id.
670 core_tag_tag
::change_instances_context($instancesfornewcontext, $newcontext);
675 * This function should be considered private to the question bank, it is called from
676 * question/editlib.php question/contextmoveq.php and a few similar places to to the
677 * work of actually moving questions and associated data. However, callers of this
678 * function also have to do other work, which is why you should not call this method
679 * directly from outside the questionbank.
681 * @param array $questionids of question ids.
682 * @param integer $newcategoryid the id of the category to move to.
684 function question_move_questions_to_category($questionids, $newcategoryid) {
687 $newcontextid = $DB->get_field('question_categories', 'contextid',
688 array('id' => $newcategoryid));
689 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
690 $questions = $DB->get_records_sql("
691 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
693 JOIN {question_categories} qc ON q.category = qc.id
694 WHERE q.id $questionidcondition", $params);
695 foreach ($questions as $question) {
696 if ($newcontextid != $question->contextid
) {
697 question_bank
::get_qtype($question->qtype
)->move_files(
698 $question->id
, $question->contextid
, $newcontextid);
700 // Check whether there could be a clash of idnumbers in the new category.
701 if (((string) $question->idnumber
!== '') &&
702 $DB->record_exists('question', ['idnumber' => $question->idnumber
, 'category' => $newcategoryid])) {
703 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
704 [$newcategoryid, $question->idnumber
. '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
708 $idnumber = $rec->idnumber
;
709 if (strpos($idnumber, '_') !== false) {
710 $unique = substr($idnumber, strpos($idnumber, '_') +
1) +
1;
713 // For the move process, add a numerical increment to the idnumber. This means that if a question is
714 // mistakenly moved then the idnumber will not be completely lost.
716 $q->id
= $question->id
;
717 $q->category
= $newcategoryid;
718 $q->idnumber
= $question->idnumber
. '_' . $unique;
719 $DB->update_record('question', $q);
722 // Log this question move.
723 $event = \core\event\question_moved
::create_from_question_instance($question, context
::instance_by_id($question->contextid
),
724 ['oldcategoryid' => $question->category
, 'newcategoryid' => $newcategoryid]);
728 // Move the questions themselves.
729 $DB->set_field_select('question', 'category', $newcategoryid,
730 "id $questionidcondition", $params);
732 // Move any subquestions belonging to them.
733 $DB->set_field_select('question', 'category', $newcategoryid,
734 "parent $questionidcondition", $params);
736 $newcontext = context
::instance_by_id($newcontextid);
737 question_move_question_tags_to_new_context($questions, $newcontext);
739 // TODO Deal with datasets.
741 // Purge these questions from the cache.
742 foreach ($questions as $question) {
743 question_bank
::notify_question_edited($question->id
);
750 * This function helps move a question cateogry to a new context by moving all
751 * the files belonging to all the questions to the new context.
752 * Also moves subcategories.
753 * @param integer $categoryid the id of the category being moved.
754 * @param integer $oldcontextid the old context id.
755 * @param integer $newcontextid the new context id.
757 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
761 $questionids = $DB->get_records_menu('question',
762 array('category' => $categoryid), '', 'id,qtype');
763 foreach ($questionids as $questionid => $qtype) {
764 question_bank
::get_qtype($qtype)->move_files(
765 $questionid, $oldcontextid, $newcontextid);
766 // Purge this question from the cache.
767 question_bank
::notify_question_edited($questionid);
769 $questions[] = (object) [
771 'contextid' => $oldcontextid
775 $newcontext = context
::instance_by_id($newcontextid);
776 question_move_question_tags_to_new_context($questions, $newcontext);
778 $subcatids = $DB->get_records_menu('question_categories',
779 array('parent' => $categoryid), '', 'id,1');
780 foreach ($subcatids as $subcatid => $notused) {
781 $DB->set_field('question_categories', 'contextid', $newcontextid,
782 array('id' => $subcatid));
783 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
788 * Generate the URL for starting a new preview of a given question with the given options.
789 * @param integer $questionid the question to preview.
790 * @param string $preferredbehaviour the behaviour to use for the preview.
791 * @param float $maxmark the maximum to mark the question out of.
792 * @param question_display_options $displayoptions the display options to use.
793 * @param int $variant the variant of the question to preview. If null, one will
794 * be picked randomly.
795 * @param object $context context to run the preview in (affects things like
796 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
797 * @return moodle_url the URL.
799 function question_preview_url($questionid, $preferredbehaviour = null,
800 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
802 $params = array('id' => $questionid);
804 if (is_null($context)) {
806 $context = $PAGE->context
;
808 if ($context->contextlevel
== CONTEXT_MODULE
) {
809 $params['cmid'] = $context->instanceid
;
810 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
811 $params['courseid'] = $context->instanceid
;
814 if (!is_null($preferredbehaviour)) {
815 $params['behaviour'] = $preferredbehaviour;
818 if (!is_null($maxmark)) {
819 $params['maxmark'] = format_float($maxmark, -1);
822 if (!is_null($displayoptions)) {
823 $params['correctness'] = $displayoptions->correctness
;
824 $params['marks'] = $displayoptions->marks
;
825 $params['markdp'] = $displayoptions->markdp
;
826 $params['feedback'] = (bool) $displayoptions->feedback
;
827 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
828 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
829 $params['history'] = (bool) $displayoptions->history
;
833 $params['variant'] = $variant;
836 return new moodle_url('/question/preview.php', $params);
840 * @return array that can be passed as $params to the {@link popup_action} constructor.
842 function question_preview_popup_params() {
850 * Given a list of ids, load the basic information about a set of questions from
851 * the questions table. The $join and $extrafields arguments can be used together
852 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
853 * read the code below to see how the SQL is assembled. Throws exceptions on error.
855 * @param array $questionids array of question ids to load. If null, then all
856 * questions matched by $join will be loaded.
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 must use named placeholders.
861 * @param string $orderby what to order the results by. Optional, default is unspecified order.
863 * @return array partially complete question objects. You need to call get_question_options
864 * on them before they can be properly used.
866 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
867 $extraparams = array(), $orderby = '') {
870 if ($questionids === null) {
874 if (empty($questionids)) {
878 list($questionidcondition, $params) = $DB->get_in_or_equal(
879 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
880 $where = 'WHERE q.id ' . $questionidcondition;
884 $join = 'JOIN ' . $join;
888 $extrafields = ', ' . $extrafields;
892 $orderby = 'ORDER BY ' . $orderby;
895 $sql = "SELECT q.*, qc.contextid{$extrafields}
897 JOIN {question_categories} qc ON q.category = qc.id
902 // Load the questions.
903 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
904 foreach ($questions as $question) {
905 $question->_partiallyloaded
= true;
912 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
913 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
914 * read the code below to see how the SQL is assembled. Throws exceptions on error.
916 * @param array $questionids array of question ids.
917 * @param string $extrafields extra SQL code to be added to the query.
918 * @param string $join extra SQL code to be added to the query.
919 * @param array $extraparams values for any placeholders in $join.
920 * You are strongly recommended to use named placeholder.
922 * @return array question objects.
924 function question_load_questions($questionids, $extrafields = '', $join = '') {
925 $questions = question_preload_questions($questionids, $extrafields, $join);
927 // Load the question type specific information
928 if (!get_question_options($questions)) {
929 return 'Could not load the question options';
936 * Private function to factor common code out of get_question_options().
938 * @param object $question the question to tidy.
939 * @param stdClass $category The question_categories record for the given $question.
940 * @param stdClass[]|null $tagobjects The tags for the given $question.
941 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
943 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
944 // Load question-type specific fields.
945 if (!question_bank
::is_qtype_installed($question->qtype
)) {
946 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
947 'qtype_missingtype')) . $question->questiontext
;
949 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
951 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
952 $question->defaultmark +
= 0;
953 $question->penalty +
= 0;
955 if (isset($question->_partiallyloaded
)) {
956 unset($question->_partiallyloaded
);
959 $question->categoryobject
= $category;
961 if (!is_null($tagobjects)) {
962 $categorycontext = context
::instance_by_id($category->contextid
);
963 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
964 $question->coursetagobjects
= $sortedtagobjects->coursetagobjects
;
965 $question->coursetags
= $sortedtagobjects->coursetags
;
966 $question->tagobjects
= $sortedtagobjects->tagobjects
;
967 $question->tags
= $sortedtagobjects->tags
;
972 * Updates the question objects with question type specific
973 * information by calling {@link get_question_options()}
975 * Can be called either with an array of question objects or with a single
978 * @param mixed $questions Either an array of question objects to be updated
979 * or just a single question object
980 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
981 * @param stdClass[] $filtercourses The courses to filter the course tags by.
982 * @return bool Indicates success or failure.
984 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
987 $questionlist = is_array($questions) ?
$questions : [$questions];
991 if (empty($questionlist)) {
995 foreach ($questionlist as $question) {
996 $questionids[] = $question->id
;
998 if (!in_array($question->category
, $categoryids)) {
999 $categoryids[] = $question->category
;
1003 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
1005 if ($loadtags && core_tag_tag
::is_enabled('core_question', 'question')) {
1006 $tagobjectsbyquestion = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
1008 $tagobjectsbyquestion = null;
1011 foreach ($questionlist as $question) {
1012 if (is_null($tagobjectsbyquestion)) {
1015 $tagobjects = $tagobjectsbyquestion[$question->id
];
1018 _tidy_question($question, $categories[$question->category
], $tagobjects, $filtercourses);
1025 * Sort question tags by course or normal tags.
1027 * This function also search tag instances that may have a context id that don't match either a course or
1028 * question context and fix the data setting the correct context id.
1030 * @param stdClass[] $tagobjects The tags for the given $question.
1031 * @param stdClass $categorycontext The question categories context.
1032 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1033 * @return stdClass $sortedtagobjects Sorted tag objects.
1035 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
1037 // Questions can have two sets of tag instances. One set at the
1038 // course context level and another at the context the question
1039 // belongs to (e.g. course category, system etc).
1040 $sortedtagobjects = new stdClass();
1041 $sortedtagobjects->coursetagobjects
= [];
1042 $sortedtagobjects->coursetags
= [];
1043 $sortedtagobjects->tagobjects
= [];
1044 $sortedtagobjects->tags
= [];
1045 $taginstanceidstonormalise = [];
1046 $filtercoursecontextids = [];
1047 $hasfiltercourses = !empty($filtercourses);
1049 if ($hasfiltercourses) {
1050 // If we're being asked to filter the course tags by a set of courses
1051 // then get the context ids to filter below.
1052 $filtercoursecontextids = array_map(function($course) {
1053 $coursecontext = context_course
::instance($course->id
);
1054 return $coursecontext->id
;
1058 foreach ($tagobjects as $tagobject) {
1059 $tagcontextid = $tagobject->taginstancecontextid
;
1060 $tagcontext = context
::instance_by_id($tagcontextid);
1061 $tagcoursecontext = $tagcontext->get_course_context(false);
1062 // This is a course tag if the tag context is a course context which
1063 // doesn't match the question's context. Any tag in the question context
1064 // is not considered a course tag, it belongs to the question.
1065 $iscoursetag = $tagcoursecontext
1066 && $tagcontext->id
== $tagcoursecontext->id
1067 && $tagcontext->id
!= $categorycontext->id
;
1070 // Any tag instance in a course context level is considered a course tag.
1071 if (!$hasfiltercourses ||
in_array($tagcontextid, $filtercoursecontextids)) {
1072 // Add the tag to the list of course tags if we aren't being
1073 // asked to filter or if this tag is in the list of courses
1074 // we're being asked to filter by.
1075 $sortedtagobjects->coursetagobjects
[] = $tagobject;
1076 $sortedtagobjects->coursetags
[$tagobject->id
] = $tagobject->get_display_name();
1079 // All non course context level tag instances or tags in the question
1080 // context belong to the context that the question was created in.
1081 $sortedtagobjects->tagobjects
[] = $tagobject;
1082 $sortedtagobjects->tags
[$tagobject->id
] = $tagobject->get_display_name();
1084 // Due to legacy tag implementations that don't force the recording
1085 // of a context id, some tag instances may have context ids that don't
1086 // match either a course context or the question context. In this case
1087 // we should take the opportunity to fix up the data and set the correct
1089 if ($tagcontext->id
!= $categorycontext->id
) {
1090 $taginstanceidstonormalise[] = $tagobject->taginstanceid
;
1091 // Update the object properties to reflect the DB update that will
1093 $tagobject->taginstancecontextid
= $categorycontext->id
;
1098 if (!empty($taginstanceidstonormalise)) {
1099 // If we found any tag instances with incorrect context id data then we can
1100 // correct those values now by setting them to the question context id.
1101 core_tag_tag
::change_instances_context($taginstanceidstonormalise, $categorycontext);
1104 return $sortedtagobjects;
1108 * Print the icon for the question type
1110 * @param object $question The question object for which the icon is required.
1111 * Only $question->qtype is used.
1112 * @return string the HTML for the img tag.
1114 function print_question_icon($question) {
1116 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
1120 * Creates a stamp that uniquely identifies this version of the question
1122 * In future we want this to use a hash of the question data to guarantee that
1123 * identical versions have the same version stamp.
1125 * @param object $question
1126 * @return string A unique version stamp
1128 function question_hash($question) {
1129 return make_unique_id_code();
1132 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1135 * returns the categories with their names ordered following parent-child relationships
1136 * finally it tries to return pending categories (those being orphaned, whose parent is
1137 * incorrect) to avoid missing any category from original array.
1139 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1142 $children = array();
1143 $keys = array_keys($categories);
1145 foreach ($keys as $key) {
1146 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1147 $children[$key] = $categories[$key];
1148 $categories[$key]->processed
= true;
1149 $children = $children +
sort_categories_by_tree(
1150 $categories, $children[$key]->id
, $level+
1);
1153 //If level = 1, we have finished, try to look for non processed categories
1154 // (bad parent) and sort them too
1156 foreach ($keys as $key) {
1157 // If not processed and it's a good candidate to start (because its
1158 // parent doesn't exist in the course)
1159 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
1160 array('contextid' => $categories[$key]->contextid
,
1161 'id' => $categories[$key]->parent
))) {
1162 $children[$key] = $categories[$key];
1163 $categories[$key]->processed
= true;
1164 $children = $children +
sort_categories_by_tree(
1165 $categories, $children[$key]->id
, $level +
1);
1173 * Private method, only for the use of add_indented_names().
1175 * Recursively adds an indentedname field to each category, starting with the category
1176 * with id $id, and dealing with that category and all its children, and
1177 * return a new array, with those categories in the right order.
1179 * @param array $categories an array of categories which has had childids
1180 * fields added by flatten_category_tree(). Passed by reference for
1181 * performance only. It is not modfied.
1182 * @param int $id the category to start the indenting process from.
1183 * @param int $depth the indent depth. Used in recursive calls.
1184 * @return array a new array of categories, in the right order for the tree.
1186 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1188 // Indent the name of this category.
1189 $newcategories = array();
1190 $newcategories[$id] = $categories[$id];
1191 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
1192 $categories[$id]->name
;
1194 // Recursively indent the children.
1195 foreach ($categories[$id]->childids
as $childid) {
1196 if ($childid != $nochildrenof) {
1197 $newcategories = $newcategories +
flatten_category_tree(
1198 $categories, $childid, $depth +
1, $nochildrenof);
1202 // Remove the childids array that were temporarily added.
1203 unset($newcategories[$id]->childids
);
1205 return $newcategories;
1209 * Format categories into an indented list reflecting the tree structure.
1211 * @param array $categories An array of category objects, for example from the.
1212 * @return array The formatted list of categories.
1214 function add_indented_names($categories, $nochildrenof = -1) {
1216 // Add an array to each category to hold the child category ids. This array
1217 // will be removed again by flatten_category_tree(). It should not be used
1218 // outside these two functions.
1219 foreach (array_keys($categories) as $id) {
1220 $categories[$id]->childids
= array();
1223 // Build the tree structure, and record which categories are top-level.
1224 // We have to be careful, because the categories array may include published
1225 // categories from other courses, but not their parents.
1226 $toplevelcategoryids = array();
1227 foreach (array_keys($categories) as $id) {
1228 if (!empty($categories[$id]->parent
) &&
1229 array_key_exists($categories[$id]->parent
, $categories)) {
1230 $categories[$categories[$id]->parent
]->childids
[] = $id;
1232 $toplevelcategoryids[] = $id;
1236 // Flatten the tree to and add the indents.
1237 $newcategories = array();
1238 foreach ($toplevelcategoryids as $id) {
1239 $newcategories = $newcategories +
flatten_category_tree(
1240 $categories, $id, 0, $nochildrenof);
1243 return $newcategories;
1247 * Output a select menu of question categories.
1249 * Categories from this course and (optionally) published categories from other courses
1250 * are included. Optionally, only categories the current user may edit can be included.
1252 * @param integer $courseid the id of the course to get the categories for.
1253 * @param integer $published if true, include publised categories from other courses.
1254 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1255 * @param integer $selected optionally, the id of a category to be selected by
1256 * default in the dropdown.
1258 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1259 $selected = "", $nochildrenof = -1) {
1260 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1261 false, $nochildrenof);
1265 $choose = 'choosedots';
1268 foreach ($categoriesarray as $group => $opts) {
1269 $options[] = array($group => $opts);
1271 echo html_writer
::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1273 'id' => 'id_movetocategory',
1274 'class' => 'custom-select',
1275 'data-action' => 'toggle',
1276 'data-togglegroup' => 'qbank',
1277 'data-toggle' => 'action',
1280 echo html_writer
::select($options, 'category', $selected, $choose, $attrs);
1284 * @param integer $contextid a context id.
1285 * @return object the default question category for that context, or false if none.
1287 function question_get_default_category($contextid) {
1289 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1290 array($contextid), 'id', '*', 0, 1);
1291 if (!empty($category)) {
1292 return reset($category);
1299 * Gets the top category in the given context.
1300 * This function can optionally create the top category if it doesn't exist.
1302 * @param int $contextid A context id.
1303 * @param bool $create Whether create a top category if it doesn't exist.
1304 * @return bool|stdClass The top question category for that context, or false if none.
1306 function question_get_top_category($contextid, $create = false) {
1308 $category = $DB->get_record('question_categories',
1309 array('contextid' => $contextid, 'parent' => 0));
1311 if (!$category && $create) {
1312 // We need to make one.
1313 $category = new stdClass();
1314 $category->name
= 'top'; // A non-real name for the top category. It will be localised at the display time.
1315 $category->info
= '';
1316 $category->contextid
= $contextid;
1317 $category->parent
= 0;
1318 $category->sortorder
= 0;
1319 $category->stamp
= make_unique_id_code();
1320 $category->id
= $DB->insert_record('question_categories', $category);
1327 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1329 * @param array $contextids List of context ids
1332 function question_get_top_categories_for_contexts($contextids) {
1335 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1336 list($insql, $params) = $DB->get_in_or_equal($contextids);
1337 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1338 $topcategories = $DB->get_fieldset_sql($sql, $params);
1340 return $topcategories;
1344 * Gets the default category in the most specific context.
1345 * If no categories exist yet then default ones are created in all contexts.
1347 * @param array $contexts The context objects for this context and all parent contexts.
1348 * @return object The default category - the category in the course context
1350 function question_make_default_categories($contexts) {
1352 static $preferredlevels = array(
1353 CONTEXT_COURSE
=> 4,
1354 CONTEXT_MODULE
=> 3,
1355 CONTEXT_COURSECAT
=> 2,
1356 CONTEXT_SYSTEM
=> 1,
1361 // If it already exists, just return it.
1362 foreach ($contexts as $key => $context) {
1363 $topcategory = question_get_top_category($context->id
, true);
1364 if (!$exists = $DB->record_exists("question_categories",
1365 array('contextid' => $context->id
, 'parent' => $topcategory->id
))) {
1366 // Otherwise, we need to make one
1367 $category = new stdClass();
1368 $contextname = $context->get_context_name(false, true);
1369 // Max length of name field is 255.
1370 $category->name
= shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1371 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1372 $category->contextid
= $context->id
;
1373 $category->parent
= $topcategory->id
;
1374 // By default, all categories get this number, and are sorted alphabetically.
1375 $category->sortorder
= 999;
1376 $category->stamp
= make_unique_id_code();
1377 $category->id
= $DB->insert_record('question_categories', $category);
1379 $category = question_get_default_category($context->id
);
1381 $thispreferredness = $preferredlevels[$context->contextlevel
];
1382 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1383 $thispreferredness +
= 10;
1385 if ($thispreferredness > $preferredness) {
1386 $toreturn = $category;
1387 $preferredness = $thispreferredness;
1391 if (!is_null($toreturn)) {
1392 $toreturn = clone($toreturn);
1398 * Get all the category objects, including a count of the number of questions in that category,
1399 * for all the categories in the lists $contexts.
1401 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1402 * @param string $sortorder used as the ORDER BY clause in the select statement.
1403 * @param bool $top Whether to return the top categories or not.
1404 * @return array of category objects.
1406 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1408 $topwhere = $top ?
'' : 'AND c.parent <> 0';
1409 return $DB->get_records_sql("
1410 SELECT c.*, (SELECT count(1) FROM {question} q
1411 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1412 FROM {question_categories} c
1413 WHERE c.contextid IN ($contexts) $topwhere
1414 ORDER BY $sortorder");
1418 * Output an array of question categories.
1420 * @param array $contexts The list of contexts.
1421 * @param bool $top Whether to return the top categories or not.
1422 * @param int $currentcat
1423 * @param bool $popupform
1424 * @param int $nochildrenof
1427 function question_category_options($contexts, $top = false, $currentcat = 0,
1428 $popupform = false, $nochildrenof = -1) {
1430 $pcontexts = array();
1431 foreach ($contexts as $context) {
1432 $pcontexts[] = $context->id
;
1434 $contextslist = join(', ', $pcontexts);
1436 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1439 $categories = question_fix_top_names($categories);
1442 $categories = question_add_context_in_key($categories);
1443 $categories = add_indented_names($categories, $nochildrenof);
1445 // sort cats out into different contexts
1446 $categoriesarray = array();
1447 foreach ($pcontexts as $contextid) {
1448 $context = context
::instance_by_id($contextid);
1449 $contextstring = $context->get_context_name(true, true);
1450 foreach ($categories as $category) {
1451 if ($category->contextid
== $contextid) {
1452 $cid = $category->id
;
1453 if ($currentcat != $cid ||
$currentcat == 0) {
1455 $a->name
= format_string($category->indentedname
, true,
1456 array('context' => $context));
1457 if ($category->idnumber
!== null && $category->idnumber
!== '') {
1458 $a->idnumber
= s($category->idnumber
);
1460 if (!empty($category->questioncount
)) {
1461 $a->questioncount
= $category->questioncount
;
1463 if (isset($a->idnumber
) && isset($a->questioncount
)) {
1464 $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
1465 } else if (isset($a->idnumber
)) {
1466 $formattedname = get_string('categorynamewithidnumber', 'question', $a);
1467 } else if (isset($a->questioncount
)) {
1468 $formattedname = get_string('categorynamewithcount', 'question', $a);
1470 $formattedname = $a->name
;
1472 $categoriesarray[$contextstring][$cid] = $formattedname;
1478 $popupcats = array();
1479 foreach ($categoriesarray as $contextstring => $optgroup) {
1481 foreach ($optgroup as $key => $value) {
1482 $key = str_replace($CFG->wwwroot
, '', $key);
1483 $group[$key] = $value;
1485 $popupcats[] = array($contextstring => $group);
1489 return $categoriesarray;
1493 function question_add_context_in_key($categories) {
1494 $newcatarray = array();
1495 foreach ($categories as $id => $category) {
1496 $category->parent
= "$category->parent,$category->contextid";
1497 $category->id
= "$category->id,$category->contextid";
1498 $newcatarray["$id,$category->contextid"] = $category;
1500 return $newcatarray;
1504 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1506 * @param array $categories An array of question categories.
1507 * @return array The same question category list given to the function, with the top category names being translated.
1509 function question_fix_top_names($categories) {
1511 foreach ($categories as $id => $category) {
1512 if ($category->parent
== 0) {
1513 $context = context
::instance_by_id($category->contextid
);
1514 $categories[$id]->name
= get_string('topfor', 'question', $context->get_context_name(false));
1522 * @return array of question category ids of the category and all subcategories.
1524 function question_categorylist($categoryid) {
1527 // final list of category IDs
1528 $categorylist = array();
1530 // a list of category IDs to check for any sub-categories
1531 $subcategories = array($categoryid);
1533 while ($subcategories) {
1534 foreach ($subcategories as $subcategory) {
1535 // if anything from the temporary list was added already, then we have a loop
1536 if (isset($categorylist[$subcategory])) {
1537 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1539 $categorylist[$subcategory] = $subcategory;
1542 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1544 $subcategories = $DB->get_records_select_menu('question_categories',
1545 "parent $in", $params, NULL, 'id,id AS id2');
1548 return $categorylist;
1552 * Get all parent categories of a given question category in decending order.
1553 * @param int $categoryid for which you want to find the parents.
1554 * @return array of question category ids of all parents categories.
1556 function question_categorylist_parents(int $categoryid) {
1558 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1562 $categorylist = [$parent];
1563 $currentid = $parent;
1564 while ($currentid) {
1565 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1567 $categorylist[] = $currentid;
1570 // Present the list in decending order (the top category at the top).
1571 $categorylist = array_reverse($categorylist);
1572 return $categorylist;
1575 //===========================
1576 // Import/Export Functions
1577 //===========================
1580 * Get list of available import or export formats
1581 * @param string $type 'import' if import list, otherwise export list assumed
1582 * @return array sorted list of import/export formats available
1584 function get_import_export_formats($type) {
1586 require_once($CFG->dirroot
. '/question/format.php');
1588 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1590 $fileformatname = array();
1591 foreach ($formatclasses as $component => $formatclass) {
1593 $format = new $formatclass();
1594 if ($type == 'import') {
1595 $provided = $format->provide_import();
1597 $provided = $format->provide_export();
1601 list($notused, $fileformat) = explode('_', $component, 2);
1602 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1606 core_collator
::asort($fileformatnames);
1607 return $fileformatnames;
1612 * Create a reasonable default file name for exporting questions from a particular
1614 * @param object $course the course the questions are in.
1615 * @param object $category the question category.
1616 * @return string the filename.
1618 function question_default_export_filename($course, $category) {
1619 // We build a string that is an appropriate name (questions) from the lang pack,
1620 // then the corse shortname, then the question category name, then a timestamp.
1622 $base = clean_filename(get_string('exportfilename', 'question'));
1624 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1625 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1627 $shortname = clean_filename($course->shortname
);
1628 if ($shortname == '' ||
$shortname == '_' ) {
1629 $shortname = $course->id
;
1632 $categoryname = clean_filename(format_string($category->name
));
1634 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1636 return $export_name;
1640 * Converts contextlevels to strings and back to help with reading/writing contexts
1641 * to/from import/export files.
1643 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1646 class context_to_string_translator
{
1648 * @var array used to translate between contextids and strings for this context.
1650 protected $contexttostringarray = array();
1652 public function __construct($contexts) {
1653 $this->generate_context_to_string_array($contexts);
1656 public function context_to_string($contextid) {
1657 return $this->contexttostringarray
[$contextid];
1660 public function string_to_context($contextname) {
1661 $contextid = array_search($contextname, $this->contexttostringarray
);
1665 protected function generate_context_to_string_array($contexts) {
1666 if (!$this->contexttostringarray
) {
1668 foreach ($contexts as $context) {
1669 switch ($context->contextlevel
) {
1670 case CONTEXT_MODULE
:
1671 $contextstring = 'module';
1673 case CONTEXT_COURSE
:
1674 $contextstring = 'course';
1676 case CONTEXT_COURSECAT
:
1677 $contextstring = "cat$catno";
1680 case CONTEXT_SYSTEM
:
1681 $contextstring = 'system';
1684 $this->contexttostringarray
[$context->id
] = $contextstring;
1692 * Check capability on category
1694 * @param int|stdClass|question_definition $questionorid object or id.
1695 * If an object is passed, it should include ->contextid and ->createdby.
1696 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1697 * @param int $notused no longer used.
1698 * @return bool this user has the capability $cap for this question $question?
1699 * @throws coding_exception
1701 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1704 if (is_numeric($questionorid)) {
1705 $questionid = (int)$questionorid;
1706 } else if (is_object($questionorid)) {
1707 // All we really need in this function is the contextid and author of the question.
1708 // We won't bother fetching other details of the question if these 2 fields are provided.
1709 if (isset($questionorid->contextid
) && isset($questionorid->createdby
)) {
1710 $question = $questionorid;
1711 } else if (!empty($questionorid->id
)) {
1712 $questionid = $questionorid->id
;
1716 // At this point, either $question or $questionid is expected to be set.
1717 if (isset($questionid)) {
1719 $question = question_bank
::load_question_data($questionid);
1720 } catch (Exception
$e) {
1721 // Let's log the exception for future debugging,
1722 // but not during Behat, or we can't test these cases.
1723 if (!defined('BEHAT_SITE_RUNNING')) {
1724 debugging($e->getMessage(), DEBUG_NORMAL
, $e->getTrace());
1727 // Well, at least we tried. Seems that we really have to read from DB.
1728 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1730 JOIN {question_categories} qc ON q.category = qc.id
1731 WHERE q.id = :id', ['id' => $questionid]);
1735 if (!isset($question)) {
1736 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1739 $context = context
::instance_by_id($question->contextid
);
1741 // These are existing questions capabilities that are set per category.
1742 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1743 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1745 if (!isset($capabilitieswithallandmine[$cap])) {
1746 return has_capability('moodle/question:' . $cap, $context);
1748 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1749 ($question->createdby
== $USER->id
&& has_capability('moodle/question:' . $cap . 'mine', $context));
1754 * Require capability on question.
1756 function question_require_capability_on($question, $cap) {
1757 if (!question_has_capability_on($question, $cap)) {
1758 print_error('nopermissions', '', '', $cap);
1764 * @param object $context a context
1765 * @return string A URL for editing questions in this context.
1767 function question_edit_url($context) {
1769 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1772 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1773 $defaultcategory = question_get_default_category($context->id
);
1774 if ($defaultcategory) {
1775 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1777 switch ($context->contextlevel
) {
1778 case CONTEXT_SYSTEM
:
1779 return $baseurl . 'courseid=' . $SITE->id
;
1780 case CONTEXT_COURSECAT
:
1781 // This is nasty, becuase we can only edit questions in a course
1782 // context at the moment, so for now we just return false.
1784 case CONTEXT_COURSE
:
1785 return $baseurl . 'courseid=' . $context->instanceid
;
1786 case CONTEXT_MODULE
:
1787 return $baseurl . 'cmid=' . $context->instanceid
;
1793 * Adds question bank setting links to the given navigation node if caps are met.
1795 * @param navigation_node $navigationnode The navigation node to add the question branch to
1796 * @param object $context
1797 * @return navigation_node Returns the question branch that was added
1799 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1802 if ($context->contextlevel
== CONTEXT_COURSE
) {
1803 $params = array('courseid'=>$context->instanceid
);
1804 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1805 $params = array('cmid'=>$context->instanceid
);
1810 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1811 $params['cat'] = $cat;
1814 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1815 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
, null, 'questionbank');
1817 $contexts = new question_edit_contexts($context);
1818 if ($contexts->have_one_edit_tab_cap('questions')) {
1819 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1820 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
, null, 'questions');
1822 if ($contexts->have_one_edit_tab_cap('categories')) {
1823 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1824 '/question/category.php', $params), navigation_node
::TYPE_SETTING
, null, 'categories');
1826 if ($contexts->have_one_edit_tab_cap('import')) {
1827 $questionnode->add(get_string('import', 'question'), new moodle_url(
1828 '/question/import.php', $params), navigation_node
::TYPE_SETTING
, null, 'import');
1830 if ($contexts->have_one_edit_tab_cap('export')) {
1831 $questionnode->add(get_string('export', 'question'), new moodle_url(
1832 '/question/export.php', $params), navigation_node
::TYPE_SETTING
, null, 'export');
1835 return $questionnode;
1839 * @return array all the capabilities that relate to accessing particular questions.
1841 function question_get_question_capabilities() {
1843 'moodle/question:add',
1844 'moodle/question:editmine',
1845 'moodle/question:editall',
1846 'moodle/question:viewmine',
1847 'moodle/question:viewall',
1848 'moodle/question:usemine',
1849 'moodle/question:useall',
1850 'moodle/question:movemine',
1851 'moodle/question:moveall',
1852 'moodle/question:tagmine',
1853 'moodle/question:tagall',
1858 * @return array all the question bank capabilities.
1860 function question_get_all_capabilities() {
1861 $caps = question_get_question_capabilities();
1862 $caps[] = 'moodle/question:managecategory';
1863 $caps[] = 'moodle/question:flag';
1869 * Tracks all the contexts related to the one where we are currently editing
1870 * questions, and provides helper methods to check permissions.
1872 * @copyright 2007 Jamie Pratt me@jamiep.org
1873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1875 class question_edit_contexts
{
1877 public static $caps = array(
1878 'editq' => array('moodle/question:add',
1879 'moodle/question:editmine',
1880 'moodle/question:editall',
1881 'moodle/question:viewmine',
1882 'moodle/question:viewall',
1883 'moodle/question:usemine',
1884 'moodle/question:useall',
1885 'moodle/question:movemine',
1886 'moodle/question:moveall'),
1887 'questions'=>array('moodle/question:add',
1888 'moodle/question:editmine',
1889 'moodle/question:editall',
1890 'moodle/question:viewmine',
1891 'moodle/question:viewall',
1892 'moodle/question:movemine',
1893 'moodle/question:moveall'),
1894 'categories'=>array('moodle/question:managecategory'),
1895 'import'=>array('moodle/question:add'),
1896 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1898 protected $allcontexts;
1902 * @param context the current context.
1904 public function __construct(context
$thiscontext) {
1905 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1909 * @return context[] all parent contexts
1911 public function all() {
1912 return $this->allcontexts
;
1916 * @return context lowest context which must be either the module or course context
1918 public function lowest() {
1919 return $this->allcontexts
[0];
1923 * @param string $cap capability
1924 * @return context[] parent contexts having capability, zero based index
1926 public function having_cap($cap) {
1927 $contextswithcap = array();
1928 foreach ($this->allcontexts
as $context) {
1929 if (has_capability($cap, $context)) {
1930 $contextswithcap[] = $context;
1933 return $contextswithcap;
1937 * @param array $caps capabilities
1938 * @return context[] parent contexts having at least one of $caps, zero based index
1940 public function having_one_cap($caps) {
1941 $contextswithacap = array();
1942 foreach ($this->allcontexts
as $context) {
1943 foreach ($caps as $cap) {
1944 if (has_capability($cap, $context)) {
1945 $contextswithacap[] = $context;
1946 break; //done with caps loop
1950 return $contextswithacap;
1954 * @param string $tabname edit tab name
1955 * @return context[] parent contexts having at least one of $caps, zero based index
1957 public function having_one_edit_tab_cap($tabname) {
1958 return $this->having_one_cap(self
::$caps[$tabname]);
1962 * @return context[] those contexts where a user can add a question and then use it.
1964 public function having_add_and_use() {
1965 $contextswithcap = array();
1966 foreach ($this->allcontexts
as $context) {
1967 if (!has_capability('moodle/question:add', $context)) {
1970 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1973 $contextswithcap[] = $context;
1975 return $contextswithcap;
1979 * Has at least one parent context got the cap $cap?
1981 * @param string $cap capability
1984 public function have_cap($cap) {
1985 return (count($this->having_cap($cap)));
1989 * Has at least one parent context got one of the caps $caps?
1991 * @param array $caps capability
1994 public function have_one_cap($caps) {
1995 foreach ($caps as $cap) {
1996 if ($this->have_cap($cap)) {
2004 * Has at least one parent context got one of the caps for actions on $tabname
2006 * @param string $tabname edit tab name
2009 public function have_one_edit_tab_cap($tabname) {
2010 return $this->have_one_cap(self
::$caps[$tabname]);
2014 * Throw error if at least one parent context hasn't got the cap $cap
2016 * @param string $cap capability
2018 public function require_cap($cap) {
2019 if (!$this->have_cap($cap)) {
2020 print_error('nopermissions', '', '', $cap);
2025 * Throw error if at least one parent context hasn't got one of the caps $caps
2027 * @param array $caps capabilities
2029 public function require_one_cap($caps) {
2030 if (!$this->have_one_cap($caps)) {
2031 $capsstring = join(', ', $caps);
2032 print_error('nopermissions', '', '', $capsstring);
2037 * Throw error if at least one parent context hasn't got one of the caps $caps
2039 * @param string $tabname edit tab name
2041 public function require_one_edit_tab_cap($tabname) {
2042 if (!$this->have_one_edit_tab_cap($tabname)) {
2043 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
2050 * Helps call file_rewrite_pluginfile_urls with the right parameters.
2052 * @package core_question
2054 * @param string $text text being processed
2055 * @param string $file the php script used to serve files
2056 * @param int $contextid context ID
2057 * @param string $component component
2058 * @param string $filearea filearea
2059 * @param array $ids other IDs will be used to check file permission
2060 * @param int $itemid item ID
2061 * @param array $options options
2064 function question_rewrite_question_urls($text, $file, $contextid, $component,
2065 $filearea, array $ids, $itemid, array $options=null) {
2069 $idsstr .= implode('/', $ids);
2071 if ($itemid !== null) {
2072 $idsstr .= '/' . $itemid;
2074 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
2075 $filearea, $idsstr, $options);
2079 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
2080 * viewing the question outside an attempt (for example, in the question bank
2081 * listing or in the quiz statistics report).
2083 * @param string $text the question text.
2084 * @param int $questionid the question id.
2085 * @param int $filecontextid the context id of the question being displayed.
2086 * @param string $filecomponent the component that owns the file area.
2087 * @param string $filearea the file area name.
2088 * @param int|null $itemid the file's itemid
2089 * @param int $previewcontextid the context id where the preview is being displayed.
2090 * @param string $previewcomponent component responsible for displaying the preview.
2091 * @param array $options text and file options ('forcehttps'=>false)
2092 * @return string $questiontext with URLs rewritten.
2094 function question_rewrite_question_preview_urls($text, $questionid,
2095 $filecontextid, $filecomponent, $filearea, $itemid,
2096 $previewcontextid, $previewcomponent, $options = null) {
2098 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2100 $path .= '/' . $itemid;
2103 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2104 $filecomponent, $filearea, $path, $options);
2108 * Called by pluginfile.php to serve files related to the 'question' core
2109 * component and for files belonging to qtypes.
2111 * For files that relate to questions in a question_attempt, then we delegate to
2112 * a function in the component that owns the attempt (for example in the quiz,
2113 * or in core question preview) to get necessary inforation.
2115 * (Note that, at the moment, all question file areas relate to questions in
2116 * attempts, so the If at the start of the last paragraph is always true.)
2118 * Does not return, either calls send_file_not_found(); or serves the file.
2120 * @package core_question
2122 * @param stdClass $course course settings object
2123 * @param stdClass $context context object
2124 * @param string $component the name of the component we are serving files for.
2125 * @param string $filearea the name of the file area.
2126 * @param array $args the remaining bits of the file path.
2127 * @param bool $forcedownload whether the user must be forced to download the file.
2128 * @param array $options additional options affecting the file serving
2130 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2133 // Special case, sending a question bank export.
2134 if ($filearea === 'export') {
2135 list($context, $course, $cm) = get_context_info_array($context->id
);
2136 require_login($course, false, $cm);
2138 require_once($CFG->dirroot
. '/question/editlib.php');
2139 $contexts = new question_edit_contexts($context);
2140 // check export capability
2141 $contexts->require_one_edit_tab_cap('export');
2142 $category_id = (int)array_shift($args);
2143 $format = array_shift($args);
2144 $cattofile = array_shift($args);
2145 $contexttofile = array_shift($args);
2146 $filename = array_shift($args);
2148 // load parent class for import/export
2149 require_once($CFG->dirroot
. '/question/format.php');
2150 require_once($CFG->dirroot
. '/question/editlib.php');
2151 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
2153 $classname = 'qformat_' . $format;
2154 if (!class_exists($classname)) {
2155 send_file_not_found();
2158 $qformat = new $classname();
2160 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2161 send_file_not_found();
2164 $qformat->setCategory($category);
2165 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2166 $qformat->setCourse($course);
2168 if ($cattofile == 'withcategories') {
2169 $qformat->setCattofile(true);
2171 $qformat->setCattofile(false);
2174 if ($contexttofile == 'withcontexts') {
2175 $qformat->setContexttofile(true);
2177 $qformat->setContexttofile(false);
2180 if (!$qformat->exportpreprocess()) {
2181 send_file_not_found();
2182 print_error('exporterror', 'question', $thispageurl->out());
2185 // export data to moodle file pool
2186 if (!$content = $qformat->exportprocess()) {
2187 send_file_not_found();
2190 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2193 // Normal case, a file belonging to a question.
2194 $qubaidorpreview = array_shift($args);
2196 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2197 if ($qubaidorpreview === 'preview') {
2198 $previewcontextid = (int)array_shift($args);
2199 $previewcomponent = array_shift($args);
2200 $questionid = (int) array_shift($args);
2201 $previewcontext = context_helper
::instance_by_id($previewcontextid);
2203 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2204 $previewcontext, $questionid,
2205 $context, $component, $filearea, $args,
2206 $forcedownload, $options), 'callbackmissing');
2208 if ($result === 'callbackmissing') {
2209 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2210 "{$previewcomponent}_question_preview_pluginfile callback. " .
2211 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER
);
2214 send_file_not_found();
2217 // 2. A question being attempted in the normal way.
2218 $qubaid = (int)$qubaidorpreview;
2219 $slot = (int)array_shift($args);
2221 $module = $DB->get_field('question_usages', 'component',
2222 array('id' => $qubaid));
2224 send_file_not_found();
2227 if ($module === 'core_question_preview') {
2228 require_once($CFG->dirroot
. '/question/previewlib.php');
2229 return question_preview_question_pluginfile($course, $context,
2230 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2233 $dir = core_component
::get_component_directory($module);
2234 if (!file_exists("$dir/lib.php")) {
2235 send_file_not_found();
2237 include_once("$dir/lib.php");
2239 $filefunction = $module . '_question_pluginfile';
2240 if (function_exists($filefunction)) {
2241 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2242 $args, $forcedownload, $options);
2245 // Okay, we're here so lets check for function without 'mod_'.
2246 if (strpos($module, 'mod_') === 0) {
2247 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2248 if (function_exists($filefunctionold)) {
2249 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2250 $args, $forcedownload, $options);
2254 send_file_not_found();
2259 * Serve questiontext files in the question text when they are displayed in this report.
2261 * @package core_files
2263 * @param context $previewcontext the context in which the preview is happening.
2264 * @param int $questionid the question id.
2265 * @param context $filecontext the file (question) context.
2266 * @param string $filecomponent the component the file belongs to.
2267 * @param string $filearea the file area.
2268 * @param array $args remaining file args.
2269 * @param bool $forcedownload.
2270 * @param array $options additional options affecting the file serving.
2272 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2273 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2276 // Verify that contextid matches the question.
2277 $question = $DB->get_record_sql('
2278 SELECT q.*, qc.contextid
2280 JOIN {question_categories} qc ON qc.id = q.category
2281 WHERE q.id = :id AND qc.contextid = :contextid',
2282 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
2284 // Check the capability.
2285 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
2286 require_login($course, false, $cm);
2288 question_require_capability_on($question, 'use');
2290 $fs = get_file_storage();
2291 $relativepath = implode('/', $args);
2292 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2293 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2294 send_file_not_found();
2297 send_stored_file($file, 0, 0, $forcedownload, $options);
2301 * Create url for question export
2303 * @param int $contextid, current context
2304 * @param int $categoryid, categoryid
2305 * @param string $format
2306 * @param string $withcategories
2307 * @param string $ithcontexts
2308 * @param moodle_url export file url
2310 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2311 $withcontexts, $filename) {
2313 $urlbase = "$CFG->wwwroot/pluginfile.php";
2314 return moodle_url
::make_file_url($urlbase,
2315 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2316 "/{$withcontexts}/{$filename}", true);
2320 * Get the URL to export a single question (exportone.php).
2322 * @param stdClass|question_definition $question the question definition as obtained from
2323 * question_bank::load_question_data() or question_bank::make_question().
2324 * (Only ->id and ->contextid are used.)
2325 * @return moodle_url the requested URL.
2327 function question_get_export_single_question_url($question) {
2328 $params = ['id' => $question->id
, 'sesskey' => sesskey()];
2329 $context = context
::instance_by_id($question->contextid
);
2330 switch ($context->contextlevel
) {
2331 case CONTEXT_MODULE
:
2332 $params['cmid'] = $context->instanceid
;
2335 case CONTEXT_COURSE
:
2336 $params['courseid'] = $context->instanceid
;
2340 $params['courseid'] = SITEID
;
2343 return new moodle_url('/question/exportone.php', $params);
2347 * Return a list of page types
2348 * @param string $pagetype current page type
2349 * @param stdClass $parentcontext Block's parent context
2350 * @param stdClass $currentcontext Current context of block
2352 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2355 'question-*'=>get_string('page-question-x', 'question'),
2356 'question-edit'=>get_string('page-question-edit', 'question'),
2357 'question-category'=>get_string('page-question-category', 'question'),
2358 'question-export'=>get_string('page-question-export', 'question'),
2359 'question-import'=>get_string('page-question-import', 'question')
2361 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
2362 require_once($CFG->dirroot
. '/course/lib.php');
2363 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2370 * Does an activity module use the question bank?
2372 * @param string $modname The name of the module (without mod_ prefix).
2373 * @return bool true if the module uses questions.
2375 function question_module_uses_questions($modname) {
2376 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
2380 $component = 'mod_'.$modname;
2381 if (component_callback_exists($component, 'question_pluginfile')) {
2382 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);