Automatically generated installer lang files
[moodle.git] / lib / questionlib.php
blob8566321a1e16759cd7e1663fc9f557fb99a4f8cd
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);
384 // Log the deletion of this question.
385 $event = \core\event\question_deleted::create_from_question_instance($question);
386 $event->add_record_snapshot('question', $question);
387 $event->trigger();
391 * All question categories and their questions are deleted for this context id.
393 * @param object $contextid The contextid to delete question categories from
394 * @return array Feedback from deletes (if any)
396 function question_delete_context($contextid) {
397 global $DB;
399 //To store feedback to be showed at the end of the process
400 $feedbackdata = array();
402 //Cache some strings
403 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
404 $fields = 'id, parent, name, contextid';
405 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
406 //Sort categories following their tree (parent-child) relationships
407 //this will make the feedback more readable
408 $categories = sort_categories_by_tree($categories);
410 foreach ($categories as $category) {
411 question_category_delete_safe($category);
413 //Fill feedback
414 $feedbackdata[] = array($category->name, $strcatdeleted);
417 return $feedbackdata;
421 * All question categories and their questions are deleted for this course.
423 * @param stdClass $course an object representing the activity
424 * @param boolean $feedback to specify if the process must output a summary of its work
425 * @return boolean
427 function question_delete_course($course, $feedback=true) {
428 $coursecontext = context_course::instance($course->id);
429 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
431 // Inform about changes performed if feedback is enabled.
432 if ($feedback && $feedbackdata) {
433 $table = new html_table();
434 $table->head = array(get_string('category', 'question'), get_string('action'));
435 $table->data = $feedbackdata;
436 echo html_writer::table($table);
438 return true;
442 * Category is about to be deleted,
443 * 1/ All question categories and their questions are deleted for this course category.
444 * 2/ All questions are moved to new category
446 * @param object|core_course_category $category course category object
447 * @param object|core_course_category $newcategory empty means everything deleted, otherwise id of
448 * category where content moved
449 * @param boolean $feedback to specify if the process must output a summary of its work
450 * @return boolean
452 function question_delete_course_category($category, $newcategory, $feedback=true) {
453 global $DB, $OUTPUT;
455 $context = context_coursecat::instance($category->id);
456 if (empty($newcategory)) {
457 $feedbackdata = question_delete_context($context->id, $feedback);
459 // Output feedback if requested.
460 if ($feedback && $feedbackdata) {
461 $table = new html_table();
462 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
463 $table->data = $feedbackdata;
464 echo html_writer::table($table);
467 } else {
468 // Move question categories to the new context.
469 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
470 return false;
473 // Only move question categories if there is any question category at all!
474 if ($topcategory = question_get_top_category($context->id)) {
475 $newtopcategory = question_get_top_category($newcontext->id, true);
477 question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
478 $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
479 // Now delete the top category.
480 $DB->delete_records('question_categories', array('id' => $topcategory->id));
483 if ($feedback) {
484 $a = new stdClass();
485 $a->oldplace = $context->get_context_name();
486 $a->newplace = $newcontext->get_context_name();
487 echo $OUTPUT->notification(
488 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
492 return true;
496 * Enter description here...
498 * @param array $questionids of question ids
499 * @param object $newcontextid the context to create the saved category in.
500 * @param string $oldplace a textual description of the think being deleted,
501 * e.g. from get_context_name
502 * @param object $newcategory
503 * @return mixed false on
505 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
506 $newcategory = null) {
507 global $DB;
509 // Make a category in the parent context to move the questions to.
510 if (is_null($newcategory)) {
511 $newcategory = new stdClass();
512 $newcategory->parent = question_get_top_category($newcontextid, true)->id;
513 $newcategory->contextid = $newcontextid;
514 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
515 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
516 $newcategory->sortorder = 999;
517 $newcategory->stamp = make_unique_id_code();
518 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
521 // Move any remaining questions to the 'saved' category.
522 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
523 return false;
525 return $newcategory;
529 * All question categories and their questions are deleted for this activity.
531 * @param object $cm the course module object representing the activity
532 * @param boolean $feedback to specify if the process must output a summary of its work
533 * @return boolean
535 function question_delete_activity($cm, $feedback=true) {
536 global $DB;
538 $modcontext = context_module::instance($cm->id);
539 $feedbackdata = question_delete_context($modcontext->id, $feedback);
540 // Inform about changes performed if feedback is enabled.
541 if ($feedback && $feedbackdata) {
542 $table = new html_table();
543 $table->head = array(get_string('category', 'question'), get_string('action'));
544 $table->data = $feedbackdata;
545 echo html_writer::table($table);
547 return true;
551 * This function will handle moving all tag instances to a new context for a
552 * given list of questions.
554 * Questions can be tagged in up to two contexts:
555 * 1.) The context the question exists in.
556 * 2.) The course context (if the question context is a higher context.
557 * E.g. course category context or system context.
559 * This means a question that exists in a higher context (e.g. course cat or
560 * system context) may have multiple groups of tags in any number of child
561 * course contexts.
563 * Questions in the course category context can be move "down" a context level
564 * into one of their child course contexts or activity contexts which affects the
565 * availability of that question in other courses / activities.
567 * In this case it makes the questions no longer available in the other course or
568 * activity contexts so we need to make sure that the tag instances in those other
569 * contexts are removed.
571 * @param stdClass[] $questions The list of question being moved (must include
572 * the id and contextid)
573 * @param context $newcontext The Moodle context the questions are being moved to
575 function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
576 // If the questions are moving to a new course/activity context then we need to
577 // find any existing tag instances from any unavailable course contexts and
578 // delete them because they will no longer be applicable (we don't support
579 // tagging questions across courses).
580 $instancestodelete = [];
581 $instancesfornewcontext = [];
582 $newcontextparentids = $newcontext->get_parent_context_ids();
583 $questionids = array_map(function($question) {
584 return $question->id;
585 }, $questions);
586 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
588 foreach ($questions as $question) {
589 $tagobjects = $questionstagobjects[$question->id];
591 foreach ($tagobjects as $tagobject) {
592 $tagid = $tagobject->taginstanceid;
593 $tagcontextid = $tagobject->taginstancecontextid;
594 $istaginnewcontext = $tagcontextid == $newcontext->id;
595 $istaginquestioncontext = $tagcontextid == $question->contextid;
597 if ($istaginnewcontext) {
598 // This tag instance is already in the correct context so we can
599 // ignore it.
600 continue;
603 if ($istaginquestioncontext) {
604 // This tag instance is in the question context so it needs to be
605 // updated.
606 $instancesfornewcontext[] = $tagid;
607 continue;
610 // These tag instances are in neither the new context nor the
611 // question context so we need to determine what to do based on
612 // the context they are in and the new question context.
613 $tagcontext = context::instance_by_id($tagcontextid);
614 $tagcoursecontext = $tagcontext->get_course_context(false);
615 // The tag is in a course context if get_course_context() returns
616 // itself.
617 $istaginstancecontextcourse = !empty($tagcoursecontext)
618 && $tagcontext->id == $tagcoursecontext->id;
620 if ($istaginstancecontextcourse) {
621 // If the tag instance is in a course context we need to add some
622 // special handling.
623 $tagcontextparentids = $tagcontext->get_parent_context_ids();
624 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
625 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
627 if ($isnewcontextaparent) {
628 // If the tag instance is a course context tag and the new
629 // context is still a parent context to the tag context then
630 // we can leave this tag where it is.
631 continue;
632 } else if ($isnewcontextachild) {
633 // If the new context is a child context (e.g. activity) of this
634 // tag instance then we should move all of this tag instance
635 // down into the activity context along with the question.
636 $instancesfornewcontext[] = $tagid;
637 } else {
638 // If the tag is in a course context that is no longer a parent
639 // or child of the new context then this tag instance should be
640 // removed.
641 $instancestodelete[] = $tagid;
643 } else {
644 // This is a catch all for any tag instances not in the question
645 // context or a course context. These tag instances should be
646 // updated to the new context id. This will clean up old invalid
647 // data.
648 $instancesfornewcontext[] = $tagid;
653 if (!empty($instancestodelete)) {
654 // Delete any course context tags that may no longer be valid.
655 core_tag_tag::delete_instances_by_id($instancestodelete);
658 if (!empty($instancesfornewcontext)) {
659 // Update the tag instances to the new context id.
660 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
665 * This function should be considered private to the question bank, it is called from
666 * question/editlib.php question/contextmoveq.php and a few similar places to to the
667 * work of actually moving questions and associated data. However, callers of this
668 * function also have to do other work, which is why you should not call this method
669 * directly from outside the questionbank.
671 * @param array $questionids of question ids.
672 * @param integer $newcategoryid the id of the category to move to.
674 function question_move_questions_to_category($questionids, $newcategoryid) {
675 global $DB;
677 $newcontextid = $DB->get_field('question_categories', 'contextid',
678 array('id' => $newcategoryid));
679 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
680 $questions = $DB->get_records_sql("
681 SELECT q.id, q.qtype, qc.contextid, q.idnumber, q.category
682 FROM {question} q
683 JOIN {question_categories} qc ON q.category = qc.id
684 WHERE q.id $questionidcondition", $params);
685 foreach ($questions as $question) {
686 if ($newcontextid != $question->contextid) {
687 question_bank::get_qtype($question->qtype)->move_files(
688 $question->id, $question->contextid, $newcontextid);
690 // Check whether there could be a clash of idnumbers in the new category.
691 if (((string) $question->idnumber !== '') &&
692 $DB->record_exists('question', ['idnumber' => $question->idnumber, 'category' => $newcategoryid])) {
693 $rec = $DB->get_records_select('question', "category = ? AND idnumber LIKE ?",
694 [$newcategoryid, $question->idnumber . '_%'], 'idnumber DESC', 'id, idnumber', 0, 1);
695 $unique = 1;
696 if (count($rec)) {
697 $rec = reset($rec);
698 $idnumber = $rec->idnumber;
699 if (strpos($idnumber, '_') !== false) {
700 $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
703 // For the move process, add a numerical increment to the idnumber. This means that if a question is
704 // mistakenly moved then the idnumber will not be completely lost.
705 $q = new stdClass();
706 $q->id = $question->id;
707 $q->category = $newcategoryid;
708 $q->idnumber = $question->idnumber . '_' . $unique;
709 $DB->update_record('question', $q);
712 // Log this question move.
713 $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
714 ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategoryid]);
715 $event->trigger();
718 // Move the questions themselves.
719 $DB->set_field_select('question', 'category', $newcategoryid,
720 "id $questionidcondition", $params);
722 // Move any subquestions belonging to them.
723 $DB->set_field_select('question', 'category', $newcategoryid,
724 "parent $questionidcondition", $params);
726 $newcontext = context::instance_by_id($newcontextid);
727 question_move_question_tags_to_new_context($questions, $newcontext);
729 // TODO Deal with datasets.
731 // Purge these questions from the cache.
732 foreach ($questions as $question) {
733 question_bank::notify_question_edited($question->id);
736 return true;
740 * This function helps move a question cateogry to a new context by moving all
741 * the files belonging to all the questions to the new context.
742 * Also moves subcategories.
743 * @param integer $categoryid the id of the category being moved.
744 * @param integer $oldcontextid the old context id.
745 * @param integer $newcontextid the new context id.
747 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
748 global $DB;
750 $questions = [];
751 $questionids = $DB->get_records_menu('question',
752 array('category' => $categoryid), '', 'id,qtype');
753 foreach ($questionids as $questionid => $qtype) {
754 question_bank::get_qtype($qtype)->move_files(
755 $questionid, $oldcontextid, $newcontextid);
756 // Purge this question from the cache.
757 question_bank::notify_question_edited($questionid);
759 $questions[] = (object) [
760 'id' => $questionid,
761 'contextid' => $oldcontextid
765 $newcontext = context::instance_by_id($newcontextid);
766 question_move_question_tags_to_new_context($questions, $newcontext);
768 $subcatids = $DB->get_records_menu('question_categories',
769 array('parent' => $categoryid), '', 'id,1');
770 foreach ($subcatids as $subcatid => $notused) {
771 $DB->set_field('question_categories', 'contextid', $newcontextid,
772 array('id' => $subcatid));
773 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
778 * Generate the URL for starting a new preview of a given question with the given options.
779 * @param integer $questionid the question to preview.
780 * @param string $preferredbehaviour the behaviour to use for the preview.
781 * @param float $maxmark the maximum to mark the question out of.
782 * @param question_display_options $displayoptions the display options to use.
783 * @param int $variant the variant of the question to preview. If null, one will
784 * be picked randomly.
785 * @param object $context context to run the preview in (affects things like
786 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
787 * @return moodle_url the URL.
789 function question_preview_url($questionid, $preferredbehaviour = null,
790 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
792 $params = array('id' => $questionid);
794 if (is_null($context)) {
795 global $PAGE;
796 $context = $PAGE->context;
798 if ($context->contextlevel == CONTEXT_MODULE) {
799 $params['cmid'] = $context->instanceid;
800 } else if ($context->contextlevel == CONTEXT_COURSE) {
801 $params['courseid'] = $context->instanceid;
804 if (!is_null($preferredbehaviour)) {
805 $params['behaviour'] = $preferredbehaviour;
808 if (!is_null($maxmark)) {
809 $params['maxmark'] = format_float($maxmark, -1);
812 if (!is_null($displayoptions)) {
813 $params['correctness'] = $displayoptions->correctness;
814 $params['marks'] = $displayoptions->marks;
815 $params['markdp'] = $displayoptions->markdp;
816 $params['feedback'] = (bool) $displayoptions->feedback;
817 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
818 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
819 $params['history'] = (bool) $displayoptions->history;
822 if ($variant) {
823 $params['variant'] = $variant;
826 return new moodle_url('/question/preview.php', $params);
830 * @return array that can be passed as $params to the {@link popup_action} constructor.
832 function question_preview_popup_params() {
833 return array(
834 'height' => 600,
835 'width' => 800,
840 * Given a list of ids, load the basic information about a set of questions from
841 * the questions table. The $join and $extrafields arguments can be used together
842 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
843 * read the code below to see how the SQL is assembled. Throws exceptions on error.
845 * @param array $questionids array of question ids to load. If null, then all
846 * questions matched by $join will be loaded.
847 * @param string $extrafields extra SQL code to be added to the query.
848 * @param string $join extra SQL code to be added to the query.
849 * @param array $extraparams values for any placeholders in $join.
850 * You must use named placeholders.
851 * @param string $orderby what to order the results by. Optional, default is unspecified order.
853 * @return array partially complete question objects. You need to call get_question_options
854 * on them before they can be properly used.
856 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
857 $extraparams = array(), $orderby = '') {
858 global $DB;
860 if ($questionids === null) {
861 $where = '';
862 $params = array();
863 } else {
864 if (empty($questionids)) {
865 return array();
868 list($questionidcondition, $params) = $DB->get_in_or_equal(
869 $questionids, SQL_PARAMS_NAMED, 'qid0000');
870 $where = 'WHERE q.id ' . $questionidcondition;
873 if ($join) {
874 $join = 'JOIN ' . $join;
877 if ($extrafields) {
878 $extrafields = ', ' . $extrafields;
881 if ($orderby) {
882 $orderby = 'ORDER BY ' . $orderby;
885 $sql = "SELECT q.*, qc.contextid{$extrafields}
886 FROM {question} q
887 JOIN {question_categories} qc ON q.category = qc.id
888 {$join}
889 {$where}
890 {$orderby}";
892 // Load the questions.
893 $questions = $DB->get_records_sql($sql, $extraparams + $params);
894 foreach ($questions as $question) {
895 $question->_partiallyloaded = true;
898 return $questions;
902 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
903 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
904 * read the code below to see how the SQL is assembled. Throws exceptions on error.
906 * @param array $questionids array of question ids.
907 * @param string $extrafields extra SQL code to be added to the query.
908 * @param string $join extra SQL code to be added to the query.
909 * @param array $extraparams values for any placeholders in $join.
910 * You are strongly recommended to use named placeholder.
912 * @return array question objects.
914 function question_load_questions($questionids, $extrafields = '', $join = '') {
915 $questions = question_preload_questions($questionids, $extrafields, $join);
917 // Load the question type specific information
918 if (!get_question_options($questions)) {
919 return 'Could not load the question options';
922 return $questions;
926 * Private function to factor common code out of get_question_options().
928 * @param object $question the question to tidy.
929 * @param stdClass $category The question_categories record for the given $question.
930 * @param stdClass[]|null $tagobjects The tags for the given $question.
931 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
933 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
934 // Load question-type specific fields.
935 if (!question_bank::is_qtype_installed($question->qtype)) {
936 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
937 'qtype_missingtype')) . $question->questiontext;
939 question_bank::get_qtype($question->qtype)->get_question_options($question);
941 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
942 $question->defaultmark += 0;
943 $question->penalty += 0;
945 if (isset($question->_partiallyloaded)) {
946 unset($question->_partiallyloaded);
949 $question->categoryobject = $category;
951 if (!is_null($tagobjects)) {
952 $categorycontext = context::instance_by_id($category->contextid);
953 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
954 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
955 $question->coursetags = $sortedtagobjects->coursetags;
956 $question->tagobjects = $sortedtagobjects->tagobjects;
957 $question->tags = $sortedtagobjects->tags;
962 * Updates the question objects with question type specific
963 * information by calling {@link get_question_options()}
965 * Can be called either with an array of question objects or with a single
966 * question object.
968 * @param mixed $questions Either an array of question objects to be updated
969 * or just a single question object
970 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
971 * @param stdClass[] $filtercourses The courses to filter the course tags by.
972 * @return bool Indicates success or failure.
974 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
975 global $DB;
977 $questionlist = is_array($questions) ? $questions : [$questions];
978 $categoryids = [];
979 $questionids = [];
981 if (empty($questionlist)) {
982 return true;
985 foreach ($questionlist as $question) {
986 $questionids[] = $question->id;
988 if (!in_array($question->category, $categoryids)) {
989 $categoryids[] = $question->category;
993 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
995 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
996 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
997 } else {
998 $tagobjectsbyquestion = null;
1001 foreach ($questionlist as $question) {
1002 if (is_null($tagobjectsbyquestion)) {
1003 $tagobjects = null;
1004 } else {
1005 $tagobjects = $tagobjectsbyquestion[$question->id];
1008 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
1011 return true;
1015 * Sort question tags by course or normal tags.
1017 * This function also search tag instances that may have a context id that don't match either a course or
1018 * question context and fix the data setting the correct context id.
1020 * @param stdClass[] $tagobjects The tags for the given $question.
1021 * @param stdClass $categorycontext The question categories context.
1022 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1023 * @return stdClass $sortedtagobjects Sorted tag objects.
1025 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
1027 // Questions can have two sets of tag instances. One set at the
1028 // course context level and another at the context the question
1029 // belongs to (e.g. course category, system etc).
1030 $sortedtagobjects = new stdClass();
1031 $sortedtagobjects->coursetagobjects = [];
1032 $sortedtagobjects->coursetags = [];
1033 $sortedtagobjects->tagobjects = [];
1034 $sortedtagobjects->tags = [];
1035 $taginstanceidstonormalise = [];
1036 $filtercoursecontextids = [];
1037 $hasfiltercourses = !empty($filtercourses);
1039 if ($hasfiltercourses) {
1040 // If we're being asked to filter the course tags by a set of courses
1041 // then get the context ids to filter below.
1042 $filtercoursecontextids = array_map(function($course) {
1043 $coursecontext = context_course::instance($course->id);
1044 return $coursecontext->id;
1045 }, $filtercourses);
1048 foreach ($tagobjects as $tagobject) {
1049 $tagcontextid = $tagobject->taginstancecontextid;
1050 $tagcontext = context::instance_by_id($tagcontextid);
1051 $tagcoursecontext = $tagcontext->get_course_context(false);
1052 // This is a course tag if the tag context is a course context which
1053 // doesn't match the question's context. Any tag in the question context
1054 // is not considered a course tag, it belongs to the question.
1055 $iscoursetag = $tagcoursecontext
1056 && $tagcontext->id == $tagcoursecontext->id
1057 && $tagcontext->id != $categorycontext->id;
1059 if ($iscoursetag) {
1060 // Any tag instance in a course context level is considered a course tag.
1061 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1062 // Add the tag to the list of course tags if we aren't being
1063 // asked to filter or if this tag is in the list of courses
1064 // we're being asked to filter by.
1065 $sortedtagobjects->coursetagobjects[] = $tagobject;
1066 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1068 } else {
1069 // All non course context level tag instances or tags in the question
1070 // context belong to the context that the question was created in.
1071 $sortedtagobjects->tagobjects[] = $tagobject;
1072 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1074 // Due to legacy tag implementations that don't force the recording
1075 // of a context id, some tag instances may have context ids that don't
1076 // match either a course context or the question context. In this case
1077 // we should take the opportunity to fix up the data and set the correct
1078 // context id.
1079 if ($tagcontext->id != $categorycontext->id) {
1080 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1081 // Update the object properties to reflect the DB update that will
1082 // happen below.
1083 $tagobject->taginstancecontextid = $categorycontext->id;
1088 if (!empty($taginstanceidstonormalise)) {
1089 // If we found any tag instances with incorrect context id data then we can
1090 // correct those values now by setting them to the question context id.
1091 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1094 return $sortedtagobjects;
1098 * Print the icon for the question type
1100 * @param object $question The question object for which the icon is required.
1101 * Only $question->qtype is used.
1102 * @return string the HTML for the img tag.
1104 function print_question_icon($question) {
1105 global $PAGE;
1106 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
1110 * Creates a stamp that uniquely identifies this version of the question
1112 * In future we want this to use a hash of the question data to guarantee that
1113 * identical versions have the same version stamp.
1115 * @param object $question
1116 * @return string A unique version stamp
1118 function question_hash($question) {
1119 return make_unique_id_code();
1122 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1125 * returns the categories with their names ordered following parent-child relationships
1126 * finally it tries to return pending categories (those being orphaned, whose parent is
1127 * incorrect) to avoid missing any category from original array.
1129 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1130 global $DB;
1132 $children = array();
1133 $keys = array_keys($categories);
1135 foreach ($keys as $key) {
1136 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1137 $children[$key] = $categories[$key];
1138 $categories[$key]->processed = true;
1139 $children = $children + sort_categories_by_tree(
1140 $categories, $children[$key]->id, $level+1);
1143 //If level = 1, we have finished, try to look for non processed categories
1144 // (bad parent) and sort them too
1145 if ($level == 1) {
1146 foreach ($keys as $key) {
1147 // If not processed and it's a good candidate to start (because its
1148 // parent doesn't exist in the course)
1149 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1150 array('contextid' => $categories[$key]->contextid,
1151 'id' => $categories[$key]->parent))) {
1152 $children[$key] = $categories[$key];
1153 $categories[$key]->processed = true;
1154 $children = $children + sort_categories_by_tree(
1155 $categories, $children[$key]->id, $level + 1);
1159 return $children;
1163 * Private method, only for the use of add_indented_names().
1165 * Recursively adds an indentedname field to each category, starting with the category
1166 * with id $id, and dealing with that category and all its children, and
1167 * return a new array, with those categories in the right order.
1169 * @param array $categories an array of categories which has had childids
1170 * fields added by flatten_category_tree(). Passed by reference for
1171 * performance only. It is not modfied.
1172 * @param int $id the category to start the indenting process from.
1173 * @param int $depth the indent depth. Used in recursive calls.
1174 * @return array a new array of categories, in the right order for the tree.
1176 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1178 // Indent the name of this category.
1179 $newcategories = array();
1180 $newcategories[$id] = $categories[$id];
1181 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
1182 $categories[$id]->name;
1184 // Recursively indent the children.
1185 foreach ($categories[$id]->childids as $childid) {
1186 if ($childid != $nochildrenof) {
1187 $newcategories = $newcategories + flatten_category_tree(
1188 $categories, $childid, $depth + 1, $nochildrenof);
1192 // Remove the childids array that were temporarily added.
1193 unset($newcategories[$id]->childids);
1195 return $newcategories;
1199 * Format categories into an indented list reflecting the tree structure.
1201 * @param array $categories An array of category objects, for example from the.
1202 * @return array The formatted list of categories.
1204 function add_indented_names($categories, $nochildrenof = -1) {
1206 // Add an array to each category to hold the child category ids. This array
1207 // will be removed again by flatten_category_tree(). It should not be used
1208 // outside these two functions.
1209 foreach (array_keys($categories) as $id) {
1210 $categories[$id]->childids = array();
1213 // Build the tree structure, and record which categories are top-level.
1214 // We have to be careful, because the categories array may include published
1215 // categories from other courses, but not their parents.
1216 $toplevelcategoryids = array();
1217 foreach (array_keys($categories) as $id) {
1218 if (!empty($categories[$id]->parent) &&
1219 array_key_exists($categories[$id]->parent, $categories)) {
1220 $categories[$categories[$id]->parent]->childids[] = $id;
1221 } else {
1222 $toplevelcategoryids[] = $id;
1226 // Flatten the tree to and add the indents.
1227 $newcategories = array();
1228 foreach ($toplevelcategoryids as $id) {
1229 $newcategories = $newcategories + flatten_category_tree(
1230 $categories, $id, 0, $nochildrenof);
1233 return $newcategories;
1237 * Output a select menu of question categories.
1239 * Categories from this course and (optionally) published categories from other courses
1240 * are included. Optionally, only categories the current user may edit can be included.
1242 * @param integer $courseid the id of the course to get the categories for.
1243 * @param integer $published if true, include publised categories from other courses.
1244 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1245 * @param integer $selected optionally, the id of a category to be selected by
1246 * default in the dropdown.
1248 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1249 $selected = "", $nochildrenof = -1) {
1250 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1251 false, $nochildrenof);
1252 if ($selected) {
1253 $choose = '';
1254 } else {
1255 $choose = 'choosedots';
1257 $options = array();
1258 foreach ($categoriesarray as $group => $opts) {
1259 $options[] = array($group => $opts);
1261 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1262 $attrs = array(
1263 'id' => 'id_movetocategory',
1264 'class' => 'custom-select',
1265 'data-action' => 'toggle',
1266 'data-togglegroup' => 'qbank',
1267 'data-toggle' => 'action',
1268 'disabled' => true,
1270 echo html_writer::select($options, 'category', $selected, $choose, $attrs);
1274 * @param integer $contextid a context id.
1275 * @return object the default question category for that context, or false if none.
1277 function question_get_default_category($contextid) {
1278 global $DB;
1279 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1280 array($contextid), 'id', '*', 0, 1);
1281 if (!empty($category)) {
1282 return reset($category);
1283 } else {
1284 return false;
1289 * Gets the top category in the given context.
1290 * This function can optionally create the top category if it doesn't exist.
1292 * @param int $contextid A context id.
1293 * @param bool $create Whether create a top category if it doesn't exist.
1294 * @return bool|stdClass The top question category for that context, or false if none.
1296 function question_get_top_category($contextid, $create = false) {
1297 global $DB;
1298 $category = $DB->get_record('question_categories',
1299 array('contextid' => $contextid, 'parent' => 0));
1301 if (!$category && $create) {
1302 // We need to make one.
1303 $category = new stdClass();
1304 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1305 $category->info = '';
1306 $category->contextid = $contextid;
1307 $category->parent = 0;
1308 $category->sortorder = 0;
1309 $category->stamp = make_unique_id_code();
1310 $category->id = $DB->insert_record('question_categories', $category);
1313 return $category;
1317 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1319 * @param array $contextids List of context ids
1320 * @return array
1322 function question_get_top_categories_for_contexts($contextids) {
1323 global $DB;
1325 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1326 list($insql, $params) = $DB->get_in_or_equal($contextids);
1327 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1328 $topcategories = $DB->get_fieldset_sql($sql, $params);
1330 return $topcategories;
1334 * Gets the default category in the most specific context.
1335 * If no categories exist yet then default ones are created in all contexts.
1337 * @param array $contexts The context objects for this context and all parent contexts.
1338 * @return object The default category - the category in the course context
1340 function question_make_default_categories($contexts) {
1341 global $DB;
1342 static $preferredlevels = array(
1343 CONTEXT_COURSE => 4,
1344 CONTEXT_MODULE => 3,
1345 CONTEXT_COURSECAT => 2,
1346 CONTEXT_SYSTEM => 1,
1349 $toreturn = null;
1350 $preferredness = 0;
1351 // If it already exists, just return it.
1352 foreach ($contexts as $key => $context) {
1353 $topcategory = question_get_top_category($context->id, true);
1354 if (!$exists = $DB->record_exists("question_categories",
1355 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1356 // Otherwise, we need to make one
1357 $category = new stdClass();
1358 $contextname = $context->get_context_name(false, true);
1359 $category->name = get_string('defaultfor', 'question', $contextname);
1360 $category->info = get_string('defaultinfofor', 'question', $contextname);
1361 $category->contextid = $context->id;
1362 $category->parent = $topcategory->id;
1363 // By default, all categories get this number, and are sorted alphabetically.
1364 $category->sortorder = 999;
1365 $category->stamp = make_unique_id_code();
1366 $category->id = $DB->insert_record('question_categories', $category);
1367 } else {
1368 $category = question_get_default_category($context->id);
1370 $thispreferredness = $preferredlevels[$context->contextlevel];
1371 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1372 $thispreferredness += 10;
1374 if ($thispreferredness > $preferredness) {
1375 $toreturn = $category;
1376 $preferredness = $thispreferredness;
1380 if (!is_null($toreturn)) {
1381 $toreturn = clone($toreturn);
1383 return $toreturn;
1387 * Get all the category objects, including a count of the number of questions in that category,
1388 * for all the categories in the lists $contexts.
1390 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1391 * @param string $sortorder used as the ORDER BY clause in the select statement.
1392 * @param bool $top Whether to return the top categories or not.
1393 * @return array of category objects.
1395 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1396 global $DB;
1397 $topwhere = $top ? '' : 'AND c.parent <> 0';
1398 return $DB->get_records_sql("
1399 SELECT c.*, (SELECT count(1) FROM {question} q
1400 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1401 FROM {question_categories} c
1402 WHERE c.contextid IN ($contexts) $topwhere
1403 ORDER BY $sortorder");
1407 * Output an array of question categories.
1409 * @param array $contexts The list of contexts.
1410 * @param bool $top Whether to return the top categories or not.
1411 * @param int $currentcat
1412 * @param bool $popupform
1413 * @param int $nochildrenof
1414 * @return array
1416 function question_category_options($contexts, $top = false, $currentcat = 0,
1417 $popupform = false, $nochildrenof = -1) {
1418 global $CFG;
1419 $pcontexts = array();
1420 foreach ($contexts as $context) {
1421 $pcontexts[] = $context->id;
1423 $contextslist = join($pcontexts, ', ');
1425 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1427 if ($top) {
1428 $categories = question_fix_top_names($categories);
1431 $categories = question_add_context_in_key($categories);
1432 $categories = add_indented_names($categories, $nochildrenof);
1434 // sort cats out into different contexts
1435 $categoriesarray = array();
1436 foreach ($pcontexts as $contextid) {
1437 $context = context::instance_by_id($contextid);
1438 $contextstring = $context->get_context_name(true, true);
1439 foreach ($categories as $category) {
1440 if ($category->contextid == $contextid) {
1441 $cid = $category->id;
1442 if ($currentcat != $cid || $currentcat == 0) {
1443 $a = new stdClass;
1444 $a->name = format_string($category->indentedname, true,
1445 array('context' => $context));
1446 if ($category->idnumber !== null && $category->idnumber !== '') {
1447 $a->idnumber = s($category->idnumber);
1449 if (!empty($category->questioncount)) {
1450 $a->questioncount = $category->questioncount;
1452 if (isset($a->idnumber) && isset($a->questioncount)) {
1453 $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
1454 } else if (isset($a->idnumber)) {
1455 $formattedname = get_string('categorynamewithidnumber', 'question', $a);
1456 } else if (isset($a->questioncount)) {
1457 $formattedname = get_string('categorynamewithcount', 'question', $a);
1458 } else {
1459 $formattedname = $a->name;
1461 $categoriesarray[$contextstring][$cid] = $formattedname;
1466 if ($popupform) {
1467 $popupcats = array();
1468 foreach ($categoriesarray as $contextstring => $optgroup) {
1469 $group = array();
1470 foreach ($optgroup as $key => $value) {
1471 $key = str_replace($CFG->wwwroot, '', $key);
1472 $group[$key] = $value;
1474 $popupcats[] = array($contextstring => $group);
1476 return $popupcats;
1477 } else {
1478 return $categoriesarray;
1482 function question_add_context_in_key($categories) {
1483 $newcatarray = array();
1484 foreach ($categories as $id => $category) {
1485 $category->parent = "$category->parent,$category->contextid";
1486 $category->id = "$category->id,$category->contextid";
1487 $newcatarray["$id,$category->contextid"] = $category;
1489 return $newcatarray;
1493 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1495 * @param array $categories An array of question categories.
1496 * @return array The same question category list given to the function, with the top category names being translated.
1498 function question_fix_top_names($categories) {
1500 foreach ($categories as $id => $category) {
1501 if ($category->parent == 0) {
1502 $context = context::instance_by_id($category->contextid);
1503 $categories[$id]->name = get_string('topfor', 'question', $context->get_context_name(false));
1507 return $categories;
1511 * @return array of question category ids of the category and all subcategories.
1513 function question_categorylist($categoryid) {
1514 global $DB;
1516 // final list of category IDs
1517 $categorylist = array();
1519 // a list of category IDs to check for any sub-categories
1520 $subcategories = array($categoryid);
1522 while ($subcategories) {
1523 foreach ($subcategories as $subcategory) {
1524 // if anything from the temporary list was added already, then we have a loop
1525 if (isset($categorylist[$subcategory])) {
1526 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1528 $categorylist[$subcategory] = $subcategory;
1531 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1533 $subcategories = $DB->get_records_select_menu('question_categories',
1534 "parent $in", $params, NULL, 'id,id AS id2');
1537 return $categorylist;
1541 * Get all parent categories of a given question category in decending order.
1542 * @param int $categoryid for which you want to find the parents.
1543 * @return array of question category ids of all parents categories.
1545 function question_categorylist_parents(int $categoryid) {
1546 global $DB;
1547 $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1548 if (!$parent) {
1549 return [];
1551 $categorylist = [$parent];
1552 $currentid = $parent;
1553 while ($currentid) {
1554 $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1555 if ($currentid) {
1556 $categorylist[] = $currentid;
1559 // Present the list in decending order (the top category at the top).
1560 $categorylist = array_reverse($categorylist);
1561 return $categorylist;
1564 //===========================
1565 // Import/Export Functions
1566 //===========================
1569 * Get list of available import or export formats
1570 * @param string $type 'import' if import list, otherwise export list assumed
1571 * @return array sorted list of import/export formats available
1573 function get_import_export_formats($type) {
1574 global $CFG;
1575 require_once($CFG->dirroot . '/question/format.php');
1577 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1579 $fileformatname = array();
1580 foreach ($formatclasses as $component => $formatclass) {
1582 $format = new $formatclass();
1583 if ($type == 'import') {
1584 $provided = $format->provide_import();
1585 } else {
1586 $provided = $format->provide_export();
1589 if ($provided) {
1590 list($notused, $fileformat) = explode('_', $component, 2);
1591 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1595 core_collator::asort($fileformatnames);
1596 return $fileformatnames;
1601 * Create a reasonable default file name for exporting questions from a particular
1602 * category.
1603 * @param object $course the course the questions are in.
1604 * @param object $category the question category.
1605 * @return string the filename.
1607 function question_default_export_filename($course, $category) {
1608 // We build a string that is an appropriate name (questions) from the lang pack,
1609 // then the corse shortname, then the question category name, then a timestamp.
1611 $base = clean_filename(get_string('exportfilename', 'question'));
1613 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1614 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1616 $shortname = clean_filename($course->shortname);
1617 if ($shortname == '' || $shortname == '_' ) {
1618 $shortname = $course->id;
1621 $categoryname = clean_filename(format_string($category->name));
1623 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1625 return $export_name;
1629 * Converts contextlevels to strings and back to help with reading/writing contexts
1630 * to/from import/export files.
1632 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1633 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1635 class context_to_string_translator{
1637 * @var array used to translate between contextids and strings for this context.
1639 protected $contexttostringarray = array();
1641 public function __construct($contexts) {
1642 $this->generate_context_to_string_array($contexts);
1645 public function context_to_string($contextid) {
1646 return $this->contexttostringarray[$contextid];
1649 public function string_to_context($contextname) {
1650 $contextid = array_search($contextname, $this->contexttostringarray);
1651 return $contextid;
1654 protected function generate_context_to_string_array($contexts) {
1655 if (!$this->contexttostringarray) {
1656 $catno = 1;
1657 foreach ($contexts as $context) {
1658 switch ($context->contextlevel) {
1659 case CONTEXT_MODULE :
1660 $contextstring = 'module';
1661 break;
1662 case CONTEXT_COURSE :
1663 $contextstring = 'course';
1664 break;
1665 case CONTEXT_COURSECAT :
1666 $contextstring = "cat$catno";
1667 $catno++;
1668 break;
1669 case CONTEXT_SYSTEM :
1670 $contextstring = 'system';
1671 break;
1673 $this->contexttostringarray[$context->id] = $contextstring;
1681 * Check capability on category
1683 * @param int|stdClass $questionorid object or id. If an object is passed, it should include ->contextid and ->createdby.
1684 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1685 * @param int $notused no longer used.
1686 * @return bool this user has the capability $cap for this question $question?
1687 * @throws coding_exception
1689 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1690 global $USER, $DB;
1692 if (is_numeric($questionorid)) {
1693 $questionid = (int)$questionorid;
1694 } else if (is_object($questionorid)) {
1695 // All we really need in this function is the contextid and author of the question.
1696 // We won't bother fetching other details of the question if these 2 fields are provided.
1697 if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1698 $question = $questionorid;
1699 } else if (!empty($questionorid->id)) {
1700 $questionid = $questionorid->id;
1704 // At this point, either $question or $questionid is expected to be set.
1705 if (isset($questionid)) {
1706 try {
1707 $question = question_bank::load_question_data($questionid);
1708 } catch (Exception $e) {
1709 // Let's log the exception for future debugging.
1710 debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1712 // Well, at least we tried. Seems that we really have to read from DB.
1713 $question = $DB->get_record_sql('SELECT q.id, q.createdby, qc.contextid
1714 FROM {question} q
1715 JOIN {question_categories} qc ON q.category = qc.id
1716 WHERE q.id = :id', ['id' => $questionid]);
1720 if (!isset($question)) {
1721 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1724 $context = context::instance_by_id($question->contextid);
1726 // These are existing questions capabilities that are set per category.
1727 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1728 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1730 if (!isset($capabilitieswithallandmine[$cap])) {
1731 return has_capability('moodle/question:' . $cap, $context);
1732 } else {
1733 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1734 ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1739 * Require capability on question.
1741 function question_require_capability_on($question, $cap) {
1742 if (!question_has_capability_on($question, $cap)) {
1743 print_error('nopermissions', '', '', $cap);
1745 return true;
1749 * @param object $context a context
1750 * @return string A URL for editing questions in this context.
1752 function question_edit_url($context) {
1753 global $CFG, $SITE;
1754 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1755 return false;
1757 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1758 $defaultcategory = question_get_default_category($context->id);
1759 if ($defaultcategory) {
1760 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1762 switch ($context->contextlevel) {
1763 case CONTEXT_SYSTEM:
1764 return $baseurl . 'courseid=' . $SITE->id;
1765 case CONTEXT_COURSECAT:
1766 // This is nasty, becuase we can only edit questions in a course
1767 // context at the moment, so for now we just return false.
1768 return false;
1769 case CONTEXT_COURSE:
1770 return $baseurl . 'courseid=' . $context->instanceid;
1771 case CONTEXT_MODULE:
1772 return $baseurl . 'cmid=' . $context->instanceid;
1778 * Adds question bank setting links to the given navigation node if caps are met.
1780 * @param navigation_node $navigationnode The navigation node to add the question branch to
1781 * @param object $context
1782 * @return navigation_node Returns the question branch that was added
1784 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1785 global $PAGE;
1787 if ($context->contextlevel == CONTEXT_COURSE) {
1788 $params = array('courseid'=>$context->instanceid);
1789 } else if ($context->contextlevel == CONTEXT_MODULE) {
1790 $params = array('cmid'=>$context->instanceid);
1791 } else {
1792 return;
1795 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1796 $params['cat'] = $cat;
1799 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1800 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1802 $contexts = new question_edit_contexts($context);
1803 if ($contexts->have_one_edit_tab_cap('questions')) {
1804 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1805 '/question/edit.php', $params), navigation_node::TYPE_SETTING, null, 'questions');
1807 if ($contexts->have_one_edit_tab_cap('categories')) {
1808 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1809 '/question/category.php', $params), navigation_node::TYPE_SETTING, null, 'categories');
1811 if ($contexts->have_one_edit_tab_cap('import')) {
1812 $questionnode->add(get_string('import', 'question'), new moodle_url(
1813 '/question/import.php', $params), navigation_node::TYPE_SETTING, null, 'import');
1815 if ($contexts->have_one_edit_tab_cap('export')) {
1816 $questionnode->add(get_string('export', 'question'), new moodle_url(
1817 '/question/export.php', $params), navigation_node::TYPE_SETTING, null, 'export');
1820 return $questionnode;
1824 * @return array all the capabilities that relate to accessing particular questions.
1826 function question_get_question_capabilities() {
1827 return array(
1828 'moodle/question:add',
1829 'moodle/question:editmine',
1830 'moodle/question:editall',
1831 'moodle/question:viewmine',
1832 'moodle/question:viewall',
1833 'moodle/question:usemine',
1834 'moodle/question:useall',
1835 'moodle/question:movemine',
1836 'moodle/question:moveall',
1841 * @return array all the question bank capabilities.
1843 function question_get_all_capabilities() {
1844 $caps = question_get_question_capabilities();
1845 $caps[] = 'moodle/question:managecategory';
1846 $caps[] = 'moodle/question:flag';
1847 return $caps;
1852 * Tracks all the contexts related to the one where we are currently editing
1853 * questions, and provides helper methods to check permissions.
1855 * @copyright 2007 Jamie Pratt me@jamiep.org
1856 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1858 class question_edit_contexts {
1860 public static $caps = array(
1861 'editq' => array('moodle/question:add',
1862 'moodle/question:editmine',
1863 'moodle/question:editall',
1864 'moodle/question:viewmine',
1865 'moodle/question:viewall',
1866 'moodle/question:usemine',
1867 'moodle/question:useall',
1868 'moodle/question:movemine',
1869 'moodle/question:moveall'),
1870 'questions'=>array('moodle/question:add',
1871 'moodle/question:editmine',
1872 'moodle/question:editall',
1873 'moodle/question:viewmine',
1874 'moodle/question:viewall',
1875 'moodle/question:movemine',
1876 'moodle/question:moveall'),
1877 'categories'=>array('moodle/question:managecategory'),
1878 'import'=>array('moodle/question:add'),
1879 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1881 protected $allcontexts;
1884 * Constructor
1885 * @param context the current context.
1887 public function __construct(context $thiscontext) {
1888 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1892 * @return context[] all parent contexts
1894 public function all() {
1895 return $this->allcontexts;
1899 * @return context lowest context which must be either the module or course context
1901 public function lowest() {
1902 return $this->allcontexts[0];
1906 * @param string $cap capability
1907 * @return context[] parent contexts having capability, zero based index
1909 public function having_cap($cap) {
1910 $contextswithcap = array();
1911 foreach ($this->allcontexts as $context) {
1912 if (has_capability($cap, $context)) {
1913 $contextswithcap[] = $context;
1916 return $contextswithcap;
1920 * @param array $caps capabilities
1921 * @return context[] parent contexts having at least one of $caps, zero based index
1923 public function having_one_cap($caps) {
1924 $contextswithacap = array();
1925 foreach ($this->allcontexts as $context) {
1926 foreach ($caps as $cap) {
1927 if (has_capability($cap, $context)) {
1928 $contextswithacap[] = $context;
1929 break; //done with caps loop
1933 return $contextswithacap;
1937 * @param string $tabname edit tab name
1938 * @return context[] parent contexts having at least one of $caps, zero based index
1940 public function having_one_edit_tab_cap($tabname) {
1941 return $this->having_one_cap(self::$caps[$tabname]);
1945 * @return context[] those contexts where a user can add a question and then use it.
1947 public function having_add_and_use() {
1948 $contextswithcap = array();
1949 foreach ($this->allcontexts as $context) {
1950 if (!has_capability('moodle/question:add', $context)) {
1951 continue;
1953 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1954 continue;
1956 $contextswithcap[] = $context;
1958 return $contextswithcap;
1962 * Has at least one parent context got the cap $cap?
1964 * @param string $cap capability
1965 * @return boolean
1967 public function have_cap($cap) {
1968 return (count($this->having_cap($cap)));
1972 * Has at least one parent context got one of the caps $caps?
1974 * @param array $caps capability
1975 * @return boolean
1977 public function have_one_cap($caps) {
1978 foreach ($caps as $cap) {
1979 if ($this->have_cap($cap)) {
1980 return true;
1983 return false;
1987 * Has at least one parent context got one of the caps for actions on $tabname
1989 * @param string $tabname edit tab name
1990 * @return boolean
1992 public function have_one_edit_tab_cap($tabname) {
1993 return $this->have_one_cap(self::$caps[$tabname]);
1997 * Throw error if at least one parent context hasn't got the cap $cap
1999 * @param string $cap capability
2001 public function require_cap($cap) {
2002 if (!$this->have_cap($cap)) {
2003 print_error('nopermissions', '', '', $cap);
2008 * Throw error if at least one parent context hasn't got one of the caps $caps
2010 * @param array $caps capabilities
2012 public function require_one_cap($caps) {
2013 if (!$this->have_one_cap($caps)) {
2014 $capsstring = join($caps, ', ');
2015 print_error('nopermissions', '', '', $capsstring);
2020 * Throw error if at least one parent context hasn't got one of the caps $caps
2022 * @param string $tabname edit tab name
2024 public function require_one_edit_tab_cap($tabname) {
2025 if (!$this->have_one_edit_tab_cap($tabname)) {
2026 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
2033 * Helps call file_rewrite_pluginfile_urls with the right parameters.
2035 * @package core_question
2036 * @category files
2037 * @param string $text text being processed
2038 * @param string $file the php script used to serve files
2039 * @param int $contextid context ID
2040 * @param string $component component
2041 * @param string $filearea filearea
2042 * @param array $ids other IDs will be used to check file permission
2043 * @param int $itemid item ID
2044 * @param array $options options
2045 * @return string
2047 function question_rewrite_question_urls($text, $file, $contextid, $component,
2048 $filearea, array $ids, $itemid, array $options=null) {
2050 $idsstr = '';
2051 if (!empty($ids)) {
2052 $idsstr .= implode('/', $ids);
2054 if ($itemid !== null) {
2055 $idsstr .= '/' . $itemid;
2057 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
2058 $filearea, $idsstr, $options);
2062 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
2063 * viewing the question outside an attempt (for example, in the question bank
2064 * listing or in the quiz statistics report).
2066 * @param string $text the question text.
2067 * @param int $questionid the question id.
2068 * @param int $filecontextid the context id of the question being displayed.
2069 * @param string $filecomponent the component that owns the file area.
2070 * @param string $filearea the file area name.
2071 * @param int|null $itemid the file's itemid
2072 * @param int $previewcontextid the context id where the preview is being displayed.
2073 * @param string $previewcomponent component responsible for displaying the preview.
2074 * @param array $options text and file options ('forcehttps'=>false)
2075 * @return string $questiontext with URLs rewritten.
2077 function question_rewrite_question_preview_urls($text, $questionid,
2078 $filecontextid, $filecomponent, $filearea, $itemid,
2079 $previewcontextid, $previewcomponent, $options = null) {
2081 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2082 if ($itemid) {
2083 $path .= '/' . $itemid;
2086 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2087 $filecomponent, $filearea, $path, $options);
2091 * Called by pluginfile.php to serve files related to the 'question' core
2092 * component and for files belonging to qtypes.
2094 * For files that relate to questions in a question_attempt, then we delegate to
2095 * a function in the component that owns the attempt (for example in the quiz,
2096 * or in core question preview) to get necessary inforation.
2098 * (Note that, at the moment, all question file areas relate to questions in
2099 * attempts, so the If at the start of the last paragraph is always true.)
2101 * Does not return, either calls send_file_not_found(); or serves the file.
2103 * @package core_question
2104 * @category files
2105 * @param stdClass $course course settings object
2106 * @param stdClass $context context object
2107 * @param string $component the name of the component we are serving files for.
2108 * @param string $filearea the name of the file area.
2109 * @param array $args the remaining bits of the file path.
2110 * @param bool $forcedownload whether the user must be forced to download the file.
2111 * @param array $options additional options affecting the file serving
2113 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2114 global $DB, $CFG;
2116 // Special case, sending a question bank export.
2117 if ($filearea === 'export') {
2118 list($context, $course, $cm) = get_context_info_array($context->id);
2119 require_login($course, false, $cm);
2121 require_once($CFG->dirroot . '/question/editlib.php');
2122 $contexts = new question_edit_contexts($context);
2123 // check export capability
2124 $contexts->require_one_edit_tab_cap('export');
2125 $category_id = (int)array_shift($args);
2126 $format = array_shift($args);
2127 $cattofile = array_shift($args);
2128 $contexttofile = array_shift($args);
2129 $filename = array_shift($args);
2131 // load parent class for import/export
2132 require_once($CFG->dirroot . '/question/format.php');
2133 require_once($CFG->dirroot . '/question/editlib.php');
2134 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2136 $classname = 'qformat_' . $format;
2137 if (!class_exists($classname)) {
2138 send_file_not_found();
2141 $qformat = new $classname();
2143 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2144 send_file_not_found();
2147 $qformat->setCategory($category);
2148 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2149 $qformat->setCourse($course);
2151 if ($cattofile == 'withcategories') {
2152 $qformat->setCattofile(true);
2153 } else {
2154 $qformat->setCattofile(false);
2157 if ($contexttofile == 'withcontexts') {
2158 $qformat->setContexttofile(true);
2159 } else {
2160 $qformat->setContexttofile(false);
2163 if (!$qformat->exportpreprocess()) {
2164 send_file_not_found();
2165 print_error('exporterror', 'question', $thispageurl->out());
2168 // export data to moodle file pool
2169 if (!$content = $qformat->exportprocess()) {
2170 send_file_not_found();
2173 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2176 // Normal case, a file belonging to a question.
2177 $qubaidorpreview = array_shift($args);
2179 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2180 if ($qubaidorpreview === 'preview') {
2181 $previewcontextid = (int)array_shift($args);
2182 $previewcomponent = array_shift($args);
2183 $questionid = (int) array_shift($args);
2184 $previewcontext = context_helper::instance_by_id($previewcontextid);
2186 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2187 $previewcontext, $questionid,
2188 $context, $component, $filearea, $args,
2189 $forcedownload, $options), 'callbackmissing');
2191 if ($result === 'callbackmissing') {
2192 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2193 "{$previewcomponent}_question_preview_pluginfile callback. " .
2194 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
2197 send_file_not_found();
2200 // 2. A question being attempted in the normal way.
2201 $qubaid = (int)$qubaidorpreview;
2202 $slot = (int)array_shift($args);
2204 $module = $DB->get_field('question_usages', 'component',
2205 array('id' => $qubaid));
2206 if (!$module) {
2207 send_file_not_found();
2210 if ($module === 'core_question_preview') {
2211 require_once($CFG->dirroot . '/question/previewlib.php');
2212 return question_preview_question_pluginfile($course, $context,
2213 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2215 } else {
2216 $dir = core_component::get_component_directory($module);
2217 if (!file_exists("$dir/lib.php")) {
2218 send_file_not_found();
2220 include_once("$dir/lib.php");
2222 $filefunction = $module . '_question_pluginfile';
2223 if (function_exists($filefunction)) {
2224 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2225 $args, $forcedownload, $options);
2228 // Okay, we're here so lets check for function without 'mod_'.
2229 if (strpos($module, 'mod_') === 0) {
2230 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2231 if (function_exists($filefunctionold)) {
2232 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2233 $args, $forcedownload, $options);
2237 send_file_not_found();
2242 * Serve questiontext files in the question text when they are displayed in this report.
2244 * @package core_files
2245 * @category files
2246 * @param context $previewcontext the context in which the preview is happening.
2247 * @param int $questionid the question id.
2248 * @param context $filecontext the file (question) context.
2249 * @param string $filecomponent the component the file belongs to.
2250 * @param string $filearea the file area.
2251 * @param array $args remaining file args.
2252 * @param bool $forcedownload.
2253 * @param array $options additional options affecting the file serving.
2255 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2256 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2257 global $DB;
2259 // Verify that contextid matches the question.
2260 $question = $DB->get_record_sql('
2261 SELECT q.*, qc.contextid
2262 FROM {question} q
2263 JOIN {question_categories} qc ON qc.id = q.category
2264 WHERE q.id = :id AND qc.contextid = :contextid',
2265 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2267 // Check the capability.
2268 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2269 require_login($course, false, $cm);
2271 question_require_capability_on($question, 'use');
2273 $fs = get_file_storage();
2274 $relativepath = implode('/', $args);
2275 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2276 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2277 send_file_not_found();
2280 send_stored_file($file, 0, 0, $forcedownload, $options);
2284 * Create url for question export
2286 * @param int $contextid, current context
2287 * @param int $categoryid, categoryid
2288 * @param string $format
2289 * @param string $withcategories
2290 * @param string $ithcontexts
2291 * @param moodle_url export file url
2293 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2294 $withcontexts, $filename) {
2295 global $CFG;
2296 $urlbase = "$CFG->wwwroot/pluginfile.php";
2297 return moodle_url::make_file_url($urlbase,
2298 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2299 "/{$withcontexts}/{$filename}", true);
2303 * Get the URL to export a single question (exportone.php).
2305 * @param stdClass|question_definition $question the question definition as obtained from
2306 * question_bank::load_question_data() or question_bank::make_question().
2307 * (Only ->id and ->contextid are used.)
2308 * @return moodle_url the requested URL.
2310 function question_get_export_single_question_url($question) {
2311 $params = ['id' => $question->id, 'sesskey' => sesskey()];
2312 $context = context::instance_by_id($question->contextid);
2313 switch ($context->contextlevel) {
2314 case CONTEXT_MODULE:
2315 $params['cmid'] = $context->instanceid;
2316 break;
2318 case CONTEXT_COURSE:
2319 $params['courseid'] = $context->instanceid;
2320 break;
2322 default:
2323 $params['courseid'] = SITEID;
2326 return new moodle_url('/question/exportone.php', $params);
2330 * Return a list of page types
2331 * @param string $pagetype current page type
2332 * @param stdClass $parentcontext Block's parent context
2333 * @param stdClass $currentcontext Current context of block
2335 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2336 global $CFG;
2337 $types = array(
2338 'question-*'=>get_string('page-question-x', 'question'),
2339 'question-edit'=>get_string('page-question-edit', 'question'),
2340 'question-category'=>get_string('page-question-category', 'question'),
2341 'question-export'=>get_string('page-question-export', 'question'),
2342 'question-import'=>get_string('page-question-import', 'question')
2344 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2345 require_once($CFG->dirroot . '/course/lib.php');
2346 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2347 } else {
2348 return $types;
2353 * Does an activity module use the question bank?
2355 * @param string $modname The name of the module (without mod_ prefix).
2356 * @return bool true if the module uses questions.
2358 function question_module_uses_questions($modname) {
2359 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2360 return true;
2363 $component = 'mod_'.$modname;
2364 if (component_callback_exists($component, 'question_pluginfile')) {
2365 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2366 return true;
2369 return false;