MDL-67585 core_course: add content_item_service class
[moodle.git] / lib / questionlib.php
blob26cf0835e301f09d6985b319a857963d243fa333
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
28 * @package moodlecore
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') || die();
37 require_once($CFG->dirroot . '/question/engine/lib.php');
38 require_once($CFG->dirroot . '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
44 /**
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
50 /**
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
57 /**
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
64 /**
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
79 if ($key === false) {
80 return $neworder;
82 // Work out the other index.
83 $otherkey = $key + $direction;
84 if (!isset($neworder[$otherkey])) {
85 return $neworder;
87 // Do the swap.
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
91 return $neworder;
94 /**
95 * Save a new question type order to the config_plugins table.
96 * @global object
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
101 global $DB;
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
110 set_config($sortvar, $index + 1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
123 // Are they used by the core question system?
124 if (question_engine::questions_in_use($questionids)) {
125 return true;
128 // Check if any plugins are using these questions.
129 $callbacksbytype = get_plugins_with_function('questions_in_use');
130 foreach ($callbacksbytype as $callbacks) {
131 foreach ($callbacks as $function) {
132 if ($function($questionids)) {
133 return true;
138 // Finally check legacy callback.
139 $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
140 foreach ($legacycallbacks as $plugin => $function) {
141 debugging($plugin . ' implements deprecated method ' . $function .
142 '. ' . $plugin . '_questions_in_use should be implemented instead.', DEBUG_DEVELOPER);
144 if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
145 continue; // Already done.
148 foreach ($questionids as $questionid) {
149 if (!empty($function($questionid))) {
150 return true;
155 return false;
159 * Determine whether there arey any questions belonging to this context, that is whether any of its
160 * question categories contain any questions. This will return true even if all the questions are
161 * hidden.
163 * @param mixed $context either a context object, or a context id.
164 * @return boolean whether any of the question categories beloning to this context have
165 * any questions in them.
167 function question_context_has_any_questions($context) {
168 global $DB;
169 if (is_object($context)) {
170 $contextid = $context->id;
171 } else if (is_numeric($context)) {
172 $contextid = $context;
173 } else {
174 print_error('invalidcontextinhasanyquestions', 'question');
176 return $DB->record_exists_sql("SELECT *
177 FROM {question} q
178 JOIN {question_categories} qc ON qc.id = q.category
179 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
183 * Check whether a given grade is one of a list of allowed options. If not,
184 * depending on $matchgrades, either return the nearest match, or return false
185 * to signal an error.
186 * @param array $gradeoptionsfull list of valid options
187 * @param int $grade grade to be tested
188 * @param string $matchgrades 'error' or 'nearest'
189 * @return mixed either 'fixed' value or false if error.
191 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
193 if ($matchgrades == 'error') {
194 // (Almost) exact match, or an error.
195 foreach ($gradeoptionsfull as $value => $option) {
196 // Slightly fuzzy test, never check floats for equality.
197 if (abs($grade - $value) < 0.00001) {
198 return $value; // Be sure the return the proper value.
201 // Didn't find a match so that's an error.
202 return false;
204 } else if ($matchgrades == 'nearest') {
205 // Work out nearest value
206 $best = false;
207 $bestmismatch = 2;
208 foreach ($gradeoptionsfull as $value => $option) {
209 $newmismatch = abs($grade - $value);
210 if ($newmismatch < $bestmismatch) {
211 $best = $value;
212 $bestmismatch = $newmismatch;
215 return $best;
217 } else {
218 // Unknow option passed.
219 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
220 ' passed to match_grade_options');
225 * Remove stale questions from a category.
227 * While questions should not be left behind when they are not used any more,
228 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
229 * this happens, the users are unable to delete the question category unless
230 * they move those stale questions to another one category, but to them the
231 * category is empty as it does not contain anything. The purpose of this function
232 * is to detect the questions that may have gone stale and remove them.
234 * You will typically use this prior to checking if the category contains questions.
236 * The stale questions (unused and hidden to the user) handled are:
237 * - hidden questions
238 * - random questions
240 * @param int $categoryid The category ID.
242 function question_remove_stale_questions_from_category($categoryid) {
243 global $DB;
245 $select = 'category = :categoryid AND (qtype = :qtype OR hidden = :hidden)';
246 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'hidden' => 1];
247 $questions = $DB->get_recordset_select("question", $select, $params, '', 'id');
248 foreach ($questions as $question) {
249 // The function question_delete_question does not delete questions in use.
250 question_delete_question($question->id);
252 $questions->close();
256 * Category is about to be deleted,
257 * 1/ All questions are deleted for this question category.
258 * 2/ Any questions that can't be deleted are moved to a new category
259 * NOTE: this function is called from lib/db/upgrade.php
261 * @param object|core_course_category $category course category object
263 function question_category_delete_safe($category) {
264 global $DB;
265 $criteria = array('category' => $category->id);
266 $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
267 $rescue = null; // See the code around the call to question_save_from_deletion.
269 // Deal with any questions in the category.
270 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
272 // Try to delete each question.
273 foreach ($questions as $question) {
274 question_delete_question($question->id);
277 // Check to see if there were any questions that were kept because
278 // they are still in use somehow, even though quizzes in courses
279 // in this category will already have been deleted. This could
280 // happen, for example, if questions are added to a course,
281 // and then that course is moved to another category (MDL-14802).
282 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
283 if (!empty($questionids)) {
284 $parentcontextid = SYSCONTEXTID;
285 $name = get_string('unknown', 'question');
286 if ($context !== false) {
287 $name = $context->get_context_name();
288 $parentcontext = $context->get_parent_context();
289 if ($parentcontext) {
290 $parentcontextid = $parentcontext->id;
293 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
297 // Now delete the category.
298 $DB->delete_records('question_categories', array('id' => $category->id));
302 * Tests whether any question in a category is used by any part of Moodle.
304 * @param integer $categoryid a question category id.
305 * @param boolean $recursive whether to check child categories too.
306 * @return boolean whether any question in this category is in use.
308 function question_category_in_use($categoryid, $recursive = false) {
309 global $DB;
311 //Look at each question in the category
312 if ($questions = $DB->get_records_menu('question',
313 array('category' => $categoryid), '', 'id, 1')) {
314 if (questions_in_use(array_keys($questions))) {
315 return true;
318 if (!$recursive) {
319 return false;
322 //Look under child categories recursively
323 if ($children = $DB->get_records('question_categories',
324 array('parent' => $categoryid), '', 'id, 1')) {
325 foreach ($children as $child) {
326 if (question_category_in_use($child->id, $recursive)) {
327 return true;
332 return false;
336 * Deletes question and all associated data from the database
338 * It will not delete a question if it is used by an activity module
339 * @param object $question The question being deleted
341 function question_delete_question($questionid) {
342 global $DB;
344 $question = $DB->get_record_sql('
345 SELECT q.*, qc.contextid
346 FROM {question} q
347 JOIN {question_categories} qc ON qc.id = q.category
348 WHERE q.id = ?', array($questionid));
349 if (!$question) {
350 // In some situations, for example if this was a child of a
351 // Cloze question that was previously deleted, the question may already
352 // have gone. In this case, just do nothing.
353 return;
356 // Do not delete a question if it is used by an activity module
357 if (questions_in_use(array($questionid))) {
358 return;
361 $dm = new question_engine_data_mapper();
362 $dm->delete_previews($questionid);
364 // delete questiontype-specific data
365 question_bank::get_qtype($question->qtype, false)->delete_question(
366 $questionid, $question->contextid);
368 // Delete all tag instances.
369 core_tag_tag::remove_all_item_tags('core_question', 'question', $question->id);
371 // Now recursively delete all child questions
372 if ($children = $DB->get_records('question',
373 array('parent' => $questionid), '', 'id, qtype')) {
374 foreach ($children as $child) {
375 if ($child->id != $questionid) {
376 question_delete_question($child->id);
381 // Finally delete the question record itself
382 $DB->delete_records('question', array('id' => $questionid));
383 question_bank::notify_question_edited($questionid);
385 // Log the deletion of this question.
386 $event = \core\event\question_deleted::create_from_question_instance($question);
387 $event->add_record_snapshot('question', $question);
388 $event->trigger();
392 * All question categories and their questions are deleted for this context id.
394 * @param object $contextid The contextid to delete question categories from
395 * @return array Feedback from deletes (if any)
397 function question_delete_context($contextid) {
398 global $DB;
400 //To store feedback to be showed at the end of the process
401 $feedbackdata = array();
403 //Cache some strings
404 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
405 $fields = 'id, parent, name, contextid';
406 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
407 //Sort categories following their tree (parent-child) relationships
408 //this will make the feedback more readable
409 $categories = sort_categories_by_tree($categories);
411 foreach ($categories as $category) {
412 question_category_delete_safe($category);
414 //Fill feedback
415 $feedbackdata[] = array($category->name, $strcatdeleted);
418 return $feedbackdata;
422 * All question categories and their questions are deleted for this course.
424 * @param stdClass $course an object representing the activity
425 * @param boolean $feedback to specify if the process must output a summary of its work
426 * @return boolean
428 function question_delete_course($course, $feedback=true) {
429 $coursecontext = context_course::instance($course->id);
430 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
432 // Inform about changes performed if feedback is enabled.
433 if ($feedback && $feedbackdata) {
434 $table = new html_table();
435 $table->head = array(get_string('category', 'question'), get_string('action'));
436 $table->data = $feedbackdata;
437 echo html_writer::table($table);
439 return true;
443 * Category is about to be deleted,
444 * 1/ All question categories and their questions are deleted for this course category.
445 * 2/ All questions are moved to new category
447 * @param object|core_course_category $category course category object
448 * @param object|core_course_category $newcategory empty means everything deleted, otherwise id of
449 * category where content moved
450 * @param boolean $feedback to specify if the process must output a summary of its work
451 * @return boolean
453 function question_delete_course_category($category, $newcategory, $feedback=true) {
454 global $DB, $OUTPUT;
456 $context = context_coursecat::instance($category->id);
457 if (empty($newcategory)) {
458 $feedbackdata = question_delete_context($context->id, $feedback);
460 // Output feedback if requested.
461 if ($feedback && $feedbackdata) {
462 $table = new html_table();
463 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
464 $table->data = $feedbackdata;
465 echo html_writer::table($table);
468 } else {
469 // Move question categories to the new context.
470 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
471 return false;
474 // Only move question categories if there is any question category at all!
475 if ($topcategory = question_get_top_category($context->id)) {
476 $newtopcategory = question_get_top_category($newcontext->id, true);
478 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
479 $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
480 // Now delete the top category.
481 $DB->delete_records('question_categories', array('id' => $topcategory->id));
484 if ($feedback) {
485 $a = new stdClass();
486 $a->oldplace = $context->get_context_name();
487 $a->newplace = $newcontext->get_context_name();
488 echo $OUTPUT->notification(
489 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
493 return true;
497 * Enter description here...
499 * @param array $questionids of question ids
500 * @param object $newcontextid the context to create the saved category in.
501 * @param string $oldplace a textual description of the think being deleted,
502 * e.g. from get_context_name
503 * @param object $newcategory
504 * @return mixed false on
506 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
507 $newcategory = null) {
508 global $DB;
510 // Make a category in the parent context to move the questions to.
511 if (is_null($newcategory)) {
512 $newcategory = new stdClass();
513 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
514 $newcategory->contextid = $newcontextid;
515 // Max length of column name in question_categories is 255.
516 $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
517 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
518 $newcategory->sortorder = 999;
519 $newcategory->stamp = make_unique_id_code();
520 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
523 // Move any remaining questions to the 'saved' category.
524 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
525 return false;
527 return $newcategory;
531 * All question categories and their questions are deleted for this activity.
533 * @param object $cm the course module object representing the activity
534 * @param boolean $feedback to specify if the process must output a summary of its work
535 * @return boolean
537 function question_delete_activity($cm, $feedback=true) {
538 global $DB;
540 $modcontext = context_module::instance($cm->id);
541 $feedbackdata = question_delete_context($modcontext->id, $feedback);
542 // Inform about changes performed if feedback is enabled.
543 if ($feedback && $feedbackdata) {
544 $table = new html_table();
545 $table->head = array(get_string('category', 'question'), get_string('action'));
546 $table->data = $feedbackdata;
547 echo html_writer::table($table);
549 return true;
553 * This function will handle moving all tag instances to a new context for a
554 * given list of questions.
556 * Questions can be tagged in up to two contexts:
557 * 1.) The context the question exists in.
558 * 2.) The course context (if the question context is a higher context.
559 * E.g. course category context or system context.
561 * This means a question that exists in a higher context (e.g. course cat or
562 * system context) may have multiple groups of tags in any number of child
563 * course contexts.
565 * Questions in the course category context can be move "down" a context level
566 * into one of their child course contexts or activity contexts which affects the
567 * availability of that question in other courses / activities.
569 * In this case it makes the questions no longer available in the other course or
570 * activity contexts so we need to make sure that the tag instances in those other
571 * contexts are removed.
573 * @param stdClass[] $questions The list of question being moved (must include
574 * the id and contextid)
575 * @param context $newcontext The Moodle context the questions are being moved to
577 function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
578 // If the questions are moving to a new course/activity context then we need to
579 // find any existing tag instances from any unavailable course contexts and
580 // delete them because they will no longer be applicable (we don't support
581 // tagging questions across courses).
582 $instancestodelete = [];
583 $instancesfornewcontext = [];
584 $newcontextparentids = $newcontext->get_parent_context_ids();
585 $questionids = array_map(function($question) {
586 return $question->id;
587 }, $questions);
588 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
590 foreach ($questions as $question) {
591 $tagobjects = $questionstagobjects[$question->id];
593 foreach ($tagobjects as $tagobject) {
594 $tagid = $tagobject->taginstanceid;
595 $tagcontextid = $tagobject->taginstancecontextid;
596 $istaginnewcontext = $tagcontextid == $newcontext->id;
597 $istaginquestioncontext = $tagcontextid == $question->contextid;
599 if ($istaginnewcontext) {
600 // This tag instance is already in the correct context so we can
601 // ignore it.
602 continue;
605 if ($istaginquestioncontext) {
606 // This tag instance is in the question context so it needs to be
607 // updated.
608 $instancesfornewcontext[] = $tagid;
609 continue;
612 // These tag instances are in neither the new context nor the
613 // question context so we need to determine what to do based on
614 // the context they are in and the new question context.
615 $tagcontext = context::instance_by_id($tagcontextid);
616 $tagcoursecontext = $tagcontext->get_course_context(false);
617 // The tag is in a course context if get_course_context() returns
618 // itself.
619 $istaginstancecontextcourse = !empty($tagcoursecontext)
620 && $tagcontext->id == $tagcoursecontext->id;
622 if ($istaginstancecontextcourse) {
623 // If the tag instance is in a course context we need to add some
624 // special handling.
625 $tagcontextparentids = $tagcontext->get_parent_context_ids();
626 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
627 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
629 if ($isnewcontextaparent) {
630 // If the tag instance is a course context tag and the new
631 // context is still a parent context to the tag context then
632 // we can leave this tag where it is.
633 continue;
634 } else if ($isnewcontextachild) {
635 // If the new context is a child context (e.g. activity) of this
636 // tag instance then we should move all of this tag instance
637 // down into the activity context along with the question.
638 $instancesfornewcontext[] = $tagid;
639 } else {
640 // If the tag is in a course context that is no longer a parent
641 // or child of the new context then this tag instance should be
642 // removed.
643 $instancestodelete[] = $tagid;
645 } else {
646 // This is a catch all for any tag instances not in the question
647 // context or a course context. These tag instances should be
648 // updated to the new context id. This will clean up old invalid
649 // data.
650 $instancesfornewcontext[] = $tagid;
655 if (!empty($instancestodelete)) {
656 // Delete any course context tags that may no longer be valid.
657 core_tag_tag::delete_instances_by_id($instancestodelete);
660 if (!empty($instancesfornewcontext)) {
661 // Update the tag instances to the new context id.
662 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
667 * This function should be considered private to the question bank, it is called from
668 * question/editlib.php question/contextmoveq.php and a few similar places to to the
669 * work of actually moving questions and associated data. However, callers of this
670 * function also have to do other work, which is why you should not call this method
671 * directly from outside the questionbank.
673 * @param array $questionids of question ids.
674 * @param integer $newcategoryid the id of the category to move to.
676 function question_move_questions_to_category($questionids, $newcategoryid) {
677 global $DB;
679 $newcontextid = $DB->get_field('question_categories', 'contextid',
680 array('id' => $newcategoryid));
681 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
682 $questions = $DB->get_records_sql("
683 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
684 FROM {question} q
685 JOIN {question_categories} qc ON q.category = qc.id
686 WHERE q.id $questionidcondition", $params);
687 foreach ($questions as $question) {
688 if ($newcontextid != $question->contextid) {
689 question_bank::get_qtype($question->qtype)->move_files(
690 $question->id, $question->contextid, $newcontextid);
692 // Check whether there could be a clash of idnumbers in the new category.
693 if (((string) $question->idnumber !== '') &&
694 $DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $newcategoryid])) {
695 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
696 [$newcategoryid, $question->idnumber . '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
697 $unique = 1;
698 if (count($rec)) {
699 $rec = reset($rec);
700 $idnumber = $rec->idnumber;
701 if (strpos($idnumber, '_') !== false) {
702 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
705 // For the move process, add a numerical increment to the idnumber. This means that if a question is
706 // mistakenly moved then the idnumber will not be completely lost.
707 $q = new stdClass();
708 $q->id = $question->id;
709 $q->category = $newcategoryid;
710 $q->idnumber = $question->idnumber . '_' . $unique;
711 $DB->update_record('question', $q);
714 // Log this question move.
715 $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
716 ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategoryid]);
717 $event->trigger();
720 // Move the questions themselves.
721 $DB->set_field_select('question', 'category', $newcategoryid,
722 "id $questionidcondition", $params);
724 // Move any subquestions belonging to them.
725 $DB->set_field_select('question', 'category', $newcategoryid,
726 "parent $questionidcondition", $params);
728 $newcontext = context::instance_by_id($newcontextid);
729 question_move_question_tags_to_new_context($questions, $newcontext);
731 // TODO Deal with datasets.
733 // Purge these questions from the cache.
734 foreach ($questions as $question) {
735 question_bank::notify_question_edited($question->id);
738 return true;
742 * This function helps move a question cateogry to a new context by moving all
743 * the files belonging to all the questions to the new context.
744 * Also moves subcategories.
745 * @param integer $categoryid the id of the category being moved.
746 * @param integer $oldcontextid the old context id.
747 * @param integer $newcontextid the new context id.
749 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
750 global $DB;
752 $questions = [];
753 $questionids = $DB->get_records_menu('question',
754 array('category' => $categoryid), '', 'id,qtype');
755 foreach ($questionids as $questionid => $qtype) {
756 question_bank::get_qtype($qtype)->move_files(
757 $questionid, $oldcontextid, $newcontextid);
758 // Purge this question from the cache.
759 question_bank::notify_question_edited($questionid);
761 $questions[] = (object) [
762 'id' => $questionid,
763 'contextid' => $oldcontextid
767 $newcontext = context::instance_by_id($newcontextid);
768 question_move_question_tags_to_new_context($questions, $newcontext);
770 $subcatids = $DB->get_records_menu('question_categories',
771 array('parent' => $categoryid), '', 'id,1');
772 foreach ($subcatids as $subcatid => $notused) {
773 $DB->set_field('question_categories', 'contextid', $newcontextid,
774 array('id' => $subcatid));
775 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
780 * Generate the URL for starting a new preview of a given question with the given options.
781 * @param integer $questionid the question to preview.
782 * @param string $preferredbehaviour the behaviour to use for the preview.
783 * @param float $maxmark the maximum to mark the question out of.
784 * @param question_display_options $displayoptions the display options to use.
785 * @param int $variant the variant of the question to preview. If null, one will
786 * be picked randomly.
787 * @param object $context context to run the preview in (affects things like
788 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
789 * @return moodle_url the URL.
791 function question_preview_url($questionid, $preferredbehaviour = null,
792 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
794 $params = array('id' => $questionid);
796 if (is_null($context)) {
797 global $PAGE;
798 $context = $PAGE->context;
800 if ($context->contextlevel == CONTEXT_MODULE) {
801 $params['cmid'] = $context->instanceid;
802 } else if ($context->contextlevel == CONTEXT_COURSE) {
803 $params['courseid'] = $context->instanceid;
806 if (!is_null($preferredbehaviour)) {
807 $params['behaviour'] = $preferredbehaviour;
810 if (!is_null($maxmark)) {
811 $params['maxmark'] = format_float($maxmark, -1);
814 if (!is_null($displayoptions)) {
815 $params['correctness'] = $displayoptions->correctness;
816 $params['marks'] = $displayoptions->marks;
817 $params['markdp'] = $displayoptions->markdp;
818 $params['feedback'] = (bool) $displayoptions->feedback;
819 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
820 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
821 $params['history'] = (bool) $displayoptions->history;
824 if ($variant) {
825 $params['variant'] = $variant;
828 return new moodle_url('/question/preview.php', $params);
832 * @return array that can be passed as $params to the {@link popup_action} constructor.
834 function question_preview_popup_params() {
835 return array(
836 'height' => 600,
837 'width' => 800,
842 * Given a list of ids, load the basic information about a set of questions from
843 * the questions table. The $join and $extrafields arguments can be used together
844 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
845 * read the code below to see how the SQL is assembled. Throws exceptions on error.
847 * @param array $questionids array of question ids to load. If null, then all
848 * questions matched by $join will be loaded.
849 * @param string $extrafields extra SQL code to be added to the query.
850 * @param string $join extra SQL code to be added to the query.
851 * @param array $extraparams values for any placeholders in $join.
852 * You must use named placeholders.
853 * @param string $orderby what to order the results by. Optional, default is unspecified order.
855 * @return array partially complete question objects. You need to call get_question_options
856 * on them before they can be properly used.
858 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
859 $extraparams = array(), $orderby = '') {
860 global $DB;
862 if ($questionids === null) {
863 $where = '';
864 $params = array();
865 } else {
866 if (empty($questionids)) {
867 return array();
870 list($questionidcondition, $params) = $DB->get_in_or_equal(
871 $questionids, SQL_PARAMS_NAMED, 'qid0000');
872 $where = 'WHERE q.id ' . $questionidcondition;
875 if ($join) {
876 $join = 'JOIN ' . $join;
879 if ($extrafields) {
880 $extrafields = ', ' . $extrafields;
883 if ($orderby) {
884 $orderby = 'ORDER BY ' . $orderby;
887 $sql = "SELECT q.*, qc.contextid{$extrafields}
888 FROM {question} q
889 JOIN {question_categories} qc ON q.category = qc.id
890 {$join}
891 {$where}
892 {$orderby}";
894 // Load the questions.
895 $questions = $DB->get_records_sql($sql, $extraparams + $params);
896 foreach ($questions as $question) {
897 $question->_partiallyloaded = true;
900 return $questions;
904 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
905 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
906 * read the code below to see how the SQL is assembled. Throws exceptions on error.
908 * @param array $questionids array of question ids.
909 * @param string $extrafields extra SQL code to be added to the query.
910 * @param string $join extra SQL code to be added to the query.
911 * @param array $extraparams values for any placeholders in $join.
912 * You are strongly recommended to use named placeholder.
914 * @return array question objects.
916 function question_load_questions($questionids, $extrafields = '', $join = '') {
917 $questions = question_preload_questions($questionids, $extrafields, $join);
919 // Load the question type specific information
920 if (!get_question_options($questions)) {
921 return 'Could not load the question options';
924 return $questions;
928 * Private function to factor common code out of get_question_options().
930 * @param object $question the question to tidy.
931 * @param stdClass $category The question_categories record for the given $question.
932 * @param stdClass[]|null $tagobjects The tags for the given $question.
933 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
935 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
936 // Load question-type specific fields.
937 if (!question_bank::is_qtype_installed($question->qtype)) {
938 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
939 'qtype_missingtype')) . $question->questiontext;
941 question_bank::get_qtype($question->qtype)->get_question_options($question);
943 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
944 $question->defaultmark += 0;
945 $question->penalty += 0;
947 if (isset($question->_partiallyloaded)) {
948 unset($question->_partiallyloaded);
951 $question->categoryobject = $category;
953 if (!is_null($tagobjects)) {
954 $categorycontext = context::instance_by_id($category->contextid);
955 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
956 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
957 $question->coursetags = $sortedtagobjects->coursetags;
958 $question->tagobjects = $sortedtagobjects->tagobjects;
959 $question->tags = $sortedtagobjects->tags;
964 * Updates the question objects with question type specific
965 * information by calling {@link get_question_options()}
967 * Can be called either with an array of question objects or with a single
968 * question object.
970 * @param mixed $questions Either an array of question objects to be updated
971 * or just a single question object
972 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
973 * @param stdClass[] $filtercourses The courses to filter the course tags by.
974 * @return bool Indicates success or failure.
976 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
977 global $DB;
979 $questionlist = is_array($questions) ? $questions : [$questions];
980 $categoryids = [];
981 $questionids = [];
983 if (empty($questionlist)) {
984 return true;
987 foreach ($questionlist as $question) {
988 $questionids[] = $question->id;
990 if (!in_array($question->category, $categoryids)) {
991 $categoryids[] = $question->category;
995 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
997 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
998 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
999 } else {
1000 $tagobjectsbyquestion = null;
1003 foreach ($questionlist as $question) {
1004 if (is_null($tagobjectsbyquestion)) {
1005 $tagobjects = null;
1006 } else {
1007 $tagobjects = $tagobjectsbyquestion[$question->id];
1010 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
1013 return true;
1017 * Sort question tags by course or normal tags.
1019 * This function also search tag instances that may have a context id that don't match either a course or
1020 * question context and fix the data setting the correct context id.
1022 * @param stdClass[] $tagobjects The tags for the given $question.
1023 * @param stdClass $categorycontext The question categories context.
1024 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1025 * @return stdClass $sortedtagobjects Sorted tag objects.
1027 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
1029 // Questions can have two sets of tag instances. One set at the
1030 // course context level and another at the context the question
1031 // belongs to (e.g. course category, system etc).
1032 $sortedtagobjects = new stdClass();
1033 $sortedtagobjects->coursetagobjects = [];
1034 $sortedtagobjects->coursetags = [];
1035 $sortedtagobjects->tagobjects = [];
1036 $sortedtagobjects->tags = [];
1037 $taginstanceidstonormalise = [];
1038 $filtercoursecontextids = [];
1039 $hasfiltercourses = !empty($filtercourses);
1041 if ($hasfiltercourses) {
1042 // If we're being asked to filter the course tags by a set of courses
1043 // then get the context ids to filter below.
1044 $filtercoursecontextids = array_map(function($course) {
1045 $coursecontext = context_course::instance($course->id);
1046 return $coursecontext->id;
1047 }, $filtercourses);
1050 foreach ($tagobjects as $tagobject) {
1051 $tagcontextid = $tagobject->taginstancecontextid;
1052 $tagcontext = context::instance_by_id($tagcontextid);
1053 $tagcoursecontext = $tagcontext->get_course_context(false);
1054 // This is a course tag if the tag context is a course context which
1055 // doesn't match the question's context. Any tag in the question context
1056 // is not considered a course tag, it belongs to the question.
1057 $iscoursetag = $tagcoursecontext
1058 && $tagcontext->id == $tagcoursecontext->id
1059 && $tagcontext->id != $categorycontext->id;
1061 if ($iscoursetag) {
1062 // Any tag instance in a course context level is considered a course tag.
1063 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1064 // Add the tag to the list of course tags if we aren't being
1065 // asked to filter or if this tag is in the list of courses
1066 // we're being asked to filter by.
1067 $sortedtagobjects->coursetagobjects[] = $tagobject;
1068 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1070 } else {
1071 // All non course context level tag instances or tags in the question
1072 // context belong to the context that the question was created in.
1073 $sortedtagobjects->tagobjects[] = $tagobject;
1074 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1076 // Due to legacy tag implementations that don't force the recording
1077 // of a context id, some tag instances may have context ids that don't
1078 // match either a course context or the question context. In this case
1079 // we should take the opportunity to fix up the data and set the correct
1080 // context id.
1081 if ($tagcontext->id != $categorycontext->id) {
1082 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1083 // Update the object properties to reflect the DB update that will
1084 // happen below.
1085 $tagobject->taginstancecontextid = $categorycontext->id;
1090 if (!empty($taginstanceidstonormalise)) {
1091 // If we found any tag instances with incorrect context id data then we can
1092 // correct those values now by setting them to the question context id.
1093 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1096 return $sortedtagobjects;
1100 * Print the icon for the question type
1102 * @param object $question The question object for which the icon is required.
1103 * Only $question->qtype is used.
1104 * @return string the HTML for the img tag.
1106 function print_question_icon($question) {
1107 global $PAGE;
1108 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
1112 * Creates a stamp that uniquely identifies this version of the question
1114 * In future we want this to use a hash of the question data to guarantee that
1115 * identical versions have the same version stamp.
1117 * @param object $question
1118 * @return string A unique version stamp
1120 function question_hash($question) {
1121 return make_unique_id_code();
1124 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1127 * returns the categories with their names ordered following parent-child relationships
1128 * finally it tries to return pending categories (those being orphaned, whose parent is
1129 * incorrect) to avoid missing any category from original array.
1131 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1132 global $DB;
1134 $children = array();
1135 $keys = array_keys($categories);
1137 foreach ($keys as $key) {
1138 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1139 $children[$key] = $categories[$key];
1140 $categories[$key]->processed = true;
1141 $children = $children + sort_categories_by_tree(
1142 $categories, $children[$key]->id, $level+1);
1145 //If level = 1, we have finished, try to look for non processed categories
1146 // (bad parent) and sort them too
1147 if ($level == 1) {
1148 foreach ($keys as $key) {
1149 // If not processed and it's a good candidate to start (because its
1150 // parent doesn't exist in the course)
1151 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1152 array('contextid' => $categories[$key]->contextid,
1153 'id' => $categories[$key]->parent))) {
1154 $children[$key] = $categories[$key];
1155 $categories[$key]->processed = true;
1156 $children = $children + sort_categories_by_tree(
1157 $categories, $children[$key]->id, $level + 1);
1161 return $children;
1165 * Private method, only for the use of add_indented_names().
1167 * Recursively adds an indentedname field to each category, starting with the category
1168 * with id $id, and dealing with that category and all its children, and
1169 * return a new array, with those categories in the right order.
1171 * @param array $categories an array of categories which has had childids
1172 * fields added by flatten_category_tree(). Passed by reference for
1173 * performance only. It is not modfied.
1174 * @param int $id the category to start the indenting process from.
1175 * @param int $depth the indent depth. Used in recursive calls.
1176 * @return array a new array of categories, in the right order for the tree.
1178 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1180 // Indent the name of this category.
1181 $newcategories = array();
1182 $newcategories[$id] = $categories[$id];
1183 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
1184 $categories[$id]->name;
1186 // Recursively indent the children.
1187 foreach ($categories[$id]->childids as $childid) {
1188 if ($childid != $nochildrenof) {
1189 $newcategories = $newcategories + flatten_category_tree(
1190 $categories, $childid, $depth + 1, $nochildrenof);
1194 // Remove the childids array that were temporarily added.
1195 unset($newcategories[$id]->childids);
1197 return $newcategories;
1201 * Format categories into an indented list reflecting the tree structure.
1203 * @param array $categories An array of category objects, for example from the.
1204 * @return array The formatted list of categories.
1206 function add_indented_names($categories, $nochildrenof = -1) {
1208 // Add an array to each category to hold the child category ids. This array
1209 // will be removed again by flatten_category_tree(). It should not be used
1210 // outside these two functions.
1211 foreach (array_keys($categories) as $id) {
1212 $categories[$id]->childids = array();
1215 // Build the tree structure, and record which categories are top-level.
1216 // We have to be careful, because the categories array may include published
1217 // categories from other courses, but not their parents.
1218 $toplevelcategoryids = array();
1219 foreach (array_keys($categories) as $id) {
1220 if (!empty($categories[$id]->parent) &&
1221 array_key_exists($categories[$id]->parent, $categories)) {
1222 $categories[$categories[$id]->parent]->childids[] = $id;
1223 } else {
1224 $toplevelcategoryids[] = $id;
1228 // Flatten the tree to and add the indents.
1229 $newcategories = array();
1230 foreach ($toplevelcategoryids as $id) {
1231 $newcategories = $newcategories + flatten_category_tree(
1232 $categories, $id, 0, $nochildrenof);
1235 return $newcategories;
1239 * Output a select menu of question categories.
1241 * Categories from this course and (optionally) published categories from other courses
1242 * are included. Optionally, only categories the current user may edit can be included.
1244 * @param integer $courseid the id of the course to get the categories for.
1245 * @param integer $published if true, include publised categories from other courses.
1246 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1247 * @param integer $selected optionally, the id of a category to be selected by
1248 * default in the dropdown.
1250 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1251 $selected = "", $nochildrenof = -1) {
1252 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1253 false, $nochildrenof);
1254 if ($selected) {
1255 $choose = '';
1256 } else {
1257 $choose = 'choosedots';
1259 $options = array();
1260 foreach ($categoriesarray as $group => $opts) {
1261 $options[] = array($group => $opts);
1263 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1264 $attrs = array(
1265 'id' => 'id_movetocategory',
1266 'class' => 'custom-select',
1267 'data-action' => 'toggle',
1268 'data-togglegroup' => 'qbank',
1269 'data-toggle' => 'action',
1270 'disabled' => true,
1272 echo html_writer::select($options, 'category', $selected, $choose, $attrs);
1276 * @param integer $contextid a context id.
1277 * @return object the default question category for that context, or false if none.
1279 function question_get_default_category($contextid) {
1280 global $DB;
1281 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1282 array($contextid), 'id', '*', 0, 1);
1283 if (!empty($category)) {
1284 return reset($category);
1285 } else {
1286 return false;
1291 * Gets the top category in the given context.
1292 * This function can optionally create the top category if it doesn't exist.
1294 * @param int $contextid A context id.
1295 * @param bool $create Whether create a top category if it doesn't exist.
1296 * @return bool|stdClass The top question category for that context, or false if none.
1298 function question_get_top_category($contextid, $create = false) {
1299 global $DB;
1300 $category = $DB->get_record('question_categories',
1301 array('contextid' => $contextid, 'parent' => 0));
1303 if (!$category && $create) {
1304 // We need to make one.
1305 $category = new stdClass();
1306 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1307 $category->info = '';
1308 $category->contextid = $contextid;
1309 $category->parent = 0;
1310 $category->sortorder = 0;
1311 $category->stamp = make_unique_id_code();
1312 $category->id = $DB->insert_record('question_categories', $category);
1315 return $category;
1319 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1321 * @param array $contextids List of context ids
1322 * @return array
1324 function question_get_top_categories_for_contexts($contextids) {
1325 global $DB;
1327 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1328 list($insql, $params) = $DB->get_in_or_equal($contextids);
1329 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1330 $topcategories = $DB->get_fieldset_sql($sql, $params);
1332 return $topcategories;
1336 * Gets the default category in the most specific context.
1337 * If no categories exist yet then default ones are created in all contexts.
1339 * @param array $contexts The context objects for this context and all parent contexts.
1340 * @return object The default category - the category in the course context
1342 function question_make_default_categories($contexts) {
1343 global $DB;
1344 static $preferredlevels = array(
1345 CONTEXT_COURSE => 4,
1346 CONTEXT_MODULE => 3,
1347 CONTEXT_COURSECAT => 2,
1348 CONTEXT_SYSTEM => 1,
1351 $toreturn = null;
1352 $preferredness = 0;
1353 // If it already exists, just return it.
1354 foreach ($contexts as $key => $context) {
1355 $topcategory = question_get_top_category($context->id, true);
1356 if (!$exists = $DB->record_exists("question_categories",
1357 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1358 // Otherwise, we need to make one
1359 $category = new stdClass();
1360 $contextname = $context->get_context_name(false, true);
1361 // Max length of name field is 255.
1362 $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1363 $category->info = get_string('defaultinfofor', 'question', $contextname);
1364 $category->contextid = $context->id;
1365 $category->parent = $topcategory->id;
1366 // By default, all categories get this number, and are sorted alphabetically.
1367 $category->sortorder = 999;
1368 $category->stamp = make_unique_id_code();
1369 $category->id = $DB->insert_record('question_categories', $category);
1370 } else {
1371 $category = question_get_default_category($context->id);
1373 $thispreferredness = $preferredlevels[$context->contextlevel];
1374 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1375 $thispreferredness += 10;
1377 if ($thispreferredness > $preferredness) {
1378 $toreturn = $category;
1379 $preferredness = $thispreferredness;
1383 if (!is_null($toreturn)) {
1384 $toreturn = clone($toreturn);
1386 return $toreturn;
1390 * Get all the category objects, including a count of the number of questions in that category,
1391 * for all the categories in the lists $contexts.
1393 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1394 * @param string $sortorder used as the ORDER BY clause in the select statement.
1395 * @param bool $top Whether to return the top categories or not.
1396 * @return array of category objects.
1398 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1399 global $DB;
1400 $topwhere = $top ? '' : 'AND c.parent <> 0';
1401 return $DB->get_records_sql("
1402 SELECT c.*, (SELECT count(1) FROM {question} q
1403 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1404 FROM {question_categories} c
1405 WHERE c.contextid IN ($contexts) $topwhere
1406 ORDER BY $sortorder");
1410 * Output an array of question categories.
1412 * @param array $contexts The list of contexts.
1413 * @param bool $top Whether to return the top categories or not.
1414 * @param int $currentcat
1415 * @param bool $popupform
1416 * @param int $nochildrenof
1417 * @return array
1419 function question_category_options($contexts, $top = false, $currentcat = 0,
1420 $popupform = false, $nochildrenof = -1) {
1421 global $CFG;
1422 $pcontexts = array();
1423 foreach ($contexts as $context) {
1424 $pcontexts[] = $context->id;
1426 $contextslist = join(', ', $pcontexts);
1428 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1430 if ($top) {
1431 $categories = question_fix_top_names($categories);
1434 $categories = question_add_context_in_key($categories);
1435 $categories = add_indented_names($categories, $nochildrenof);
1437 // sort cats out into different contexts
1438 $categoriesarray = array();
1439 foreach ($pcontexts as $contextid) {
1440 $context = context::instance_by_id($contextid);
1441 $contextstring = $context->get_context_name(true, true);
1442 foreach ($categories as $category) {
1443 if ($category->contextid == $contextid) {
1444 $cid = $category->id;
1445 if ($currentcat != $cid || $currentcat == 0) {
1446 $a = new stdClass;
1447 $a->name = format_string($category->indentedname, true,
1448 array('context' => $context));
1449 if ($category->idnumber !== null && $category->idnumber !== '') {
1450 $a->idnumber = s($category->idnumber);
1452 if (!empty($category->questioncount)) {
1453 $a->questioncount = $category->questioncount;
1455 if (isset($a->idnumber) && isset($a->questioncount)) {
1456 $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
1457 } else if (isset($a->idnumber)) {
1458 $formattedname = get_string('categorynamewithidnumber', 'question', $a);
1459 } else if (isset($a->questioncount)) {
1460 $formattedname = get_string('categorynamewithcount', 'question', $a);
1461 } else {
1462 $formattedname = $a->name;
1464 $categoriesarray[$contextstring][$cid] = $formattedname;
1469 if ($popupform) {
1470 $popupcats = array();
1471 foreach ($categoriesarray as $contextstring => $optgroup) {
1472 $group = array();
1473 foreach ($optgroup as $key => $value) {
1474 $key = str_replace($CFG->wwwroot, '', $key);
1475 $group[$key] = $value;
1477 $popupcats[] = array($contextstring => $group);
1479 return $popupcats;
1480 } else {
1481 return $categoriesarray;
1485 function question_add_context_in_key($categories) {
1486 $newcatarray = array();
1487 foreach ($categories as $id => $category) {
1488 $category->parent = "$category->parent,$category->contextid";
1489 $category->id = "$category->id,$category->contextid";
1490 $newcatarray["$id,$category->contextid"] = $category;
1492 return $newcatarray;
1496 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1498 * @param array $categories An array of question categories.
1499 * @return array The same question category list given to the function, with the top category names being translated.
1501 function question_fix_top_names($categories) {
1503 foreach ($categories as $id => $category) {
1504 if ($category->parent == 0) {
1505 $context = context::instance_by_id($category->contextid);
1506 $categories[$id]->name = get_string('topfor', 'question', $context->get_context_name(false));
1510 return $categories;
1514 * @return array of question category ids of the category and all subcategories.
1516 function question_categorylist($categoryid) {
1517 global $DB;
1519 // final list of category IDs
1520 $categorylist = array();
1522 // a list of category IDs to check for any sub-categories
1523 $subcategories = array($categoryid);
1525 while ($subcategories) {
1526 foreach ($subcategories as $subcategory) {
1527 // if anything from the temporary list was added already, then we have a loop
1528 if (isset($categorylist[$subcategory])) {
1529 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1531 $categorylist[$subcategory] = $subcategory;
1534 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1536 $subcategories = $DB->get_records_select_menu('question_categories',
1537 "parent $in", $params, NULL, 'id,id AS id2');
1540 return $categorylist;
1544 * Get all parent categories of a given question category in decending order.
1545 * @param int $categoryid for which you want to find the parents.
1546 * @return array of question category ids of all parents categories.
1548 function question_categorylist_parents(int $categoryid) {
1549 global $DB;
1550 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1551 if (!$parent) {
1552 return [];
1554 $categorylist = [$parent];
1555 $currentid = $parent;
1556 while ($currentid) {
1557 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1558 if ($currentid) {
1559 $categorylist[] = $currentid;
1562 // Present the list in decending order (the top category at the top).
1563 $categorylist = array_reverse($categorylist);
1564 return $categorylist;
1567 //===========================
1568 // Import/Export Functions
1569 //===========================
1572 * Get list of available import or export formats
1573 * @param string $type 'import' if import list, otherwise export list assumed
1574 * @return array sorted list of import/export formats available
1576 function get_import_export_formats($type) {
1577 global $CFG;
1578 require_once($CFG->dirroot . '/question/format.php');
1580 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1582 $fileformatname = array();
1583 foreach ($formatclasses as $component => $formatclass) {
1585 $format = new $formatclass();
1586 if ($type == 'import') {
1587 $provided = $format->provide_import();
1588 } else {
1589 $provided = $format->provide_export();
1592 if ($provided) {
1593 list($notused, $fileformat) = explode('_', $component, 2);
1594 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1598 core_collator::asort($fileformatnames);
1599 return $fileformatnames;
1604 * Create a reasonable default file name for exporting questions from a particular
1605 * category.
1606 * @param object $course the course the questions are in.
1607 * @param object $category the question category.
1608 * @return string the filename.
1610 function question_default_export_filename($course, $category) {
1611 // We build a string that is an appropriate name (questions) from the lang pack,
1612 // then the corse shortname, then the question category name, then a timestamp.
1614 $base = clean_filename(get_string('exportfilename', 'question'));
1616 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1617 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1619 $shortname = clean_filename($course->shortname);
1620 if ($shortname == '' || $shortname == '_' ) {
1621 $shortname = $course->id;
1624 $categoryname = clean_filename(format_string($category->name));
1626 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1628 return $export_name;
1632 * Converts contextlevels to strings and back to help with reading/writing contexts
1633 * to/from import/export files.
1635 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1636 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1638 class context_to_string_translator{
1640 * @var array used to translate between contextids and strings for this context.
1642 protected $contexttostringarray = array();
1644 public function __construct($contexts) {
1645 $this->generate_context_to_string_array($contexts);
1648 public function context_to_string($contextid) {
1649 return $this->contexttostringarray[$contextid];
1652 public function string_to_context($contextname) {
1653 $contextid = array_search($contextname, $this->contexttostringarray);
1654 return $contextid;
1657 protected function generate_context_to_string_array($contexts) {
1658 if (!$this->contexttostringarray) {
1659 $catno = 1;
1660 foreach ($contexts as $context) {
1661 switch ($context->contextlevel) {
1662 case CONTEXT_MODULE :
1663 $contextstring = 'module';
1664 break;
1665 case CONTEXT_COURSE :
1666 $contextstring = 'course';
1667 break;
1668 case CONTEXT_COURSECAT :
1669 $contextstring = "cat$catno";
1670 $catno++;
1671 break;
1672 case CONTEXT_SYSTEM :
1673 $contextstring = 'system';
1674 break;
1676 $this->contexttostringarray[$context->id] = $contextstring;
1684 * Check capability on category
1686 * @param int|stdClass|question_definition $questionorid object or id.
1687 * If an object is passed, it should include ->contextid and ->createdby.
1688 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1689 * @param int $notused no longer used.
1690 * @return bool this user has the capability $cap for this question $question?
1691 * @throws coding_exception
1693 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1694 global $USER, $DB;
1696 if (is_numeric($questionorid)) {
1697 $questionid = (int)$questionorid;
1698 } else if (is_object($questionorid)) {
1699 // All we really need in this function is the contextid and author of the question.
1700 // We won't bother fetching other details of the question if these 2 fields are provided.
1701 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1702 $question = $questionorid;
1703 } else if (!empty($questionorid->id)) {
1704 $questionid = $questionorid->id;
1708 // At this point, either $question or $questionid is expected to be set.
1709 if (isset($questionid)) {
1710 try {
1711 $question = question_bank::load_question_data($questionid);
1712 } catch (Exception $e) {
1713 // Let's log the exception for future debugging.
1714 debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1716 // Well, at least we tried. Seems that we really have to read from DB.
1717 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1718 FROM {question} q
1719 JOIN {question_categories} qc ON q.category = qc.id
1720 WHERE q.id = :id', ['id' => $questionid]);
1724 if (!isset($question)) {
1725 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1728 $context = context::instance_by_id($question->contextid);
1730 // These are existing questions capabilities that are set per category.
1731 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1732 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1734 if (!isset($capabilitieswithallandmine[$cap])) {
1735 return has_capability('moodle/question:' . $cap, $context);
1736 } else {
1737 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1738 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1743 * Require capability on question.
1745 function question_require_capability_on($question, $cap) {
1746 if (!question_has_capability_on($question, $cap)) {
1747 print_error('nopermissions', '', '', $cap);
1749 return true;
1753 * @param object $context a context
1754 * @return string A URL for editing questions in this context.
1756 function question_edit_url($context) {
1757 global $CFG, $SITE;
1758 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1759 return false;
1761 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1762 $defaultcategory = question_get_default_category($context->id);
1763 if ($defaultcategory) {
1764 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1766 switch ($context->contextlevel) {
1767 case CONTEXT_SYSTEM:
1768 return $baseurl . 'courseid=' . $SITE->id;
1769 case CONTEXT_COURSECAT:
1770 // This is nasty, becuase we can only edit questions in a course
1771 // context at the moment, so for now we just return false.
1772 return false;
1773 case CONTEXT_COURSE:
1774 return $baseurl . 'courseid=' . $context->instanceid;
1775 case CONTEXT_MODULE:
1776 return $baseurl . 'cmid=' . $context->instanceid;
1782 * Adds question bank setting links to the given navigation node if caps are met.
1784 * @param navigation_node $navigationnode The navigation node to add the question branch to
1785 * @param object $context
1786 * @return navigation_node Returns the question branch that was added
1788 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1789 global $PAGE;
1791 if ($context->contextlevel == CONTEXT_COURSE) {
1792 $params = array('courseid'=>$context->instanceid);
1793 } else if ($context->contextlevel == CONTEXT_MODULE) {
1794 $params = array('cmid'=>$context->instanceid);
1795 } else {
1796 return;
1799 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1800 $params['cat'] = $cat;
1803 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1804 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1806 $contexts = new question_edit_contexts($context);
1807 if ($contexts->have_one_edit_tab_cap('questions')) {
1808 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1809 '/question/edit.php', $params), navigation_node::TYPE_SETTING, null, 'questions');
1811 if ($contexts->have_one_edit_tab_cap('categories')) {
1812 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1813 '/question/category.php', $params), navigation_node::TYPE_SETTING, null, 'categories');
1815 if ($contexts->have_one_edit_tab_cap('import')) {
1816 $questionnode->add(get_string('import', 'question'), new moodle_url(
1817 '/question/import.php', $params), navigation_node::TYPE_SETTING, null, 'import');
1819 if ($contexts->have_one_edit_tab_cap('export')) {
1820 $questionnode->add(get_string('export', 'question'), new moodle_url(
1821 '/question/export.php', $params), navigation_node::TYPE_SETTING, null, 'export');
1824 return $questionnode;
1828 * @return array all the capabilities that relate to accessing particular questions.
1830 function question_get_question_capabilities() {
1831 return array(
1832 'moodle/question:add',
1833 'moodle/question:editmine',
1834 'moodle/question:editall',
1835 'moodle/question:viewmine',
1836 'moodle/question:viewall',
1837 'moodle/question:usemine',
1838 'moodle/question:useall',
1839 'moodle/question:movemine',
1840 'moodle/question:moveall',
1845 * @return array all the question bank capabilities.
1847 function question_get_all_capabilities() {
1848 $caps = question_get_question_capabilities();
1849 $caps[] = 'moodle/question:managecategory';
1850 $caps[] = 'moodle/question:flag';
1851 return $caps;
1856 * Tracks all the contexts related to the one where we are currently editing
1857 * questions, and provides helper methods to check permissions.
1859 * @copyright 2007 Jamie Pratt me@jamiep.org
1860 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1862 class question_edit_contexts {
1864 public static $caps = array(
1865 'editq' => array('moodle/question:add',
1866 'moodle/question:editmine',
1867 'moodle/question:editall',
1868 'moodle/question:viewmine',
1869 'moodle/question:viewall',
1870 'moodle/question:usemine',
1871 'moodle/question:useall',
1872 'moodle/question:movemine',
1873 'moodle/question:moveall'),
1874 'questions'=>array('moodle/question:add',
1875 'moodle/question:editmine',
1876 'moodle/question:editall',
1877 'moodle/question:viewmine',
1878 'moodle/question:viewall',
1879 'moodle/question:movemine',
1880 'moodle/question:moveall'),
1881 'categories'=>array('moodle/question:managecategory'),
1882 'import'=>array('moodle/question:add'),
1883 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1885 protected $allcontexts;
1888 * Constructor
1889 * @param context the current context.
1891 public function __construct(context $thiscontext) {
1892 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1896 * @return context[] all parent contexts
1898 public function all() {
1899 return $this->allcontexts;
1903 * @return context lowest context which must be either the module or course context
1905 public function lowest() {
1906 return $this->allcontexts[0];
1910 * @param string $cap capability
1911 * @return context[] parent contexts having capability, zero based index
1913 public function having_cap($cap) {
1914 $contextswithcap = array();
1915 foreach ($this->allcontexts as $context) {
1916 if (has_capability($cap, $context)) {
1917 $contextswithcap[] = $context;
1920 return $contextswithcap;
1924 * @param array $caps capabilities
1925 * @return context[] parent contexts having at least one of $caps, zero based index
1927 public function having_one_cap($caps) {
1928 $contextswithacap = array();
1929 foreach ($this->allcontexts as $context) {
1930 foreach ($caps as $cap) {
1931 if (has_capability($cap, $context)) {
1932 $contextswithacap[] = $context;
1933 break; //done with caps loop
1937 return $contextswithacap;
1941 * @param string $tabname edit tab name
1942 * @return context[] parent contexts having at least one of $caps, zero based index
1944 public function having_one_edit_tab_cap($tabname) {
1945 return $this->having_one_cap(self::$caps[$tabname]);
1949 * @return context[] those contexts where a user can add a question and then use it.
1951 public function having_add_and_use() {
1952 $contextswithcap = array();
1953 foreach ($this->allcontexts as $context) {
1954 if (!has_capability('moodle/question:add', $context)) {
1955 continue;
1957 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1958 continue;
1960 $contextswithcap[] = $context;
1962 return $contextswithcap;
1966 * Has at least one parent context got the cap $cap?
1968 * @param string $cap capability
1969 * @return boolean
1971 public function have_cap($cap) {
1972 return (count($this->having_cap($cap)));
1976 * Has at least one parent context got one of the caps $caps?
1978 * @param array $caps capability
1979 * @return boolean
1981 public function have_one_cap($caps) {
1982 foreach ($caps as $cap) {
1983 if ($this->have_cap($cap)) {
1984 return true;
1987 return false;
1991 * Has at least one parent context got one of the caps for actions on $tabname
1993 * @param string $tabname edit tab name
1994 * @return boolean
1996 public function have_one_edit_tab_cap($tabname) {
1997 return $this->have_one_cap(self::$caps[$tabname]);
2001 * Throw error if at least one parent context hasn't got the cap $cap
2003 * @param string $cap capability
2005 public function require_cap($cap) {
2006 if (!$this->have_cap($cap)) {
2007 print_error('nopermissions', '', '', $cap);
2012 * Throw error if at least one parent context hasn't got one of the caps $caps
2014 * @param array $caps capabilities
2016 public function require_one_cap($caps) {
2017 if (!$this->have_one_cap($caps)) {
2018 $capsstring = join(', ', $caps);
2019 print_error('nopermissions', '', '', $capsstring);
2024 * Throw error if at least one parent context hasn't got one of the caps $caps
2026 * @param string $tabname edit tab name
2028 public function require_one_edit_tab_cap($tabname) {
2029 if (!$this->have_one_edit_tab_cap($tabname)) {
2030 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
2037 * Helps call file_rewrite_pluginfile_urls with the right parameters.
2039 * @package core_question
2040 * @category files
2041 * @param string $text text being processed
2042 * @param string $file the php script used to serve files
2043 * @param int $contextid context ID
2044 * @param string $component component
2045 * @param string $filearea filearea
2046 * @param array $ids other IDs will be used to check file permission
2047 * @param int $itemid item ID
2048 * @param array $options options
2049 * @return string
2051 function question_rewrite_question_urls($text, $file, $contextid, $component,
2052 $filearea, array $ids, $itemid, array $options=null) {
2054 $idsstr = '';
2055 if (!empty($ids)) {
2056 $idsstr .= implode('/', $ids);
2058 if ($itemid !== null) {
2059 $idsstr .= '/' . $itemid;
2061 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
2062 $filearea, $idsstr, $options);
2066 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
2067 * viewing the question outside an attempt (for example, in the question bank
2068 * listing or in the quiz statistics report).
2070 * @param string $text the question text.
2071 * @param int $questionid the question id.
2072 * @param int $filecontextid the context id of the question being displayed.
2073 * @param string $filecomponent the component that owns the file area.
2074 * @param string $filearea the file area name.
2075 * @param int|null $itemid the file's itemid
2076 * @param int $previewcontextid the context id where the preview is being displayed.
2077 * @param string $previewcomponent component responsible for displaying the preview.
2078 * @param array $options text and file options ('forcehttps'=>false)
2079 * @return string $questiontext with URLs rewritten.
2081 function question_rewrite_question_preview_urls($text, $questionid,
2082 $filecontextid, $filecomponent, $filearea, $itemid,
2083 $previewcontextid, $previewcomponent, $options = null) {
2085 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2086 if ($itemid) {
2087 $path .= '/' . $itemid;
2090 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2091 $filecomponent, $filearea, $path, $options);
2095 * Called by pluginfile.php to serve files related to the 'question' core
2096 * component and for files belonging to qtypes.
2098 * For files that relate to questions in a question_attempt, then we delegate to
2099 * a function in the component that owns the attempt (for example in the quiz,
2100 * or in core question preview) to get necessary inforation.
2102 * (Note that, at the moment, all question file areas relate to questions in
2103 * attempts, so the If at the start of the last paragraph is always true.)
2105 * Does not return, either calls send_file_not_found(); or serves the file.
2107 * @package core_question
2108 * @category files
2109 * @param stdClass $course course settings object
2110 * @param stdClass $context context object
2111 * @param string $component the name of the component we are serving files for.
2112 * @param string $filearea the name of the file area.
2113 * @param array $args the remaining bits of the file path.
2114 * @param bool $forcedownload whether the user must be forced to download the file.
2115 * @param array $options additional options affecting the file serving
2117 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2118 global $DB, $CFG;
2120 // Special case, sending a question bank export.
2121 if ($filearea === 'export') {
2122 list($context, $course, $cm) = get_context_info_array($context->id);
2123 require_login($course, false, $cm);
2125 require_once($CFG->dirroot . '/question/editlib.php');
2126 $contexts = new question_edit_contexts($context);
2127 // check export capability
2128 $contexts->require_one_edit_tab_cap('export');
2129 $category_id = (int)array_shift($args);
2130 $format = array_shift($args);
2131 $cattofile = array_shift($args);
2132 $contexttofile = array_shift($args);
2133 $filename = array_shift($args);
2135 // load parent class for import/export
2136 require_once($CFG->dirroot . '/question/format.php');
2137 require_once($CFG->dirroot . '/question/editlib.php');
2138 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2140 $classname = 'qformat_' . $format;
2141 if (!class_exists($classname)) {
2142 send_file_not_found();
2145 $qformat = new $classname();
2147 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2148 send_file_not_found();
2151 $qformat->setCategory($category);
2152 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2153 $qformat->setCourse($course);
2155 if ($cattofile == 'withcategories') {
2156 $qformat->setCattofile(true);
2157 } else {
2158 $qformat->setCattofile(false);
2161 if ($contexttofile == 'withcontexts') {
2162 $qformat->setContexttofile(true);
2163 } else {
2164 $qformat->setContexttofile(false);
2167 if (!$qformat->exportpreprocess()) {
2168 send_file_not_found();
2169 print_error('exporterror', 'question', $thispageurl->out());
2172 // export data to moodle file pool
2173 if (!$content = $qformat->exportprocess()) {
2174 send_file_not_found();
2177 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2180 // Normal case, a file belonging to a question.
2181 $qubaidorpreview = array_shift($args);
2183 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2184 if ($qubaidorpreview === 'preview') {
2185 $previewcontextid = (int)array_shift($args);
2186 $previewcomponent = array_shift($args);
2187 $questionid = (int) array_shift($args);
2188 $previewcontext = context_helper::instance_by_id($previewcontextid);
2190 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2191 $previewcontext, $questionid,
2192 $context, $component, $filearea, $args,
2193 $forcedownload, $options), 'callbackmissing');
2195 if ($result === 'callbackmissing') {
2196 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2197 "{$previewcomponent}_question_preview_pluginfile callback. " .
2198 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
2201 send_file_not_found();
2204 // 2. A question being attempted in the normal way.
2205 $qubaid = (int)$qubaidorpreview;
2206 $slot = (int)array_shift($args);
2208 $module = $DB->get_field('question_usages', 'component',
2209 array('id' => $qubaid));
2210 if (!$module) {
2211 send_file_not_found();
2214 if ($module === 'core_question_preview') {
2215 require_once($CFG->dirroot . '/question/previewlib.php');
2216 return question_preview_question_pluginfile($course, $context,
2217 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2219 } else {
2220 $dir = core_component::get_component_directory($module);
2221 if (!file_exists("$dir/lib.php")) {
2222 send_file_not_found();
2224 include_once("$dir/lib.php");
2226 $filefunction = $module . '_question_pluginfile';
2227 if (function_exists($filefunction)) {
2228 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2229 $args, $forcedownload, $options);
2232 // Okay, we're here so lets check for function without 'mod_'.
2233 if (strpos($module, 'mod_') === 0) {
2234 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2235 if (function_exists($filefunctionold)) {
2236 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2237 $args, $forcedownload, $options);
2241 send_file_not_found();
2246 * Serve questiontext files in the question text when they are displayed in this report.
2248 * @package core_files
2249 * @category files
2250 * @param context $previewcontext the context in which the preview is happening.
2251 * @param int $questionid the question id.
2252 * @param context $filecontext the file (question) context.
2253 * @param string $filecomponent the component the file belongs to.
2254 * @param string $filearea the file area.
2255 * @param array $args remaining file args.
2256 * @param bool $forcedownload.
2257 * @param array $options additional options affecting the file serving.
2259 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2260 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2261 global $DB;
2263 // Verify that contextid matches the question.
2264 $question = $DB->get_record_sql('
2265 SELECT q.*, qc.contextid
2266 FROM {question} q
2267 JOIN {question_categories} qc ON qc.id = q.category
2268 WHERE q.id = :id AND qc.contextid = :contextid',
2269 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2271 // Check the capability.
2272 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2273 require_login($course, false, $cm);
2275 question_require_capability_on($question, 'use');
2277 $fs = get_file_storage();
2278 $relativepath = implode('/', $args);
2279 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2280 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2281 send_file_not_found();
2284 send_stored_file($file, 0, 0, $forcedownload, $options);
2288 * Create url for question export
2290 * @param int $contextid, current context
2291 * @param int $categoryid, categoryid
2292 * @param string $format
2293 * @param string $withcategories
2294 * @param string $ithcontexts
2295 * @param moodle_url export file url
2297 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2298 $withcontexts, $filename) {
2299 global $CFG;
2300 $urlbase = "$CFG->wwwroot/pluginfile.php";
2301 return moodle_url::make_file_url($urlbase,
2302 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2303 "/{$withcontexts}/{$filename}", true);
2307 * Get the URL to export a single question (exportone.php).
2309 * @param stdClass|question_definition $question the question definition as obtained from
2310 * question_bank::load_question_data() or question_bank::make_question().
2311 * (Only ->id and ->contextid are used.)
2312 * @return moodle_url the requested URL.
2314 function question_get_export_single_question_url($question) {
2315 $params = ['id' => $question->id, 'sesskey' => sesskey()];
2316 $context = context::instance_by_id($question->contextid);
2317 switch ($context->contextlevel) {
2318 case CONTEXT_MODULE:
2319 $params['cmid'] = $context->instanceid;
2320 break;
2322 case CONTEXT_COURSE:
2323 $params['courseid'] = $context->instanceid;
2324 break;
2326 default:
2327 $params['courseid'] = SITEID;
2330 return new moodle_url('/question/exportone.php', $params);
2334 * Return a list of page types
2335 * @param string $pagetype current page type
2336 * @param stdClass $parentcontext Block's parent context
2337 * @param stdClass $currentcontext Current context of block
2339 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2340 global $CFG;
2341 $types = array(
2342 'question-*'=>get_string('page-question-x', 'question'),
2343 'question-edit'=>get_string('page-question-edit', 'question'),
2344 'question-category'=>get_string('page-question-category', 'question'),
2345 'question-export'=>get_string('page-question-export', 'question'),
2346 'question-import'=>get_string('page-question-import', 'question')
2348 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2349 require_once($CFG->dirroot . '/course/lib.php');
2350 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2351 } else {
2352 return $types;
2357 * Does an activity module use the question bank?
2359 * @param string $modname The name of the module (without mod_ prefix).
2360 * @return bool true if the module uses questions.
2362 function question_module_uses_questions($modname) {
2363 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2364 return true;
2367 $component = 'mod_'.$modname;
2368 if (component_callback_exists($component, 'question_pluginfile')) {
2369 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2370 return true;
2373 return false;