MDL-60425 blog: Remove empty line
[moodle.git] / lib / questionlib.php
blob1439ea87364d564e9c25a27cbe76e343c34a3525
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) {
122 global $CFG;
124 if (question_engine::questions_in_use($questionids)) {
125 return true;
128 foreach (core_component::get_plugin_list('mod') as $module => $path) {
129 $lib = $path . '/lib.php';
130 if (is_readable($lib)) {
131 include_once($lib);
133 $fn = $module . '_questions_in_use';
134 if (function_exists($fn)) {
135 if ($fn($questionids)) {
136 return true;
138 } else {
140 // Fallback for legacy modules.
141 $fn = $module . '_question_list_instances';
142 if (function_exists($fn)) {
143 foreach ($questionids as $questionid) {
144 $instances = $fn($questionid);
145 if (!empty($instances)) {
146 return true;
154 return false;
158 * Determine whether there arey any questions belonging to this context, that is whether any of its
159 * question categories contain any questions. This will return true even if all the questions are
160 * hidden.
162 * @param mixed $context either a context object, or a context id.
163 * @return boolean whether any of the question categories beloning to this context have
164 * any questions in them.
166 function question_context_has_any_questions($context) {
167 global $DB;
168 if (is_object($context)) {
169 $contextid = $context->id;
170 } else if (is_numeric($context)) {
171 $contextid = $context;
172 } else {
173 print_error('invalidcontextinhasanyquestions', 'question');
175 return $DB->record_exists_sql("SELECT *
176 FROM {question} q
177 JOIN {question_categories} qc ON qc.id = q.category
178 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
182 * Check whether a given grade is one of a list of allowed options. If not,
183 * depending on $matchgrades, either return the nearest match, or return false
184 * to signal an error.
185 * @param array $gradeoptionsfull list of valid options
186 * @param int $grade grade to be tested
187 * @param string $matchgrades 'error' or 'nearest'
188 * @return mixed either 'fixed' value or false if error.
190 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
192 if ($matchgrades == 'error') {
193 // (Almost) exact match, or an error.
194 foreach ($gradeoptionsfull as $value => $option) {
195 // Slightly fuzzy test, never check floats for equality.
196 if (abs($grade - $value) < 0.00001) {
197 return $value; // Be sure the return the proper value.
200 // Didn't find a match so that's an error.
201 return false;
203 } else if ($matchgrades == 'nearest') {
204 // Work out nearest value
205 $best = false;
206 $bestmismatch = 2;
207 foreach ($gradeoptionsfull as $value => $option) {
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
210 $best = $value;
211 $bestmismatch = $newmismatch;
214 return $best;
216 } else {
217 // Unknow option passed.
218 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
219 ' passed to match_grade_options');
224 * Remove stale questions from a category.
226 * While questions should not be left behind when they are not used any more,
227 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
228 * this happens, the users are unable to delete the question category unless
229 * they move those stale questions to another one category, but to them the
230 * category is empty as it does not contain anything. The purpose of this function
231 * is to detect the questions that may have gone stale and remove them.
233 * You will typically use this prior to checking if the category contains questions.
235 * The stale questions (unused and hidden to the user) handled are:
236 * - hidden questions
237 * - random questions
239 * @param int $categoryid The category ID.
241 function question_remove_stale_questions_from_category($categoryid) {
242 global $DB;
244 $select = 'category = :categoryid AND (qtype = :qtype OR hidden = :hidden)';
245 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'hidden' => 1];
246 $questions = $DB->get_recordset_select("question", $select, $params, '', 'id');
247 foreach ($questions as $question) {
248 // The function question_delete_question does not delete questions in use.
249 question_delete_question($question->id);
251 $questions->close();
255 * Category is about to be deleted,
256 * 1/ All questions are deleted for this question category.
257 * 2/ Any questions that can't be deleted are moved to a new category
258 * NOTE: this function is called from lib/db/upgrade.php
260 * @param object|core_course_category $category course category object
262 function question_category_delete_safe($category) {
263 global $DB;
264 $criteria = array('category' => $category->id);
265 $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
266 $rescue = null; // See the code around the call to question_save_from_deletion.
268 // Deal with any questions in the category.
269 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
271 // Try to delete each question.
272 foreach ($questions as $question) {
273 question_delete_question($question->id);
276 // Check to see if there were any questions that were kept because
277 // they are still in use somehow, even though quizzes in courses
278 // in this category will already have been deleted. This could
279 // happen, for example, if questions are added to a course,
280 // and then that course is moved to another category (MDL-14802).
281 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
282 if (!empty($questionids)) {
283 $parentcontextid = SYSCONTEXTID;
284 $name = get_string('unknown', 'question');
285 if ($context !== false) {
286 $name = $context->get_context_name();
287 $parentcontext = $context->get_parent_context();
288 if ($parentcontext) {
289 $parentcontextid = $parentcontext->id;
292 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
296 // Now delete the category.
297 $DB->delete_records('question_categories', array('id' => $category->id));
301 * Tests whether any question in a category is used by any part of Moodle.
303 * @param integer $categoryid a question category id.
304 * @param boolean $recursive whether to check child categories too.
305 * @return boolean whether any question in this category is in use.
307 function question_category_in_use($categoryid, $recursive = false) {
308 global $DB;
310 //Look at each question in the category
311 if ($questions = $DB->get_records_menu('question',
312 array('category' => $categoryid), '', 'id, 1')) {
313 if (questions_in_use(array_keys($questions))) {
314 return true;
317 if (!$recursive) {
318 return false;
321 //Look under child categories recursively
322 if ($children = $DB->get_records('question_categories',
323 array('parent' => $categoryid), '', 'id, 1')) {
324 foreach ($children as $child) {
325 if (question_category_in_use($child->id, $recursive)) {
326 return true;
331 return false;
335 * Deletes question and all associated data from the database
337 * It will not delete a question if it is used by an activity module
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.*, qc.contextid
345 FROM {question} q
346 JOIN {question_categories} qc ON qc.id = q.category
347 WHERE q.id = ?', array($questionid));
348 if (!$question) {
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.
352 return;
355 // Do not delete a question if it is used by an activity module
356 if (questions_in_use(array($questionid))) {
357 return;
360 $dm = new question_engine_data_mapper();
361 $dm->delete_previews($questionid);
363 // delete questiontype-specific data
364 question_bank::get_qtype($question->qtype, false)->delete_question(
365 $questionid, $question->contextid);
367 // Delete all tag instances.
368 core_tag_tag::remove_all_item_tags('core_question', 'question', $question->id);
370 // Now recursively delete all child questions
371 if ($children = $DB->get_records('question',
372 array('parent' => $questionid), '', 'id, qtype')) {
373 foreach ($children as $child) {
374 if ($child->id != $questionid) {
375 question_delete_question($child->id);
380 // Finally delete the question record itself
381 $DB->delete_records('question', array('id' => $questionid));
382 question_bank::notify_question_edited($questionid);
386 * All question categories and their questions are deleted for this context id.
388 * @param object $contextid The contextid to delete question categories from
389 * @return array Feedback from deletes (if any)
391 function question_delete_context($contextid) {
392 global $DB;
394 //To store feedback to be showed at the end of the process
395 $feedbackdata = array();
397 //Cache some strings
398 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
399 $fields = 'id, parent, name, contextid';
400 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
401 //Sort categories following their tree (parent-child) relationships
402 //this will make the feedback more readable
403 $categories = sort_categories_by_tree($categories);
405 foreach ($categories as $category) {
406 question_category_delete_safe($category);
408 //Fill feedback
409 $feedbackdata[] = array($category->name, $strcatdeleted);
412 return $feedbackdata;
416 * All question categories and their questions are deleted for this course.
418 * @param stdClass $course an object representing the activity
419 * @param boolean $feedback to specify if the process must output a summary of its work
420 * @return boolean
422 function question_delete_course($course, $feedback=true) {
423 $coursecontext = context_course::instance($course->id);
424 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
426 // Inform about changes performed if feedback is enabled.
427 if ($feedback && $feedbackdata) {
428 $table = new html_table();
429 $table->head = array(get_string('category', 'question'), get_string('action'));
430 $table->data = $feedbackdata;
431 echo html_writer::table($table);
433 return true;
437 * Category is about to be deleted,
438 * 1/ All question categories and their questions are deleted for this course category.
439 * 2/ All questions are moved to new category
441 * @param object|core_course_category $category course category object
442 * @param object|core_course_category $newcategory empty means everything deleted, otherwise id of
443 * category where content moved
444 * @param boolean $feedback to specify if the process must output a summary of its work
445 * @return boolean
447 function question_delete_course_category($category, $newcategory, $feedback=true) {
448 global $DB, $OUTPUT;
450 $context = context_coursecat::instance($category->id);
451 if (empty($newcategory)) {
452 $feedbackdata = question_delete_context($context->id, $feedback);
454 // Output feedback if requested.
455 if ($feedback && $feedbackdata) {
456 $table = new html_table();
457 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
458 $table->data = $feedbackdata;
459 echo html_writer::table($table);
462 } else {
463 // Move question categories to the new context.
464 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
465 return false;
468 // Only move question categories if there is any question category at all!
469 if ($topcategory = question_get_top_category($context->id)) {
470 $newtopcategory = question_get_top_category($newcontext->id, true);
472 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
473 $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
474 // Now delete the top category.
475 $DB->delete_records('question_categories', array('id' => $topcategory->id));
478 if ($feedback) {
479 $a = new stdClass();
480 $a->oldplace = $context->get_context_name();
481 $a->newplace = $newcontext->get_context_name();
482 echo $OUTPUT->notification(
483 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
487 return true;
491 * Enter description here...
493 * @param array $questionids of question ids
494 * @param object $newcontextid the context to create the saved category in.
495 * @param string $oldplace a textual description of the think being deleted,
496 * e.g. from get_context_name
497 * @param object $newcategory
498 * @return mixed false on
500 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
501 $newcategory = null) {
502 global $DB;
504 // Make a category in the parent context to move the questions to.
505 if (is_null($newcategory)) {
506 $newcategory = new stdClass();
507 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
508 $newcategory->contextid = $newcontextid;
509 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
510 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
511 $newcategory->sortorder = 999;
512 $newcategory->stamp = make_unique_id_code();
513 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
516 // Move any remaining questions to the 'saved' category.
517 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
518 return false;
520 return $newcategory;
524 * All question categories and their questions are deleted for this activity.
526 * @param object $cm the course module object representing the activity
527 * @param boolean $feedback to specify if the process must output a summary of its work
528 * @return boolean
530 function question_delete_activity($cm, $feedback=true) {
531 global $DB;
533 $modcontext = context_module::instance($cm->id);
534 $feedbackdata = question_delete_context($modcontext->id, $feedback);
535 // Inform about changes performed if feedback is enabled.
536 if ($feedback && $feedbackdata) {
537 $table = new html_table();
538 $table->head = array(get_string('category', 'question'), get_string('action'));
539 $table->data = $feedbackdata;
540 echo html_writer::table($table);
542 return true;
546 * This function will handle moving all tag instances to a new context for a
547 * given list of questions.
549 * Questions can be tagged in up to two contexts:
550 * 1.) The context the question exists in.
551 * 2.) The course context (if the question context is a higher context.
552 * E.g. course category context or system context.
554 * This means a question that exists in a higher context (e.g. course cat or
555 * system context) may have multiple groups of tags in any number of child
556 * course contexts.
558 * Questions in the course category context can be move "down" a context level
559 * into one of their child course contexts or activity contexts which affects the
560 * availability of that question in other courses / activities.
562 * In this case it makes the questions no longer available in the other course or
563 * activity contexts so we need to make sure that the tag instances in those other
564 * contexts are removed.
566 * @param stdClass[] $questions The list of question being moved (must include
567 * the id and contextid)
568 * @param context $newcontext The Moodle context the questions are being moved to
570 function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
571 // If the questions are moving to a new course/activity context then we need to
572 // find any existing tag instances from any unavailable course contexts and
573 // delete them because they will no longer be applicable (we don't support
574 // tagging questions across courses).
575 $instancestodelete = [];
576 $instancesfornewcontext = [];
577 $newcontextparentids = $newcontext->get_parent_context_ids();
578 $questionids = array_map(function($question) {
579 return $question->id;
580 }, $questions);
581 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
583 foreach ($questions as $question) {
584 $tagobjects = $questionstagobjects[$question->id];
586 foreach ($tagobjects as $tagobject) {
587 $tagid = $tagobject->taginstanceid;
588 $tagcontextid = $tagobject->taginstancecontextid;
589 $istaginnewcontext = $tagcontextid == $newcontext->id;
590 $istaginquestioncontext = $tagcontextid == $question->contextid;
592 if ($istaginnewcontext) {
593 // This tag instance is already in the correct context so we can
594 // ignore it.
595 continue;
598 if ($istaginquestioncontext) {
599 // This tag instance is in the question context so it needs to be
600 // updated.
601 $instancesfornewcontext[] = $tagid;
602 continue;
605 // These tag instances are in neither the new context nor the
606 // question context so we need to determine what to do based on
607 // the context they are in and the new question context.
608 $tagcontext = context::instance_by_id($tagcontextid);
609 $tagcoursecontext = $tagcontext->get_course_context(false);
610 // The tag is in a course context if get_course_context() returns
611 // itself.
612 $istaginstancecontextcourse = !empty($tagcoursecontext)
613 && $tagcontext->id == $tagcoursecontext->id;
615 if ($istaginstancecontextcourse) {
616 // If the tag instance is in a course context we need to add some
617 // special handling.
618 $tagcontextparentids = $tagcontext->get_parent_context_ids();
619 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
620 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
622 if ($isnewcontextaparent) {
623 // If the tag instance is a course context tag and the new
624 // context is still a parent context to the tag context then
625 // we can leave this tag where it is.
626 continue;
627 } else if ($isnewcontextachild) {
628 // If the new context is a child context (e.g. activity) of this
629 // tag instance then we should move all of this tag instance
630 // down into the activity context along with the question.
631 $instancesfornewcontext[] = $tagid;
632 } else {
633 // If the tag is in a course context that is no longer a parent
634 // or child of the new context then this tag instance should be
635 // removed.
636 $instancestodelete[] = $tagid;
638 } else {
639 // This is a catch all for any tag instances not in the question
640 // context or a course context. These tag instances should be
641 // updated to the new context id. This will clean up old invalid
642 // data.
643 $instancesfornewcontext[] = $tagid;
648 if (!empty($instancestodelete)) {
649 // Delete any course context tags that may no longer be valid.
650 core_tag_tag::delete_instances_by_id($instancestodelete);
653 if (!empty($instancesfornewcontext)) {
654 // Update the tag instances to the new context id.
655 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
660 * This function should be considered private to the question bank, it is called from
661 * question/editlib.php question/contextmoveq.php and a few similar places to to the
662 * work of acutally moving questions and associated data. However, callers of this
663 * function also have to do other work, which is why you should not call this method
664 * directly from outside the questionbank.
666 * @param array $questionids of question ids.
667 * @param integer $newcategoryid the id of the category to move to.
669 function question_move_questions_to_category($questionids, $newcategoryid) {
670 global $DB;
672 $newcontextid = $DB->get_field('question_categories', 'contextid',
673 array('id' => $newcategoryid));
674 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
675 $questions = $DB->get_records_sql("
676 SELECT q.id, q.qtype, qc.contextid, q.idnumber
677 FROM {question} q
678 JOIN {question_categories} qc ON q.category = qc.id
679 WHERE q.id $questionidcondition", $params);
680 foreach ($questions as $question) {
681 if ($newcontextid != $question->contextid) {
682 question_bank::get_qtype($question->qtype)->move_files(
683 $question->id, $question->contextid, $newcontextid);
685 // Check whether there could be a clash of idnumbers in the new category.
686 if (((string) $question->idnumber !== '') &&
687 $DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $newcategoryid])) {
688 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
689 [$newcategoryid, $question->idnumber . '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
690 $unique = 1;
691 if (count($rec)) {
692 $rec = reset($rec);
693 $idnumber = $rec->idnumber;
694 if (strpos($idnumber, '_') !== false) {
695 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
698 // For the move process, add a numerical increment to the idnumber. This means that if a question is
699 // mistakenly moved then the idnumber will not be completely lost.
700 $q = new stdClass();
701 $q->id = $question->id;
702 $q->category = $newcategoryid;
703 $q->idnumber = $question->idnumber . '_' . $unique;
704 $DB->update_record('question', $q);
708 // Move the questions themselves.
709 $DB->set_field_select('question', 'category', $newcategoryid,
710 "id $questionidcondition", $params);
712 // Move any subquestions belonging to them.
713 $DB->set_field_select('question', 'category', $newcategoryid,
714 "parent $questionidcondition", $params);
716 $newcontext = context::instance_by_id($newcontextid);
717 question_move_question_tags_to_new_context($questions, $newcontext);
719 // TODO Deal with datasets.
721 // Purge these questions from the cache.
722 foreach ($questions as $question) {
723 question_bank::notify_question_edited($question->id);
726 return true;
730 * This function helps move a question cateogry to a new context by moving all
731 * the files belonging to all the questions to the new context.
732 * Also moves subcategories.
733 * @param integer $categoryid the id of the category being moved.
734 * @param integer $oldcontextid the old context id.
735 * @param integer $newcontextid the new context id.
737 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
738 global $DB;
740 $questions = [];
741 $questionids = $DB->get_records_menu('question',
742 array('category' => $categoryid), '', 'id,qtype');
743 foreach ($questionids as $questionid => $qtype) {
744 question_bank::get_qtype($qtype)->move_files(
745 $questionid, $oldcontextid, $newcontextid);
746 // Purge this question from the cache.
747 question_bank::notify_question_edited($questionid);
749 $questions[] = (object) [
750 'id' => $questionid,
751 'contextid' => $oldcontextid
755 $newcontext = context::instance_by_id($newcontextid);
756 question_move_question_tags_to_new_context($questions, $newcontext);
758 $subcatids = $DB->get_records_menu('question_categories',
759 array('parent' => $categoryid), '', 'id,1');
760 foreach ($subcatids as $subcatid => $notused) {
761 $DB->set_field('question_categories', 'contextid', $newcontextid,
762 array('id' => $subcatid));
763 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
768 * Generate the URL for starting a new preview of a given question with the given options.
769 * @param integer $questionid the question to preview.
770 * @param string $preferredbehaviour the behaviour to use for the preview.
771 * @param float $maxmark the maximum to mark the question out of.
772 * @param question_display_options $displayoptions the display options to use.
773 * @param int $variant the variant of the question to preview. If null, one will
774 * be picked randomly.
775 * @param object $context context to run the preview in (affects things like
776 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
777 * @return moodle_url the URL.
779 function question_preview_url($questionid, $preferredbehaviour = null,
780 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
782 $params = array('id' => $questionid);
784 if (is_null($context)) {
785 global $PAGE;
786 $context = $PAGE->context;
788 if ($context->contextlevel == CONTEXT_MODULE) {
789 $params['cmid'] = $context->instanceid;
790 } else if ($context->contextlevel == CONTEXT_COURSE) {
791 $params['courseid'] = $context->instanceid;
794 if (!is_null($preferredbehaviour)) {
795 $params['behaviour'] = $preferredbehaviour;
798 if (!is_null($maxmark)) {
799 $params['maxmark'] = $maxmark;
802 if (!is_null($displayoptions)) {
803 $params['correctness'] = $displayoptions->correctness;
804 $params['marks'] = $displayoptions->marks;
805 $params['markdp'] = $displayoptions->markdp;
806 $params['feedback'] = (bool) $displayoptions->feedback;
807 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
808 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
809 $params['history'] = (bool) $displayoptions->history;
812 if ($variant) {
813 $params['variant'] = $variant;
816 return new moodle_url('/question/preview.php', $params);
820 * @return array that can be passed as $params to the {@link popup_action} constructor.
822 function question_preview_popup_params() {
823 return array(
824 'height' => 600,
825 'width' => 800,
830 * Given a list of ids, load the basic information about a set of questions from
831 * the questions table. The $join and $extrafields arguments can be used together
832 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
833 * read the code below to see how the SQL is assembled. Throws exceptions on error.
835 * @param array $questionids array of question ids to load. If null, then all
836 * questions matched by $join will be loaded.
837 * @param string $extrafields extra SQL code to be added to the query.
838 * @param string $join extra SQL code to be added to the query.
839 * @param array $extraparams values for any placeholders in $join.
840 * You must use named placeholders.
841 * @param string $orderby what to order the results by. Optional, default is unspecified order.
843 * @return array partially complete question objects. You need to call get_question_options
844 * on them before they can be properly used.
846 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
847 $extraparams = array(), $orderby = '') {
848 global $DB;
850 if ($questionids === null) {
851 $where = '';
852 $params = array();
853 } else {
854 if (empty($questionids)) {
855 return array();
858 list($questionidcondition, $params) = $DB->get_in_or_equal(
859 $questionids, SQL_PARAMS_NAMED, 'qid0000');
860 $where = 'WHERE q.id ' . $questionidcondition;
863 if ($join) {
864 $join = 'JOIN ' . $join;
867 if ($extrafields) {
868 $extrafields = ', ' . $extrafields;
871 if ($orderby) {
872 $orderby = 'ORDER BY ' . $orderby;
875 $sql = "SELECT q.*, qc.contextid{$extrafields}
876 FROM {question} q
877 JOIN {question_categories} qc ON q.category = qc.id
878 {$join}
879 {$where}
880 {$orderby}";
882 // Load the questions.
883 $questions = $DB->get_records_sql($sql, $extraparams + $params);
884 foreach ($questions as $question) {
885 $question->_partiallyloaded = true;
888 return $questions;
892 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
893 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
894 * read the code below to see how the SQL is assembled. Throws exceptions on error.
896 * @param array $questionids array of question ids.
897 * @param string $extrafields extra SQL code to be added to the query.
898 * @param string $join extra SQL code to be added to the query.
899 * @param array $extraparams values for any placeholders in $join.
900 * You are strongly recommended to use named placeholder.
902 * @return array question objects.
904 function question_load_questions($questionids, $extrafields = '', $join = '') {
905 $questions = question_preload_questions($questionids, $extrafields, $join);
907 // Load the question type specific information
908 if (!get_question_options($questions)) {
909 return 'Could not load the question options';
912 return $questions;
916 * Private function to factor common code out of get_question_options().
918 * @param object $question the question to tidy.
919 * @param stdClass $category The question_categories record for the given $question.
920 * @param stdClass[]|null $tagobjects The tags for the given $question.
921 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
923 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
924 global $CFG;
926 // Load question-type specific fields.
927 if (!question_bank::is_qtype_installed($question->qtype)) {
928 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
929 'qtype_missingtype')) . $question->questiontext;
931 question_bank::get_qtype($question->qtype)->get_question_options($question);
933 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
934 $question->defaultmark += 0;
935 $question->penalty += 0;
937 if (isset($question->_partiallyloaded)) {
938 unset($question->_partiallyloaded);
941 $question->categoryobject = $category;
943 if (!is_null($tagobjects)) {
944 $categorycontext = context::instance_by_id($category->contextid);
945 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
946 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
947 $question->coursetags = $sortedtagobjects->coursetags;
948 $question->tagobjects = $sortedtagobjects->tagobjects;
949 $question->tags = $sortedtagobjects->tags;
954 * Updates the question objects with question type specific
955 * information by calling {@link get_question_options()}
957 * Can be called either with an array of question objects or with a single
958 * question object.
960 * @param mixed $questions Either an array of question objects to be updated
961 * or just a single question object
962 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
963 * @param stdClass[] $filtercourses The courses to filter the course tags by.
964 * @return bool Indicates success or failure.
966 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
967 global $DB;
969 $questionlist = is_array($questions) ? $questions : [$questions];
970 $categoryids = [];
971 $questionids = [];
973 if (empty($questionlist)) {
974 return true;
977 foreach ($questionlist as $question) {
978 $questionids[] = $question->id;
980 if (!in_array($question->category, $categoryids)) {
981 $categoryids[] = $question->category;
985 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
987 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
988 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
989 } else {
990 $tagobjectsbyquestion = null;
993 foreach ($questionlist as $question) {
994 if (is_null($tagobjectsbyquestion)) {
995 $tagobjects = null;
996 } else {
997 $tagobjects = $tagobjectsbyquestion[$question->id];
1000 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
1003 return true;
1007 * Sort question tags by course or normal tags.
1009 * This function also search tag instances that may have a context id that don't match either a course or
1010 * question context and fix the data setting the correct context id.
1012 * @param stdClass[] $tagobjects The tags for the given $question.
1013 * @param stdClass $categorycontext The question categories context.
1014 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1015 * @return stdClass $sortedtagobjects Sorted tag objects.
1017 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
1019 // Questions can have two sets of tag instances. One set at the
1020 // course context level and another at the context the question
1021 // belongs to (e.g. course category, system etc).
1022 $sortedtagobjects = new stdClass();
1023 $sortedtagobjects->coursetagobjects = [];
1024 $sortedtagobjects->coursetags = [];
1025 $sortedtagobjects->tagobjects = [];
1026 $sortedtagobjects->tags = [];
1027 $taginstanceidstonormalise = [];
1028 $filtercoursecontextids = [];
1029 $hasfiltercourses = !empty($filtercourses);
1031 if ($hasfiltercourses) {
1032 // If we're being asked to filter the course tags by a set of courses
1033 // then get the context ids to filter below.
1034 $filtercoursecontextids = array_map(function($course) {
1035 $coursecontext = context_course::instance($course->id);
1036 return $coursecontext->id;
1037 }, $filtercourses);
1040 foreach ($tagobjects as $tagobject) {
1041 $tagcontextid = $tagobject->taginstancecontextid;
1042 $tagcontext = context::instance_by_id($tagcontextid);
1043 $tagcoursecontext = $tagcontext->get_course_context(false);
1044 // This is a course tag if the tag context is a course context which
1045 // doesn't match the question's context. Any tag in the question context
1046 // is not considered a course tag, it belongs to the question.
1047 $iscoursetag = $tagcoursecontext
1048 && $tagcontext->id == $tagcoursecontext->id
1049 && $tagcontext->id != $categorycontext->id;
1051 if ($iscoursetag) {
1052 // Any tag instance in a course context level is considered a course tag.
1053 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1054 // Add the tag to the list of course tags if we aren't being
1055 // asked to filter or if this tag is in the list of courses
1056 // we're being asked to filter by.
1057 $sortedtagobjects->coursetagobjects[] = $tagobject;
1058 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1060 } else {
1061 // All non course context level tag instances or tags in the question
1062 // context belong to the context that the question was created in.
1063 $sortedtagobjects->tagobjects[] = $tagobject;
1064 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1066 // Due to legacy tag implementations that don't force the recording
1067 // of a context id, some tag instances may have context ids that don't
1068 // match either a course context or the question context. In this case
1069 // we should take the opportunity to fix up the data and set the correct
1070 // context id.
1071 if ($tagcontext->id != $categorycontext->id) {
1072 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1073 // Update the object properties to reflect the DB update that will
1074 // happen below.
1075 $tagobject->taginstancecontextid = $categorycontext->id;
1080 if (!empty($taginstanceidstonormalise)) {
1081 // If we found any tag instances with incorrect context id data then we can
1082 // correct those values now by setting them to the question context id.
1083 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1086 return $sortedtagobjects;
1090 * Print the icon for the question type
1092 * @param object $question The question object for which the icon is required.
1093 * Only $question->qtype is used.
1094 * @return string the HTML for the img tag.
1096 function print_question_icon($question) {
1097 global $PAGE;
1098 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
1102 * Creates a stamp that uniquely identifies this version of the question
1104 * In future we want this to use a hash of the question data to guarantee that
1105 * identical versions have the same version stamp.
1107 * @param object $question
1108 * @return string A unique version stamp
1110 function question_hash($question) {
1111 return make_unique_id_code();
1114 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1117 * returns the categories with their names ordered following parent-child relationships
1118 * finally it tries to return pending categories (those being orphaned, whose parent is
1119 * incorrect) to avoid missing any category from original array.
1121 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1122 global $DB;
1124 $children = array();
1125 $keys = array_keys($categories);
1127 foreach ($keys as $key) {
1128 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1129 $children[$key] = $categories[$key];
1130 $categories[$key]->processed = true;
1131 $children = $children + sort_categories_by_tree(
1132 $categories, $children[$key]->id, $level+1);
1135 //If level = 1, we have finished, try to look for non processed categories
1136 // (bad parent) and sort them too
1137 if ($level == 1) {
1138 foreach ($keys as $key) {
1139 // If not processed and it's a good candidate to start (because its
1140 // parent doesn't exist in the course)
1141 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1142 array('contextid' => $categories[$key]->contextid,
1143 'id' => $categories[$key]->parent))) {
1144 $children[$key] = $categories[$key];
1145 $categories[$key]->processed = true;
1146 $children = $children + sort_categories_by_tree(
1147 $categories, $children[$key]->id, $level + 1);
1151 return $children;
1155 * Private method, only for the use of add_indented_names().
1157 * Recursively adds an indentedname field to each category, starting with the category
1158 * with id $id, and dealing with that category and all its children, and
1159 * return a new array, with those categories in the right order.
1161 * @param array $categories an array of categories which has had childids
1162 * fields added by flatten_category_tree(). Passed by reference for
1163 * performance only. It is not modfied.
1164 * @param int $id the category to start the indenting process from.
1165 * @param int $depth the indent depth. Used in recursive calls.
1166 * @return array a new array of categories, in the right order for the tree.
1168 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1170 // Indent the name of this category.
1171 $newcategories = array();
1172 $newcategories[$id] = $categories[$id];
1173 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
1174 $categories[$id]->name;
1176 // Recursively indent the children.
1177 foreach ($categories[$id]->childids as $childid) {
1178 if ($childid != $nochildrenof) {
1179 $newcategories = $newcategories + flatten_category_tree(
1180 $categories, $childid, $depth + 1, $nochildrenof);
1184 // Remove the childids array that were temporarily added.
1185 unset($newcategories[$id]->childids);
1187 return $newcategories;
1191 * Format categories into an indented list reflecting the tree structure.
1193 * @param array $categories An array of category objects, for example from the.
1194 * @return array The formatted list of categories.
1196 function add_indented_names($categories, $nochildrenof = -1) {
1198 // Add an array to each category to hold the child category ids. This array
1199 // will be removed again by flatten_category_tree(). It should not be used
1200 // outside these two functions.
1201 foreach (array_keys($categories) as $id) {
1202 $categories[$id]->childids = array();
1205 // Build the tree structure, and record which categories are top-level.
1206 // We have to be careful, because the categories array may include published
1207 // categories from other courses, but not their parents.
1208 $toplevelcategoryids = array();
1209 foreach (array_keys($categories) as $id) {
1210 if (!empty($categories[$id]->parent) &&
1211 array_key_exists($categories[$id]->parent, $categories)) {
1212 $categories[$categories[$id]->parent]->childids[] = $id;
1213 } else {
1214 $toplevelcategoryids[] = $id;
1218 // Flatten the tree to and add the indents.
1219 $newcategories = array();
1220 foreach ($toplevelcategoryids as $id) {
1221 $newcategories = $newcategories + flatten_category_tree(
1222 $categories, $id, 0, $nochildrenof);
1225 return $newcategories;
1229 * Output a select menu of question categories.
1231 * Categories from this course and (optionally) published categories from other courses
1232 * are included. Optionally, only categories the current user may edit can be included.
1234 * @param integer $courseid the id of the course to get the categories for.
1235 * @param integer $published if true, include publised categories from other courses.
1236 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1237 * @param integer $selected optionally, the id of a category to be selected by
1238 * default in the dropdown.
1240 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1241 $selected = "", $nochildrenof = -1) {
1242 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1243 false, $nochildrenof);
1244 if ($selected) {
1245 $choose = '';
1246 } else {
1247 $choose = 'choosedots';
1249 $options = array();
1250 foreach ($categoriesarray as $group => $opts) {
1251 $options[] = array($group => $opts);
1253 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1254 $attrs = array('id' => 'id_movetocategory', 'class' => 'custom-select');
1255 echo html_writer::select($options, 'category', $selected, $choose, $attrs);
1259 * @param integer $contextid a context id.
1260 * @return object the default question category for that context, or false if none.
1262 function question_get_default_category($contextid) {
1263 global $DB;
1264 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1265 array($contextid), 'id', '*', 0, 1);
1266 if (!empty($category)) {
1267 return reset($category);
1268 } else {
1269 return false;
1274 * Gets the top category in the given context.
1275 * This function can optionally create the top category if it doesn't exist.
1277 * @param int $contextid A context id.
1278 * @param bool $create Whether create a top category if it doesn't exist.
1279 * @return bool|stdClass The top question category for that context, or false if none.
1281 function question_get_top_category($contextid, $create = false) {
1282 global $DB;
1283 $category = $DB->get_record('question_categories',
1284 array('contextid' => $contextid, 'parent' => 0));
1286 if (!$category && $create) {
1287 // We need to make one.
1288 $category = new stdClass();
1289 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1290 $category->info = '';
1291 $category->contextid = $contextid;
1292 $category->parent = 0;
1293 $category->sortorder = 0;
1294 $category->stamp = make_unique_id_code();
1295 $category->id = $DB->insert_record('question_categories', $category);
1298 return $category;
1302 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1304 * @param array $contextids List of context ids
1305 * @return array
1307 function question_get_top_categories_for_contexts($contextids) {
1308 global $DB;
1310 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1311 list($insql, $params) = $DB->get_in_or_equal($contextids);
1312 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1313 $topcategories = $DB->get_fieldset_sql($sql, $params);
1315 return $topcategories;
1319 * Gets the default category in the most specific context.
1320 * If no categories exist yet then default ones are created in all contexts.
1322 * @param array $contexts The context objects for this context and all parent contexts.
1323 * @return object The default category - the category in the course context
1325 function question_make_default_categories($contexts) {
1326 global $DB;
1327 static $preferredlevels = array(
1328 CONTEXT_COURSE => 4,
1329 CONTEXT_MODULE => 3,
1330 CONTEXT_COURSECAT => 2,
1331 CONTEXT_SYSTEM => 1,
1334 $toreturn = null;
1335 $preferredness = 0;
1336 // If it already exists, just return it.
1337 foreach ($contexts as $key => $context) {
1338 $topcategory = question_get_top_category($context->id, true);
1339 if (!$exists = $DB->record_exists("question_categories",
1340 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1341 // Otherwise, we need to make one
1342 $category = new stdClass();
1343 $contextname = $context->get_context_name(false, true);
1344 $category->name = get_string('defaultfor', 'question', $contextname);
1345 $category->info = get_string('defaultinfofor', 'question', $contextname);
1346 $category->contextid = $context->id;
1347 $category->parent = $topcategory->id;
1348 // By default, all categories get this number, and are sorted alphabetically.
1349 $category->sortorder = 999;
1350 $category->stamp = make_unique_id_code();
1351 $category->id = $DB->insert_record('question_categories', $category);
1352 } else {
1353 $category = question_get_default_category($context->id);
1355 $thispreferredness = $preferredlevels[$context->contextlevel];
1356 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1357 $thispreferredness += 10;
1359 if ($thispreferredness > $preferredness) {
1360 $toreturn = $category;
1361 $preferredness = $thispreferredness;
1365 if (!is_null($toreturn)) {
1366 $toreturn = clone($toreturn);
1368 return $toreturn;
1372 * Get all the category objects, including a count of the number of questions in that category,
1373 * for all the categories in the lists $contexts.
1375 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1376 * @param string $sortorder used as the ORDER BY clause in the select statement.
1377 * @param bool $top Whether to return the top categories or not.
1378 * @return array of category objects.
1380 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1381 global $DB;
1382 $topwhere = $top ? '' : 'AND c.parent <> 0';
1383 return $DB->get_records_sql("
1384 SELECT c.*, (SELECT count(1) FROM {question} q
1385 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1386 FROM {question_categories} c
1387 WHERE c.contextid IN ($contexts) $topwhere
1388 ORDER BY $sortorder");
1392 * Output an array of question categories.
1394 * @param array $contexts The list of contexts.
1395 * @param bool $top Whether to return the top categories or not.
1396 * @param int $currentcat
1397 * @param bool $popupform
1398 * @param int $nochildrenof
1399 * @return array
1401 function question_category_options($contexts, $top = false, $currentcat = 0,
1402 $popupform = false, $nochildrenof = -1) {
1403 global $CFG;
1404 $pcontexts = array();
1405 foreach ($contexts as $context) {
1406 $pcontexts[] = $context->id;
1408 $contextslist = join($pcontexts, ', ');
1410 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1412 if ($top) {
1413 $categories = question_fix_top_names($categories);
1416 $categories = question_add_context_in_key($categories);
1417 $categories = add_indented_names($categories, $nochildrenof);
1419 // sort cats out into different contexts
1420 $categoriesarray = array();
1421 foreach ($pcontexts as $contextid) {
1422 $context = context::instance_by_id($contextid);
1423 $contextstring = $context->get_context_name(true, true);
1424 foreach ($categories as $category) {
1425 if ($category->contextid == $contextid) {
1426 $cid = $category->id;
1427 if ($currentcat != $cid || $currentcat == 0) {
1428 $countstring = !empty($category->questioncount) ?
1429 " ($category->questioncount)" : '';
1430 $categoriesarray[$contextstring][$cid] =
1431 format_string($category->indentedname, true,
1432 array('context' => $context)) . $countstring;
1437 if ($popupform) {
1438 $popupcats = array();
1439 foreach ($categoriesarray as $contextstring => $optgroup) {
1440 $group = array();
1441 foreach ($optgroup as $key => $value) {
1442 $key = str_replace($CFG->wwwroot, '', $key);
1443 $group[$key] = $value;
1445 $popupcats[] = array($contextstring => $group);
1447 return $popupcats;
1448 } else {
1449 return $categoriesarray;
1453 function question_add_context_in_key($categories) {
1454 $newcatarray = array();
1455 foreach ($categories as $id => $category) {
1456 $category->parent = "$category->parent,$category->contextid";
1457 $category->id = "$category->id,$category->contextid";
1458 $newcatarray["$id,$category->contextid"] = $category;
1460 return $newcatarray;
1464 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1466 * @param array $categories An array of question categories.
1467 * @return array The same question category list given to the function, with the top category names being translated.
1469 function question_fix_top_names($categories) {
1471 foreach ($categories as $id => $category) {
1472 if ($category->parent == 0) {
1473 $context = context::instance_by_id($category->contextid);
1474 $categories[$id]->name = get_string('topfor', 'question', $context->get_context_name(false));
1478 return $categories;
1482 * @return array of question category ids of the category and all subcategories.
1484 function question_categorylist($categoryid) {
1485 global $DB;
1487 // final list of category IDs
1488 $categorylist = array();
1490 // a list of category IDs to check for any sub-categories
1491 $subcategories = array($categoryid);
1493 while ($subcategories) {
1494 foreach ($subcategories as $subcategory) {
1495 // if anything from the temporary list was added already, then we have a loop
1496 if (isset($categorylist[$subcategory])) {
1497 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1499 $categorylist[$subcategory] = $subcategory;
1502 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1504 $subcategories = $DB->get_records_select_menu('question_categories',
1505 "parent $in", $params, NULL, 'id,id AS id2');
1508 return $categorylist;
1512 * Get all parent categories of a given question category in decending order.
1513 * @param int $categoryid for which you want to find the parents.
1514 * @return array of question category ids of all parents categories.
1516 function question_categorylist_parents(int $categoryid) {
1517 global $DB;
1518 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1519 if (!$parent) {
1520 return [];
1522 $categorylist = [$parent];
1523 $currentid = $parent;
1524 while ($currentid) {
1525 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1526 if ($currentid) {
1527 $categorylist[] = $currentid;
1530 // Present the list in decending order (the top category at the top).
1531 $categorylist = array_reverse($categorylist);
1532 return $categorylist;
1535 //===========================
1536 // Import/Export Functions
1537 //===========================
1540 * Get list of available import or export formats
1541 * @param string $type 'import' if import list, otherwise export list assumed
1542 * @return array sorted list of import/export formats available
1544 function get_import_export_formats($type) {
1545 global $CFG;
1546 require_once($CFG->dirroot . '/question/format.php');
1548 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1550 $fileformatname = array();
1551 foreach ($formatclasses as $component => $formatclass) {
1553 $format = new $formatclass();
1554 if ($type == 'import') {
1555 $provided = $format->provide_import();
1556 } else {
1557 $provided = $format->provide_export();
1560 if ($provided) {
1561 list($notused, $fileformat) = explode('_', $component, 2);
1562 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1566 core_collator::asort($fileformatnames);
1567 return $fileformatnames;
1572 * Create a reasonable default file name for exporting questions from a particular
1573 * category.
1574 * @param object $course the course the questions are in.
1575 * @param object $category the question category.
1576 * @return string the filename.
1578 function question_default_export_filename($course, $category) {
1579 // We build a string that is an appropriate name (questions) from the lang pack,
1580 // then the corse shortname, then the question category name, then a timestamp.
1582 $base = clean_filename(get_string('exportfilename', 'question'));
1584 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1585 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1587 $shortname = clean_filename($course->shortname);
1588 if ($shortname == '' || $shortname == '_' ) {
1589 $shortname = $course->id;
1592 $categoryname = clean_filename(format_string($category->name));
1594 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1596 return $export_name;
1600 * Converts contextlevels to strings and back to help with reading/writing contexts
1601 * to/from import/export files.
1603 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1604 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1606 class context_to_string_translator{
1608 * @var array used to translate between contextids and strings for this context.
1610 protected $contexttostringarray = array();
1612 public function __construct($contexts) {
1613 $this->generate_context_to_string_array($contexts);
1616 public function context_to_string($contextid) {
1617 return $this->contexttostringarray[$contextid];
1620 public function string_to_context($contextname) {
1621 $contextid = array_search($contextname, $this->contexttostringarray);
1622 return $contextid;
1625 protected function generate_context_to_string_array($contexts) {
1626 if (!$this->contexttostringarray) {
1627 $catno = 1;
1628 foreach ($contexts as $context) {
1629 switch ($context->contextlevel) {
1630 case CONTEXT_MODULE :
1631 $contextstring = 'module';
1632 break;
1633 case CONTEXT_COURSE :
1634 $contextstring = 'course';
1635 break;
1636 case CONTEXT_COURSECAT :
1637 $contextstring = "cat$catno";
1638 $catno++;
1639 break;
1640 case CONTEXT_SYSTEM :
1641 $contextstring = 'system';
1642 break;
1644 $this->contexttostringarray[$context->id] = $contextstring;
1652 * Check capability on category
1654 * @param mixed $questionorid object or id. If an object is passed, it should include ->contextid and ->createdby.
1655 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1656 * @param integer $notused no longer used.
1657 * @return boolean this user has the capability $cap for this question $question?
1659 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1660 global $USER;
1662 if (is_numeric($questionorid)) {
1663 $question = question_bank::load_question_data((int)$questionorid);
1664 } else if (is_object($questionorid)) {
1665 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1666 $question = $questionorid;
1669 if (!isset($question) && isset($questionorid->id) && $questionorid->id != 0) {
1670 $question = question_bank::load_question_data($questionorid->id);
1672 } else {
1673 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1676 $context = context::instance_by_id($question->contextid);
1678 // These are existing questions capabilities that are set per category.
1679 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1680 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1682 if (!isset($capabilitieswithallandmine[$cap])) {
1683 return has_capability('moodle/question:' . $cap, $context);
1684 } else {
1685 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1686 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1691 * Require capability on question.
1693 function question_require_capability_on($question, $cap) {
1694 if (!question_has_capability_on($question, $cap)) {
1695 print_error('nopermissions', '', '', $cap);
1697 return true;
1701 * @param object $context a context
1702 * @return string A URL for editing questions in this context.
1704 function question_edit_url($context) {
1705 global $CFG, $SITE;
1706 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1707 return false;
1709 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1710 $defaultcategory = question_get_default_category($context->id);
1711 if ($defaultcategory) {
1712 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1714 switch ($context->contextlevel) {
1715 case CONTEXT_SYSTEM:
1716 return $baseurl . 'courseid=' . $SITE->id;
1717 case CONTEXT_COURSECAT:
1718 // This is nasty, becuase we can only edit questions in a course
1719 // context at the moment, so for now we just return false.
1720 return false;
1721 case CONTEXT_COURSE:
1722 return $baseurl . 'courseid=' . $context->instanceid;
1723 case CONTEXT_MODULE:
1724 return $baseurl . 'cmid=' . $context->instanceid;
1730 * Adds question bank setting links to the given navigation node if caps are met.
1732 * @param navigation_node $navigationnode The navigation node to add the question branch to
1733 * @param object $context
1734 * @return navigation_node Returns the question branch that was added
1736 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1737 global $PAGE;
1739 if ($context->contextlevel == CONTEXT_COURSE) {
1740 $params = array('courseid'=>$context->instanceid);
1741 } else if ($context->contextlevel == CONTEXT_MODULE) {
1742 $params = array('cmid'=>$context->instanceid);
1743 } else {
1744 return;
1747 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1748 $params['cat'] = $cat;
1751 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1752 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1754 $contexts = new question_edit_contexts($context);
1755 if ($contexts->have_one_edit_tab_cap('questions')) {
1756 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1757 '/question/edit.php', $params), navigation_node::TYPE_SETTING, null, 'questions');
1759 if ($contexts->have_one_edit_tab_cap('categories')) {
1760 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1761 '/question/category.php', $params), navigation_node::TYPE_SETTING, null, 'categories');
1763 if ($contexts->have_one_edit_tab_cap('import')) {
1764 $questionnode->add(get_string('import', 'question'), new moodle_url(
1765 '/question/import.php', $params), navigation_node::TYPE_SETTING, null, 'import');
1767 if ($contexts->have_one_edit_tab_cap('export')) {
1768 $questionnode->add(get_string('export', 'question'), new moodle_url(
1769 '/question/export.php', $params), navigation_node::TYPE_SETTING, null, 'export');
1772 return $questionnode;
1776 * @return array all the capabilities that relate to accessing particular questions.
1778 function question_get_question_capabilities() {
1779 return array(
1780 'moodle/question:add',
1781 'moodle/question:editmine',
1782 'moodle/question:editall',
1783 'moodle/question:viewmine',
1784 'moodle/question:viewall',
1785 'moodle/question:usemine',
1786 'moodle/question:useall',
1787 'moodle/question:movemine',
1788 'moodle/question:moveall',
1793 * @return array all the question bank capabilities.
1795 function question_get_all_capabilities() {
1796 $caps = question_get_question_capabilities();
1797 $caps[] = 'moodle/question:managecategory';
1798 $caps[] = 'moodle/question:flag';
1799 return $caps;
1804 * Tracks all the contexts related to the one where we are currently editing
1805 * questions, and provides helper methods to check permissions.
1807 * @copyright 2007 Jamie Pratt me@jamiep.org
1808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1810 class question_edit_contexts {
1812 public static $caps = array(
1813 'editq' => array('moodle/question:add',
1814 'moodle/question:editmine',
1815 'moodle/question:editall',
1816 'moodle/question:viewmine',
1817 'moodle/question:viewall',
1818 'moodle/question:usemine',
1819 'moodle/question:useall',
1820 'moodle/question:movemine',
1821 'moodle/question:moveall'),
1822 'questions'=>array('moodle/question:add',
1823 'moodle/question:editmine',
1824 'moodle/question:editall',
1825 'moodle/question:viewmine',
1826 'moodle/question:viewall',
1827 'moodle/question:movemine',
1828 'moodle/question:moveall'),
1829 'categories'=>array('moodle/question:managecategory'),
1830 'import'=>array('moodle/question:add'),
1831 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1833 protected $allcontexts;
1836 * Constructor
1837 * @param context the current context.
1839 public function __construct(context $thiscontext) {
1840 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1844 * @return array all parent contexts
1846 public function all() {
1847 return $this->allcontexts;
1851 * @return object lowest context which must be either the module or course context
1853 public function lowest() {
1854 return $this->allcontexts[0];
1858 * @param string $cap capability
1859 * @return array parent contexts having capability, zero based index
1861 public function having_cap($cap) {
1862 $contextswithcap = array();
1863 foreach ($this->allcontexts as $context) {
1864 if (has_capability($cap, $context)) {
1865 $contextswithcap[] = $context;
1868 return $contextswithcap;
1872 * @param array $caps capabilities
1873 * @return array parent contexts having at least one of $caps, zero based index
1875 public function having_one_cap($caps) {
1876 $contextswithacap = array();
1877 foreach ($this->allcontexts as $context) {
1878 foreach ($caps as $cap) {
1879 if (has_capability($cap, $context)) {
1880 $contextswithacap[] = $context;
1881 break; //done with caps loop
1885 return $contextswithacap;
1889 * @param string $tabname edit tab name
1890 * @return array parent contexts having at least one of $caps, zero based index
1892 public function having_one_edit_tab_cap($tabname) {
1893 return $this->having_one_cap(self::$caps[$tabname]);
1897 * @return those contexts where a user can add a question and then use it.
1899 public function having_add_and_use() {
1900 $contextswithcap = array();
1901 foreach ($this->allcontexts as $context) {
1902 if (!has_capability('moodle/question:add', $context)) {
1903 continue;
1905 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1906 continue;
1908 $contextswithcap[] = $context;
1910 return $contextswithcap;
1914 * Has at least one parent context got the cap $cap?
1916 * @param string $cap capability
1917 * @return boolean
1919 public function have_cap($cap) {
1920 return (count($this->having_cap($cap)));
1924 * Has at least one parent context got one of the caps $caps?
1926 * @param array $caps capability
1927 * @return boolean
1929 public function have_one_cap($caps) {
1930 foreach ($caps as $cap) {
1931 if ($this->have_cap($cap)) {
1932 return true;
1935 return false;
1939 * Has at least one parent context got one of the caps for actions on $tabname
1941 * @param string $tabname edit tab name
1942 * @return boolean
1944 public function have_one_edit_tab_cap($tabname) {
1945 return $this->have_one_cap(self::$caps[$tabname]);
1949 * Throw error if at least one parent context hasn't got the cap $cap
1951 * @param string $cap capability
1953 public function require_cap($cap) {
1954 if (!$this->have_cap($cap)) {
1955 print_error('nopermissions', '', '', $cap);
1960 * Throw error if at least one parent context hasn't got one of the caps $caps
1962 * @param array $cap capabilities
1964 public function require_one_cap($caps) {
1965 if (!$this->have_one_cap($caps)) {
1966 $capsstring = join($caps, ', ');
1967 print_error('nopermissions', '', '', $capsstring);
1972 * Throw error if at least one parent context hasn't got one of the caps $caps
1974 * @param string $tabname edit tab name
1976 public function require_one_edit_tab_cap($tabname) {
1977 if (!$this->have_one_edit_tab_cap($tabname)) {
1978 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1985 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1987 * @package core_question
1988 * @category files
1989 * @param string $text text being processed
1990 * @param string $file the php script used to serve files
1991 * @param int $contextid context ID
1992 * @param string $component component
1993 * @param string $filearea filearea
1994 * @param array $ids other IDs will be used to check file permission
1995 * @param int $itemid item ID
1996 * @param array $options options
1997 * @return string
1999 function question_rewrite_question_urls($text, $file, $contextid, $component,
2000 $filearea, array $ids, $itemid, array $options=null) {
2002 $idsstr = '';
2003 if (!empty($ids)) {
2004 $idsstr .= implode('/', $ids);
2006 if ($itemid !== null) {
2007 $idsstr .= '/' . $itemid;
2009 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
2010 $filearea, $idsstr, $options);
2014 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
2015 * viewing the question outside an attempt (for example, in the question bank
2016 * listing or in the quiz statistics report).
2018 * @param string $text the question text.
2019 * @param int $questionid the question id.
2020 * @param int $filecontextid the context id of the question being displayed.
2021 * @param string $filecomponent the component that owns the file area.
2022 * @param string $filearea the file area name.
2023 * @param int|null $itemid the file's itemid
2024 * @param int $previewcontextid the context id where the preview is being displayed.
2025 * @param string $previewcomponent component responsible for displaying the preview.
2026 * @param array $options text and file options ('forcehttps'=>false)
2027 * @return string $questiontext with URLs rewritten.
2029 function question_rewrite_question_preview_urls($text, $questionid,
2030 $filecontextid, $filecomponent, $filearea, $itemid,
2031 $previewcontextid, $previewcomponent, $options = null) {
2033 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2034 if ($itemid) {
2035 $path .= '/' . $itemid;
2038 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2039 $filecomponent, $filearea, $path, $options);
2043 * Called by pluginfile.php to serve files related to the 'question' core
2044 * component and for files belonging to qtypes.
2046 * For files that relate to questions in a question_attempt, then we delegate to
2047 * a function in the component that owns the attempt (for example in the quiz,
2048 * or in core question preview) to get necessary inforation.
2050 * (Note that, at the moment, all question file areas relate to questions in
2051 * attempts, so the If at the start of the last paragraph is always true.)
2053 * Does not return, either calls send_file_not_found(); or serves the file.
2055 * @package core_question
2056 * @category files
2057 * @param stdClass $course course settings object
2058 * @param stdClass $context context object
2059 * @param string $component the name of the component we are serving files for.
2060 * @param string $filearea the name of the file area.
2061 * @param array $args the remaining bits of the file path.
2062 * @param bool $forcedownload whether the user must be forced to download the file.
2063 * @param array $options additional options affecting the file serving
2065 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2066 global $DB, $CFG;
2068 // Special case, sending a question bank export.
2069 if ($filearea === 'export') {
2070 list($context, $course, $cm) = get_context_info_array($context->id);
2071 require_login($course, false, $cm);
2073 require_once($CFG->dirroot . '/question/editlib.php');
2074 $contexts = new question_edit_contexts($context);
2075 // check export capability
2076 $contexts->require_one_edit_tab_cap('export');
2077 $category_id = (int)array_shift($args);
2078 $format = array_shift($args);
2079 $cattofile = array_shift($args);
2080 $contexttofile = array_shift($args);
2081 $filename = array_shift($args);
2083 // load parent class for import/export
2084 require_once($CFG->dirroot . '/question/format.php');
2085 require_once($CFG->dirroot . '/question/editlib.php');
2086 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2088 $classname = 'qformat_' . $format;
2089 if (!class_exists($classname)) {
2090 send_file_not_found();
2093 $qformat = new $classname();
2095 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2096 send_file_not_found();
2099 $qformat->setCategory($category);
2100 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2101 $qformat->setCourse($course);
2103 if ($cattofile == 'withcategories') {
2104 $qformat->setCattofile(true);
2105 } else {
2106 $qformat->setCattofile(false);
2109 if ($contexttofile == 'withcontexts') {
2110 $qformat->setContexttofile(true);
2111 } else {
2112 $qformat->setContexttofile(false);
2115 if (!$qformat->exportpreprocess()) {
2116 send_file_not_found();
2117 print_error('exporterror', 'question', $thispageurl->out());
2120 // export data to moodle file pool
2121 if (!$content = $qformat->exportprocess()) {
2122 send_file_not_found();
2125 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2128 // Normal case, a file belonging to a question.
2129 $qubaidorpreview = array_shift($args);
2131 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2132 if ($qubaidorpreview === 'preview') {
2133 $previewcontextid = (int)array_shift($args);
2134 $previewcomponent = array_shift($args);
2135 $questionid = (int) array_shift($args);
2136 $previewcontext = context_helper::instance_by_id($previewcontextid);
2138 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2139 $previewcontext, $questionid,
2140 $context, $component, $filearea, $args,
2141 $forcedownload, $options), 'callbackmissing');
2143 if ($result === 'callbackmissing') {
2144 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2145 "{$previewcomponent}_question_preview_pluginfile callback. " .
2146 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
2149 send_file_not_found();
2152 // 2. A question being attempted in the normal way.
2153 $qubaid = (int)$qubaidorpreview;
2154 $slot = (int)array_shift($args);
2156 $module = $DB->get_field('question_usages', 'component',
2157 array('id' => $qubaid));
2158 if (!$module) {
2159 send_file_not_found();
2162 if ($module === 'core_question_preview') {
2163 require_once($CFG->dirroot . '/question/previewlib.php');
2164 return question_preview_question_pluginfile($course, $context,
2165 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2167 } else {
2168 $dir = core_component::get_component_directory($module);
2169 if (!file_exists("$dir/lib.php")) {
2170 send_file_not_found();
2172 include_once("$dir/lib.php");
2174 $filefunction = $module . '_question_pluginfile';
2175 if (function_exists($filefunction)) {
2176 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2177 $args, $forcedownload, $options);
2180 // Okay, we're here so lets check for function without 'mod_'.
2181 if (strpos($module, 'mod_') === 0) {
2182 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2183 if (function_exists($filefunctionold)) {
2184 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2185 $args, $forcedownload, $options);
2189 send_file_not_found();
2194 * Serve questiontext files in the question text when they are displayed in this report.
2196 * @package core_files
2197 * @category files
2198 * @param context $previewcontext the context in which the preview is happening.
2199 * @param int $questionid the question id.
2200 * @param context $filecontext the file (question) context.
2201 * @param string $filecomponent the component the file belongs to.
2202 * @param string $filearea the file area.
2203 * @param array $args remaining file args.
2204 * @param bool $forcedownload.
2205 * @param array $options additional options affecting the file serving.
2207 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2208 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2209 global $DB;
2211 // Verify that contextid matches the question.
2212 $question = $DB->get_record_sql('
2213 SELECT q.*, qc.contextid
2214 FROM {question} q
2215 JOIN {question_categories} qc ON qc.id = q.category
2216 WHERE q.id = :id AND qc.contextid = :contextid',
2217 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2219 // Check the capability.
2220 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2221 require_login($course, false, $cm);
2223 question_require_capability_on($question, 'use');
2225 $fs = get_file_storage();
2226 $relativepath = implode('/', $args);
2227 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2228 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2229 send_file_not_found();
2232 send_stored_file($file, 0, 0, $forcedownload, $options);
2236 * Create url for question export
2238 * @param int $contextid, current context
2239 * @param int $categoryid, categoryid
2240 * @param string $format
2241 * @param string $withcategories
2242 * @param string $ithcontexts
2243 * @param moodle_url export file url
2245 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2246 $withcontexts, $filename) {
2247 global $CFG;
2248 $urlbase = "$CFG->wwwroot/pluginfile.php";
2249 return moodle_url::make_file_url($urlbase,
2250 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2251 "/{$withcontexts}/{$filename}", true);
2255 * Return a list of page types
2256 * @param string $pagetype current page type
2257 * @param stdClass $parentcontext Block's parent context
2258 * @param stdClass $currentcontext Current context of block
2260 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2261 global $CFG;
2262 $types = array(
2263 'question-*'=>get_string('page-question-x', 'question'),
2264 'question-edit'=>get_string('page-question-edit', 'question'),
2265 'question-category'=>get_string('page-question-category', 'question'),
2266 'question-export'=>get_string('page-question-export', 'question'),
2267 'question-import'=>get_string('page-question-import', 'question')
2269 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2270 require_once($CFG->dirroot . '/course/lib.php');
2271 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2272 } else {
2273 return $types;
2278 * Does an activity module use the question bank?
2280 * @param string $modname The name of the module (without mod_ prefix).
2281 * @return bool true if the module uses questions.
2283 function question_module_uses_questions($modname) {
2284 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2285 return true;
2288 $component = 'mod_'.$modname;
2289 if (component_callback_exists($component, 'question_pluginfile')) {
2290 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2291 return true;
2294 return false;