2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
124 if (question_engine
::questions_in_use($questionids)) {
128 foreach (core_component
::get_plugin_list('mod') as $module => $path) {
129 $lib = $path . '/lib.php';
130 if (is_readable($lib)) {
133 $fn = $module . '_questions_in_use';
134 if (function_exists($fn)) {
135 if ($fn($questionids)) {
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)) {
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
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) {
168 if (is_object($context)) {
169 $contextid = $context->id
;
170 } else if (is_numeric($context)) {
171 $contextid = $context;
173 print_error('invalidcontextinhasanyquestions', 'question');
175 return $DB->record_exists_sql("SELECT *
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.
203 } else if ($matchgrades == 'nearest') {
204 // Work out nearest value
207 foreach ($gradeoptionsfull as $value => $option) {
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
211 $bestmismatch = $newmismatch;
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:
239 * @param int $categoryid The category ID.
241 function question_remove_stale_questions_from_category($categoryid) {
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
);
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|coursecat $category course category object
262 function question_category_delete_safe($category) {
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) {
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))) {
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)) {
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) {
343 $question = $DB->get_record_sql('
344 SELECT q.*, qc.contextid
346 JOIN {question_categories} qc ON qc.id = q.category
347 WHERE q.id = ?', array($questionid));
349 // In some situations, for example if this was a child of a
350 // Cloze question that was previously deleted, the question may already
351 // have gone. In this case, just do nothing.
355 // Do not delete a question if it is used by an activity module
356 if (questions_in_use(array($questionid))) {
360 $dm = new question_engine_data_mapper();
361 $dm->delete_previews($questionid);
363 // delete questiontype-specific data
364 question_bank
::get_qtype($question->qtype
, false)->delete_question(
365 $questionid, $question->contextid
);
367 // Delete all tag instances.
368 core_tag_tag
::remove_all_item_tags('core_question', 'question', $question->id
);
370 // Now recursively delete all child questions
371 if ($children = $DB->get_records('question',
372 array('parent' => $questionid), '', 'id, qtype')) {
373 foreach ($children as $child) {
374 if ($child->id
!= $questionid) {
375 question_delete_question($child->id
);
380 // Finally delete the question record itself
381 $DB->delete_records('question', array('id' => $questionid));
382 question_bank
::notify_question_edited($questionid);
386 * All question categories and their questions are deleted for this context id.
388 * @param object $contextid The contextid to delete question categories from
389 * @return array Feedback from deletes (if any)
391 function question_delete_context($contextid) {
394 //To store feedback to be showed at the end of the process
395 $feedbackdata = array();
398 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
399 $fields = 'id, parent, name, contextid';
400 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
401 //Sort categories following their tree (parent-child) relationships
402 //this will make the feedback more readable
403 $categories = sort_categories_by_tree($categories);
405 foreach ($categories as $category) {
406 question_category_delete_safe($category);
409 $feedbackdata[] = array($category->name
, $strcatdeleted);
412 return $feedbackdata;
416 * All question categories and their questions are deleted for this course.
418 * @param stdClass $course an object representing the activity
419 * @param boolean $feedback to specify if the process must output a summary of its work
422 function question_delete_course($course, $feedback=true) {
423 $coursecontext = context_course
::instance($course->id
);
424 $feedbackdata = question_delete_context($coursecontext->id
, $feedback);
426 // Inform about changes performed if feedback is enabled.
427 if ($feedback && $feedbackdata) {
428 $table = new html_table();
429 $table->head
= array(get_string('category', 'question'), get_string('action'));
430 $table->data
= $feedbackdata;
431 echo html_writer
::table($table);
437 * Category is about to be deleted,
438 * 1/ All question categories and their questions are deleted for this course category.
439 * 2/ All questions are moved to new category
441 * @param object|coursecat $category course category object
442 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
443 * category where content moved
444 * @param boolean $feedback to specify if the process must output a summary of its work
447 function question_delete_course_category($category, $newcategory, $feedback=true) {
450 $context = context_coursecat
::instance($category->id
);
451 if (empty($newcategory)) {
452 $feedbackdata = question_delete_context($context->id
, $feedback);
454 // Output feedback if requested.
455 if ($feedback && $feedbackdata) {
456 $table = new html_table();
457 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
458 $table->data
= $feedbackdata;
459 echo html_writer
::table($table);
463 // Move question categories to the new context.
464 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
468 // Only move question categories if there is any question category at all!
469 if ($topcategory = question_get_top_category($context->id
)) {
470 $newtopcategory = question_get_top_category($newcontext->id
, true);
472 question_move_category_to_context($topcategory->id
, $context->id
, $newcontext->id
);
473 $DB->set_field('question_categories', 'parent', $newtopcategory->id
, array('parent' => $topcategory->id
));
474 // Now delete the top category.
475 $DB->delete_records('question_categories', array('id' => $topcategory->id
));
480 $a->oldplace
= $context->get_context_name();
481 $a->newplace
= $newcontext->get_context_name();
482 echo $OUTPUT->notification(
483 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
491 * Enter description here...
493 * @param array $questionids of question ids
494 * @param object $newcontextid the context to create the saved category in.
495 * @param string $oldplace a textual description of the think being deleted,
496 * e.g. from get_context_name
497 * @param object $newcategory
498 * @return mixed false on
500 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
501 $newcategory = null) {
504 // Make a category in the parent context to move the questions to.
505 if (is_null($newcategory)) {
506 $newcategory = new stdClass();
507 $newcategory->parent
= 0;
508 $newcategory->contextid
= $newcontextid;
509 $newcategory->name
= get_string('questionsrescuedfrom', 'question', $oldplace);
510 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
511 $newcategory->sortorder
= 999;
512 $newcategory->stamp
= make_unique_id_code();
513 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
516 // Move any remaining questions to the 'saved' category.
517 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
524 * All question categories and their questions are deleted for this activity.
526 * @param object $cm the course module object representing the activity
527 * @param boolean $feedback to specify if the process must output a summary of its work
530 function question_delete_activity($cm, $feedback=true) {
533 $modcontext = context_module
::instance($cm->id
);
534 $feedbackdata = question_delete_context($modcontext->id
, $feedback);
535 // Inform about changes performed if feedback is enabled.
536 if ($feedback && $feedbackdata) {
537 $table = new html_table();
538 $table->head
= array(get_string('category', 'question'), get_string('action'));
539 $table->data
= $feedbackdata;
540 echo html_writer
::table($table);
546 * This function will handle moving all tag instances to a new context for a
547 * given list of questions.
549 * Questions can be tagged in up to two contexts:
550 * 1.) The context the question exists in.
551 * 2.) The course context (if the question context is a higher context.
552 * E.g. course category context or system context.
554 * This means a question that exists in a higher context (e.g. course cat or
555 * system context) may have multiple groups of tags in any number of child
558 * Questions in the course category context can be move "down" a context level
559 * into one of their child course contexts or activity contexts which affects the
560 * availability of that question in other courses / activities.
562 * In this case it makes the questions no longer available in the other course or
563 * activity contexts so we need to make sure that the tag instances in those other
564 * contexts are removed.
566 * @param stdClass[] $questions The list of question being moved (must include
567 * the id and contextid)
568 * @param context $newcontext The Moodle context the questions are being moved to
570 function question_move_question_tags_to_new_context(array $questions, context
$newcontext) {
571 // If the questions are moving to a new course/activity context then we need to
572 // find any existing tag instances from any unavailable course contexts and
573 // delete them because they will no longer be applicable (we don't support
574 // tagging questions across courses).
575 $instancestodelete = [];
576 $instancesfornewcontext = [];
577 $newcontextparentids = $newcontext->get_parent_context_ids();
578 $questionids = array_map(function($question) {
579 return $question->id
;
581 $questionstagobjects = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
583 foreach ($questions as $question) {
584 $tagobjects = $questionstagobjects[$question->id
];
586 foreach ($tagobjects as $tagobject) {
587 $tagid = $tagobject->taginstanceid
;
588 $tagcontextid = $tagobject->taginstancecontextid
;
589 $istaginnewcontext = $tagcontextid == $newcontext->id
;
590 $istaginquestioncontext = $tagcontextid == $question->contextid
;
592 if ($istaginnewcontext) {
593 // This tag instance is already in the correct context so we can
598 if ($istaginquestioncontext) {
599 // This tag instance is in the question context so it needs to be
601 $instancesfornewcontext[] = $tagid;
605 // These tag instances are in neither the new context nor the
606 // question context so we need to determine what to do based on
607 // the context they are in and the new question context.
608 $tagcontext = context
::instance_by_id($tagcontextid);
609 $tagcoursecontext = $tagcontext->get_course_context(false);
610 // The tag is in a course context if get_course_context() returns
612 $istaginstancecontextcourse = !empty($tagcoursecontext)
613 && $tagcontext->id
== $tagcoursecontext->id
;
615 if ($istaginstancecontextcourse) {
616 // If the tag instance is in a course context we need to add some
618 $tagcontextparentids = $tagcontext->get_parent_context_ids();
619 $isnewcontextaparent = in_array($newcontext->id
, $tagcontextparentids);
620 $isnewcontextachild = in_array($tagcontext->id
, $newcontextparentids);
622 if ($isnewcontextaparent) {
623 // If the tag instance is a course context tag and the new
624 // context is still a parent context to the tag context then
625 // we can leave this tag where it is.
627 } else if ($isnewcontextachild) {
628 // If the new context is a child context (e.g. activity) of this
629 // tag instance then we should move all of this tag instance
630 // down into the activity context along with the question.
631 $instancesfornewcontext[] = $tagid;
633 // If the tag is in a course context that is no longer a parent
634 // or child of the new context then this tag instance should be
636 $instancestodelete[] = $tagid;
639 // This is a catch all for any tag instances not in the question
640 // context or a course context. These tag instances should be
641 // updated to the new context id. This will clean up old invalid
643 $instancesfornewcontext[] = $tagid;
648 if (!empty($instancestodelete)) {
649 // Delete any course context tags that may no longer be valid.
650 core_tag_tag
::delete_instances_by_id($instancestodelete);
653 if (!empty($instancesfornewcontext)) {
654 // Update the tag instances to the new context id.
655 core_tag_tag
::change_instances_context($instancesfornewcontext, $newcontext);
660 * This function should be considered private to the question bank, it is called from
661 * question/editlib.php question/contextmoveq.php and a few similar places to to the
662 * work of acutally moving questions and associated data. However, callers of this
663 * function also have to do other work, which is why you should not call this method
664 * directly from outside the questionbank.
666 * @param array $questionids of question ids.
667 * @param integer $newcategoryid the id of the category to move to.
669 function question_move_questions_to_category($questionids, $newcategoryid) {
672 $newcontextid = $DB->get_field('question_categories', 'contextid',
673 array('id' => $newcategoryid));
674 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
675 $questions = $DB->get_records_sql("
676 SELECT q.id, q.qtype, qc.contextid
678 JOIN {question_categories} qc ON q.category = qc.id
679 WHERE q.id $questionidcondition", $params);
680 foreach ($questions as $question) {
681 if ($newcontextid != $question->contextid
) {
682 question_bank
::get_qtype($question->qtype
)->move_files(
683 $question->id
, $question->contextid
, $newcontextid);
687 // Move the questions themselves.
688 $DB->set_field_select('question', 'category', $newcategoryid,
689 "id $questionidcondition", $params);
691 // Move any subquestions belonging to them.
692 $DB->set_field_select('question', 'category', $newcategoryid,
693 "parent $questionidcondition", $params);
695 $newcontext = context
::instance_by_id($newcontextid);
696 question_move_question_tags_to_new_context($questions, $newcontext);
698 // TODO Deal with datasets.
700 // Purge these questions from the cache.
701 foreach ($questions as $question) {
702 question_bank
::notify_question_edited($question->id
);
709 * This function helps move a question cateogry to a new context by moving all
710 * the files belonging to all the questions to the new context.
711 * Also moves subcategories.
712 * @param integer $categoryid the id of the category being moved.
713 * @param integer $oldcontextid the old context id.
714 * @param integer $newcontextid the new context id.
716 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
720 $questionids = $DB->get_records_menu('question',
721 array('category' => $categoryid), '', 'id,qtype');
722 foreach ($questionids as $questionid => $qtype) {
723 question_bank
::get_qtype($qtype)->move_files(
724 $questionid, $oldcontextid, $newcontextid);
725 // Purge this question from the cache.
726 question_bank
::notify_question_edited($questionid);
728 $questions[] = (object) [
730 'contextid' => $oldcontextid
734 $newcontext = context
::instance_by_id($newcontextid);
735 question_move_question_tags_to_new_context($questions, $newcontext);
737 $subcatids = $DB->get_records_menu('question_categories',
738 array('parent' => $categoryid), '', 'id,1');
739 foreach ($subcatids as $subcatid => $notused) {
740 $DB->set_field('question_categories', 'contextid', $newcontextid,
741 array('id' => $subcatid));
742 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
747 * Generate the URL for starting a new preview of a given question with the given options.
748 * @param integer $questionid the question to preview.
749 * @param string $preferredbehaviour the behaviour to use for the preview.
750 * @param float $maxmark the maximum to mark the question out of.
751 * @param question_display_options $displayoptions the display options to use.
752 * @param int $variant the variant of the question to preview. If null, one will
753 * be picked randomly.
754 * @param object $context context to run the preview in (affects things like
755 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
756 * @return moodle_url the URL.
758 function question_preview_url($questionid, $preferredbehaviour = null,
759 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
761 $params = array('id' => $questionid);
763 if (is_null($context)) {
765 $context = $PAGE->context
;
767 if ($context->contextlevel
== CONTEXT_MODULE
) {
768 $params['cmid'] = $context->instanceid
;
769 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
770 $params['courseid'] = $context->instanceid
;
773 if (!is_null($preferredbehaviour)) {
774 $params['behaviour'] = $preferredbehaviour;
777 if (!is_null($maxmark)) {
778 $params['maxmark'] = $maxmark;
781 if (!is_null($displayoptions)) {
782 $params['correctness'] = $displayoptions->correctness
;
783 $params['marks'] = $displayoptions->marks
;
784 $params['markdp'] = $displayoptions->markdp
;
785 $params['feedback'] = (bool) $displayoptions->feedback
;
786 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
787 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
788 $params['history'] = (bool) $displayoptions->history
;
792 $params['variant'] = $variant;
795 return new moodle_url('/question/preview.php', $params);
799 * @return array that can be passed as $params to the {@link popup_action} constructor.
801 function question_preview_popup_params() {
809 * Given a list of ids, load the basic information about a set of questions from
810 * the questions table. The $join and $extrafields arguments can be used together
811 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
812 * read the code below to see how the SQL is assembled. Throws exceptions on error.
814 * @param array $questionids array of question ids to load. If null, then all
815 * questions matched by $join will be loaded.
816 * @param string $extrafields extra SQL code to be added to the query.
817 * @param string $join extra SQL code to be added to the query.
818 * @param array $extraparams values for any placeholders in $join.
819 * You must use named placeholders.
820 * @param string $orderby what to order the results by. Optional, default is unspecified order.
822 * @return array partially complete question objects. You need to call get_question_options
823 * on them before they can be properly used.
825 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
826 $extraparams = array(), $orderby = '') {
829 if ($questionids === null) {
833 if (empty($questionids)) {
837 list($questionidcondition, $params) = $DB->get_in_or_equal(
838 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
839 $where = 'WHERE q.id ' . $questionidcondition;
843 $join = 'JOIN ' . $join;
847 $extrafields = ', ' . $extrafields;
851 $orderby = 'ORDER BY ' . $orderby;
854 $sql = "SELECT q.*, qc.contextid{$extrafields}
856 JOIN {question_categories} qc ON q.category = qc.id
861 // Load the questions.
862 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
863 foreach ($questions as $question) {
864 $question->_partiallyloaded
= true;
871 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
872 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
873 * read the code below to see how the SQL is assembled. Throws exceptions on error.
875 * @param array $questionids array of question ids.
876 * @param string $extrafields extra SQL code to be added to the query.
877 * @param string $join extra SQL code to be added to the query.
878 * @param array $extraparams values for any placeholders in $join.
879 * You are strongly recommended to use named placeholder.
881 * @return array question objects.
883 function question_load_questions($questionids, $extrafields = '', $join = '') {
884 $questions = question_preload_questions($questionids, $extrafields, $join);
886 // Load the question type specific information
887 if (!get_question_options($questions)) {
888 return 'Could not load the question options';
895 * Private function to factor common code out of get_question_options().
897 * @param object $question the question to tidy.
898 * @param stdClass $category The question_categories record for the given $question.
899 * @param stdClass[]|null $tagobjects The tags for the given $question.
900 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
902 function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
905 // Load question-type specific fields.
906 if (!question_bank
::is_qtype_installed($question->qtype
)) {
907 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
908 'qtype_missingtype')) . $question->questiontext
;
910 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
912 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
913 $question->defaultmark +
= 0;
914 $question->penalty +
= 0;
916 if (isset($question->_partiallyloaded
)) {
917 unset($question->_partiallyloaded
);
920 $question->categoryobject
= $category;
922 if (!is_null($tagobjects)) {
923 $categorycontext = context
::instance_by_id($category->contextid
);
924 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
925 $question->coursetagobjects
= $sortedtagobjects->coursetagobjects
;
926 $question->coursetags
= $sortedtagobjects->coursetags
;
927 $question->tagobjects
= $sortedtagobjects->tagobjects
;
928 $question->tags
= $sortedtagobjects->tags
;
933 * Updates the question objects with question type specific
934 * information by calling {@link get_question_options()}
936 * Can be called either with an array of question objects or with a single
939 * @param mixed $questions Either an array of question objects to be updated
940 * or just a single question object
941 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
942 * @param stdClass[] $filtercourses The courses to filter the course tags by.
943 * @return bool Indicates success or failure.
945 function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
948 $questionlist = is_array($questions) ?
$questions : [$questions];
952 if (empty($questionlist)) {
956 foreach ($questionlist as $question) {
957 $questionids[] = $question->id
;
959 if (!in_array($question->category
, $categoryids)) {
960 $categoryids[] = $question->category
;
964 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
966 if ($loadtags && core_tag_tag
::is_enabled('core_question', 'question')) {
967 $tagobjectsbyquestion = core_tag_tag
::get_items_tags('core_question', 'question', $questionids);
969 $tagobjectsbyquestion = null;
972 foreach ($questionlist as $question) {
973 if (is_null($tagobjectsbyquestion)) {
976 $tagobjects = $tagobjectsbyquestion[$question->id
];
979 _tidy_question($question, $categories[$question->category
], $tagobjects, $filtercourses);
986 * Sort question tags by course or normal tags.
988 * This function also search tag instances that may have a context id that don't match either a course or
989 * question context and fix the data setting the correct context id.
991 * @param stdClass[] $tagobjects The tags for the given $question.
992 * @param stdClass $categorycontext The question categories context.
993 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
994 * @return stdClass $sortedtagobjects Sorted tag objects.
996 function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
998 // Questions can have two sets of tag instances. One set at the
999 // course context level and another at the context the question
1000 // belongs to (e.g. course category, system etc).
1001 $sortedtagobjects = new stdClass();
1002 $sortedtagobjects->coursetagobjects
= [];
1003 $sortedtagobjects->coursetags
= [];
1004 $sortedtagobjects->tagobjects
= [];
1005 $sortedtagobjects->tags
= [];
1006 $taginstanceidstonormalise = [];
1007 $filtercoursecontextids = [];
1008 $hasfiltercourses = !empty($filtercourses);
1010 if ($hasfiltercourses) {
1011 // If we're being asked to filter the course tags by a set of courses
1012 // then get the context ids to filter below.
1013 $filtercoursecontextids = array_map(function($course) {
1014 $coursecontext = context_course
::instance($course->id
);
1015 return $coursecontext->id
;
1019 foreach ($tagobjects as $tagobject) {
1020 $tagcontextid = $tagobject->taginstancecontextid
;
1021 $tagcontext = context
::instance_by_id($tagcontextid);
1022 $tagcoursecontext = $tagcontext->get_course_context(false);
1023 // This is a course tag if the tag context is a course context which
1024 // doesn't match the question's context. Any tag in the question context
1025 // is not considered a course tag, it belongs to the question.
1026 $iscoursetag = $tagcoursecontext
1027 && $tagcontext->id
== $tagcoursecontext->id
1028 && $tagcontext->id
!= $categorycontext->id
;
1031 // Any tag instance in a course context level is considered a course tag.
1032 if (!$hasfiltercourses ||
in_array($tagcontextid, $filtercoursecontextids)) {
1033 // Add the tag to the list of course tags if we aren't being
1034 // asked to filter or if this tag is in the list of courses
1035 // we're being asked to filter by.
1036 $sortedtagobjects->coursetagobjects
[] = $tagobject;
1037 $sortedtagobjects->coursetags
[$tagobject->id
] = $tagobject->get_display_name();
1040 // All non course context level tag instances or tags in the question
1041 // context belong to the context that the question was created in.
1042 $sortedtagobjects->tagobjects
[] = $tagobject;
1043 $sortedtagobjects->tags
[$tagobject->id
] = $tagobject->get_display_name();
1045 // Due to legacy tag implementations that don't force the recording
1046 // of a context id, some tag instances may have context ids that don't
1047 // match either a course context or the question context. In this case
1048 // we should take the opportunity to fix up the data and set the correct
1050 if ($tagcontext->id
!= $categorycontext->id
) {
1051 $taginstanceidstonormalise[] = $tagobject->taginstanceid
;
1052 // Update the object properties to reflect the DB update that will
1054 $tagobject->taginstancecontextid
= $categorycontext->id
;
1059 if (!empty($taginstanceidstonormalise)) {
1060 // If we found any tag instances with incorrect context id data then we can
1061 // correct those values now by setting them to the question context id.
1062 core_tag_tag
::change_instances_context($taginstanceidstonormalise, $categorycontext);
1065 return $sortedtagobjects;
1069 * Print the icon for the question type
1071 * @param object $question The question object for which the icon is required.
1072 * Only $question->qtype is used.
1073 * @return string the HTML for the img tag.
1075 function print_question_icon($question) {
1077 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
1081 * Creates a stamp that uniquely identifies this version of the question
1083 * In future we want this to use a hash of the question data to guarantee that
1084 * identical versions have the same version stamp.
1086 * @param object $question
1087 * @return string A unique version stamp
1089 function question_hash($question) {
1090 return make_unique_id_code();
1093 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1096 * returns the categories with their names ordered following parent-child relationships
1097 * finally it tries to return pending categories (those being orphaned, whose parent is
1098 * incorrect) to avoid missing any category from original array.
1100 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1103 $children = array();
1104 $keys = array_keys($categories);
1106 foreach ($keys as $key) {
1107 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
1108 $children[$key] = $categories[$key];
1109 $categories[$key]->processed
= true;
1110 $children = $children +
sort_categories_by_tree(
1111 $categories, $children[$key]->id
, $level+
1);
1114 //If level = 1, we have finished, try to look for non processed categories
1115 // (bad parent) and sort them too
1117 foreach ($keys as $key) {
1118 // If not processed and it's a good candidate to start (because its
1119 // parent doesn't exist in the course)
1120 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
1121 array('contextid' => $categories[$key]->contextid
,
1122 'id' => $categories[$key]->parent
))) {
1123 $children[$key] = $categories[$key];
1124 $categories[$key]->processed
= true;
1125 $children = $children +
sort_categories_by_tree(
1126 $categories, $children[$key]->id
, $level +
1);
1134 * Private method, only for the use of add_indented_names().
1136 * Recursively adds an indentedname field to each category, starting with the category
1137 * with id $id, and dealing with that category and all its children, and
1138 * return a new array, with those categories in the right order.
1140 * @param array $categories an array of categories which has had childids
1141 * fields added by flatten_category_tree(). Passed by reference for
1142 * performance only. It is not modfied.
1143 * @param int $id the category to start the indenting process from.
1144 * @param int $depth the indent depth. Used in recursive calls.
1145 * @return array a new array of categories, in the right order for the tree.
1147 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
1149 // Indent the name of this category.
1150 $newcategories = array();
1151 $newcategories[$id] = $categories[$id];
1152 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
1153 $categories[$id]->name
;
1155 // Recursively indent the children.
1156 foreach ($categories[$id]->childids
as $childid) {
1157 if ($childid != $nochildrenof) {
1158 $newcategories = $newcategories +
flatten_category_tree(
1159 $categories, $childid, $depth +
1, $nochildrenof);
1163 // Remove the childids array that were temporarily added.
1164 unset($newcategories[$id]->childids
);
1166 return $newcategories;
1170 * Format categories into an indented list reflecting the tree structure.
1172 * @param array $categories An array of category objects, for example from the.
1173 * @return array The formatted list of categories.
1175 function add_indented_names($categories, $nochildrenof = -1) {
1177 // Add an array to each category to hold the child category ids. This array
1178 // will be removed again by flatten_category_tree(). It should not be used
1179 // outside these two functions.
1180 foreach (array_keys($categories) as $id) {
1181 $categories[$id]->childids
= array();
1184 // Build the tree structure, and record which categories are top-level.
1185 // We have to be careful, because the categories array may include published
1186 // categories from other courses, but not their parents.
1187 $toplevelcategoryids = array();
1188 foreach (array_keys($categories) as $id) {
1189 if (!empty($categories[$id]->parent
) &&
1190 array_key_exists($categories[$id]->parent
, $categories)) {
1191 $categories[$categories[$id]->parent
]->childids
[] = $id;
1193 $toplevelcategoryids[] = $id;
1197 // Flatten the tree to and add the indents.
1198 $newcategories = array();
1199 foreach ($toplevelcategoryids as $id) {
1200 $newcategories = $newcategories +
flatten_category_tree(
1201 $categories, $id, 0, $nochildrenof);
1204 return $newcategories;
1208 * Output a select menu of question categories.
1210 * Categories from this course and (optionally) published categories from other courses
1211 * are included. Optionally, only categories the current user may edit can be included.
1213 * @param integer $courseid the id of the course to get the categories for.
1214 * @param integer $published if true, include publised categories from other courses.
1215 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1216 * @param integer $selected optionally, the id of a category to be selected by
1217 * default in the dropdown.
1219 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1220 $selected = "", $nochildrenof = -1) {
1221 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1222 false, $nochildrenof);
1226 $choose = 'choosedots';
1229 foreach ($categoriesarray as $group => $opts) {
1230 $options[] = array($group => $opts);
1232 echo html_writer
::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1233 $attrs = array('id' => 'id_movetocategory', 'class' => 'custom-select');
1234 echo html_writer
::select($options, 'category', $selected, $choose, $attrs);
1238 * @param integer $contextid a context id.
1239 * @return object the default question category for that context, or false if none.
1241 function question_get_default_category($contextid) {
1243 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1244 array($contextid), 'id', '*', 0, 1);
1245 if (!empty($category)) {
1246 return reset($category);
1253 * Gets the top category in the given context.
1254 * This function can optionally create the top category if it doesn't exist.
1256 * @param int $contextid A context id.
1257 * @param bool $create Whether create a top category if it doesn't exist.
1258 * @return bool|stdClass The top question category for that context, or false if none.
1260 function question_get_top_category($contextid, $create = false) {
1262 $category = $DB->get_record('question_categories',
1263 array('contextid' => $contextid, 'parent' => 0));
1265 if (!$category && $create) {
1266 // We need to make one.
1267 $category = new stdClass();
1268 $category->name
= 'top'; // A non-real name for the top category. It will be localised at the display time.
1269 $category->info
= '';
1270 $category->contextid
= $contextid;
1271 $category->parent
= 0;
1272 $category->sortorder
= 0;
1273 $category->stamp
= make_unique_id_code();
1274 $category->id
= $DB->insert_record('question_categories', $category);
1281 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1283 * @param array $contextids List of context ids
1286 function question_get_top_categories_for_contexts($contextids) {
1289 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1290 list($insql, $params) = $DB->get_in_or_equal($contextids);
1291 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1292 $topcategories = $DB->get_fieldset_sql($sql, $params);
1294 return $topcategories;
1298 * Gets the default category in the most specific context.
1299 * If no categories exist yet then default ones are created in all contexts.
1301 * @param array $contexts The context objects for this context and all parent contexts.
1302 * @return object The default category - the category in the course context
1304 function question_make_default_categories($contexts) {
1306 static $preferredlevels = array(
1307 CONTEXT_COURSE
=> 4,
1308 CONTEXT_MODULE
=> 3,
1309 CONTEXT_COURSECAT
=> 2,
1310 CONTEXT_SYSTEM
=> 1,
1315 // If it already exists, just return it.
1316 foreach ($contexts as $key => $context) {
1317 $topcategory = question_get_top_category($context->id
, true);
1318 if (!$exists = $DB->record_exists("question_categories",
1319 array('contextid' => $context->id
, 'parent' => $topcategory->id
))) {
1320 // Otherwise, we need to make one
1321 $category = new stdClass();
1322 $contextname = $context->get_context_name(false, true);
1323 $category->name
= get_string('defaultfor', 'question', $contextname);
1324 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1325 $category->contextid
= $context->id
;
1326 $category->parent
= $topcategory->id
;
1327 // By default, all categories get this number, and are sorted alphabetically.
1328 $category->sortorder
= 999;
1329 $category->stamp
= make_unique_id_code();
1330 $category->id
= $DB->insert_record('question_categories', $category);
1332 $category = question_get_default_category($context->id
);
1334 $thispreferredness = $preferredlevels[$context->contextlevel
];
1335 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1336 $thispreferredness +
= 10;
1338 if ($thispreferredness > $preferredness) {
1339 $toreturn = $category;
1340 $preferredness = $thispreferredness;
1344 if (!is_null($toreturn)) {
1345 $toreturn = clone($toreturn);
1351 * Get all the category objects, including a count of the number of questions in that category,
1352 * for all the categories in the lists $contexts.
1354 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1355 * @param string $sortorder used as the ORDER BY clause in the select statement.
1356 * @param bool $top Whether to return the top categories or not.
1357 * @return array of category objects.
1359 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
1361 $topwhere = $top ?
'' : 'AND c.parent <> 0';
1362 return $DB->get_records_sql("
1363 SELECT c.*, (SELECT count(1) FROM {question} q
1364 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1365 FROM {question_categories} c
1366 WHERE c.contextid IN ($contexts) $topwhere
1367 ORDER BY $sortorder");
1371 * Output an array of question categories.
1373 * @param array $contexts The list of contexts.
1374 * @param bool $top Whether to return the top categories or not.
1375 * @param int $currentcat
1376 * @param bool $popupform
1377 * @param int $nochildrenof
1380 function question_category_options($contexts, $top = false, $currentcat = 0,
1381 $popupform = false, $nochildrenof = -1) {
1383 $pcontexts = array();
1384 foreach ($contexts as $context) {
1385 $pcontexts[] = $context->id
;
1387 $contextslist = join($pcontexts, ', ');
1389 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
1392 $categories = question_fix_top_names($categories);
1395 $categories = question_add_context_in_key($categories);
1396 $categories = add_indented_names($categories, $nochildrenof);
1398 // sort cats out into different contexts
1399 $categoriesarray = array();
1400 foreach ($pcontexts as $contextid) {
1401 $context = context
::instance_by_id($contextid);
1402 $contextstring = $context->get_context_name(true, true);
1403 foreach ($categories as $category) {
1404 if ($category->contextid
== $contextid) {
1405 $cid = $category->id
;
1406 if ($currentcat != $cid ||
$currentcat == 0) {
1407 $countstring = !empty($category->questioncount
) ?
1408 " ($category->questioncount)" : '';
1409 $categoriesarray[$contextstring][$cid] =
1410 format_string($category->indentedname
, true,
1411 array('context' => $context)) . $countstring;
1417 $popupcats = array();
1418 foreach ($categoriesarray as $contextstring => $optgroup) {
1420 foreach ($optgroup as $key => $value) {
1421 $key = str_replace($CFG->wwwroot
, '', $key);
1422 $group[$key] = $value;
1424 $popupcats[] = array($contextstring => $group);
1428 return $categoriesarray;
1432 function question_add_context_in_key($categories) {
1433 $newcatarray = array();
1434 foreach ($categories as $id => $category) {
1435 $category->parent
= "$category->parent,$category->contextid";
1436 $category->id
= "$category->id,$category->contextid";
1437 $newcatarray["$id,$category->contextid"] = $category;
1439 return $newcatarray;
1443 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1445 * @param array $categories An array of question categories.
1446 * @return array The same question category list given to the function, with the top category names being translated.
1448 function question_fix_top_names($categories) {
1450 foreach ($categories as $id => $category) {
1451 if ($category->parent
== 0) {
1452 $context = context
::instance_by_id($category->contextid
);
1453 $categories[$id]->name
= get_string('topfor', 'question', $context->get_context_name(false));
1461 * @return array of question category ids of the category and all subcategories.
1463 function question_categorylist($categoryid) {
1466 // final list of category IDs
1467 $categorylist = array();
1469 // a list of category IDs to check for any sub-categories
1470 $subcategories = array($categoryid);
1472 while ($subcategories) {
1473 foreach ($subcategories as $subcategory) {
1474 // if anything from the temporary list was added already, then we have a loop
1475 if (isset($categorylist[$subcategory])) {
1476 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1478 $categorylist[$subcategory] = $subcategory;
1481 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1483 $subcategories = $DB->get_records_select_menu('question_categories',
1484 "parent $in", $params, NULL, 'id,id AS id2');
1487 return $categorylist;
1490 //===========================
1491 // Import/Export Functions
1492 //===========================
1495 * Get list of available import or export formats
1496 * @param string $type 'import' if import list, otherwise export list assumed
1497 * @return array sorted list of import/export formats available
1499 function get_import_export_formats($type) {
1501 require_once($CFG->dirroot
. '/question/format.php');
1503 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1505 $fileformatname = array();
1506 foreach ($formatclasses as $component => $formatclass) {
1508 $format = new $formatclass();
1509 if ($type == 'import') {
1510 $provided = $format->provide_import();
1512 $provided = $format->provide_export();
1516 list($notused, $fileformat) = explode('_', $component, 2);
1517 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1521 core_collator
::asort($fileformatnames);
1522 return $fileformatnames;
1527 * Create a reasonable default file name for exporting questions from a particular
1529 * @param object $course the course the questions are in.
1530 * @param object $category the question category.
1531 * @return string the filename.
1533 function question_default_export_filename($course, $category) {
1534 // We build a string that is an appropriate name (questions) from the lang pack,
1535 // then the corse shortname, then the question category name, then a timestamp.
1537 $base = clean_filename(get_string('exportfilename', 'question'));
1539 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1540 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1542 $shortname = clean_filename($course->shortname
);
1543 if ($shortname == '' ||
$shortname == '_' ) {
1544 $shortname = $course->id
;
1547 $categoryname = clean_filename(format_string($category->name
));
1549 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1551 return $export_name;
1555 * Converts contextlevels to strings and back to help with reading/writing contexts
1556 * to/from import/export files.
1558 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1561 class context_to_string_translator
{
1563 * @var array used to translate between contextids and strings for this context.
1565 protected $contexttostringarray = array();
1567 public function __construct($contexts) {
1568 $this->generate_context_to_string_array($contexts);
1571 public function context_to_string($contextid) {
1572 return $this->contexttostringarray
[$contextid];
1575 public function string_to_context($contextname) {
1576 $contextid = array_search($contextname, $this->contexttostringarray
);
1580 protected function generate_context_to_string_array($contexts) {
1581 if (!$this->contexttostringarray
) {
1583 foreach ($contexts as $context) {
1584 switch ($context->contextlevel
) {
1585 case CONTEXT_MODULE
:
1586 $contextstring = 'module';
1588 case CONTEXT_COURSE
:
1589 $contextstring = 'course';
1591 case CONTEXT_COURSECAT
:
1592 $contextstring = "cat$catno";
1595 case CONTEXT_SYSTEM
:
1596 $contextstring = 'system';
1599 $this->contexttostringarray
[$context->id
] = $contextstring;
1607 * Check capability on category
1609 * @param mixed $questionorid object or id. If an object is passed, it should include ->contextid and ->createdby.
1610 * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1611 * @param integer $notused no longer used.
1612 * @return boolean this user has the capability $cap for this question $question?
1614 function question_has_capability_on($questionorid, $cap, $notused = -1) {
1617 if (is_numeric($questionorid)) {
1618 $question = question_bank
::load_question_data((int)$questionorid);
1619 } else if (is_object($questionorid)) {
1620 if (isset($questionorid->contextid
) && isset($questionorid->createdby
)) {
1621 $question = $questionorid;
1624 if (!isset($question) && isset($questionorid->id
) && $questionorid->id
!= 0) {
1625 $question = question_bank
::load_question_data($questionorid->id
);
1628 throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1631 $context = context
::instance_by_id($question->contextid
);
1633 // These are existing questions capabilities that are set per category.
1634 // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1635 $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1];
1637 if (!isset($capabilitieswithallandmine[$cap])) {
1638 return has_capability('moodle/question:' . $cap, $context);
1640 return has_capability('moodle/question:' . $cap . 'all', $context) ||
1641 ($question->createdby
== $USER->id
&& has_capability('moodle/question:' . $cap . 'mine', $context));
1646 * Require capability on question.
1648 function question_require_capability_on($question, $cap) {
1649 if (!question_has_capability_on($question, $cap)) {
1650 print_error('nopermissions', '', '', $cap);
1656 * @param object $context a context
1657 * @return string A URL for editing questions in this context.
1659 function question_edit_url($context) {
1661 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1664 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1665 $defaultcategory = question_get_default_category($context->id
);
1666 if ($defaultcategory) {
1667 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1669 switch ($context->contextlevel
) {
1670 case CONTEXT_SYSTEM
:
1671 return $baseurl . 'courseid=' . $SITE->id
;
1672 case CONTEXT_COURSECAT
:
1673 // This is nasty, becuase we can only edit questions in a course
1674 // context at the moment, so for now we just return false.
1676 case CONTEXT_COURSE
:
1677 return $baseurl . 'courseid=' . $context->instanceid
;
1678 case CONTEXT_MODULE
:
1679 return $baseurl . 'cmid=' . $context->instanceid
;
1685 * Adds question bank setting links to the given navigation node if caps are met.
1687 * @param navigation_node $navigationnode The navigation node to add the question branch to
1688 * @param object $context
1689 * @return navigation_node Returns the question branch that was added
1691 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1694 if ($context->contextlevel
== CONTEXT_COURSE
) {
1695 $params = array('courseid'=>$context->instanceid
);
1696 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1697 $params = array('cmid'=>$context->instanceid
);
1702 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1703 $params['cat'] = $cat;
1706 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1707 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
, null, 'questionbank');
1709 $contexts = new question_edit_contexts($context);
1710 if ($contexts->have_one_edit_tab_cap('questions')) {
1711 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1712 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
, null, 'questions');
1714 if ($contexts->have_one_edit_tab_cap('categories')) {
1715 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1716 '/question/category.php', $params), navigation_node
::TYPE_SETTING
, null, 'categories');
1718 if ($contexts->have_one_edit_tab_cap('import')) {
1719 $questionnode->add(get_string('import', 'question'), new moodle_url(
1720 '/question/import.php', $params), navigation_node
::TYPE_SETTING
, null, 'import');
1722 if ($contexts->have_one_edit_tab_cap('export')) {
1723 $questionnode->add(get_string('export', 'question'), new moodle_url(
1724 '/question/export.php', $params), navigation_node
::TYPE_SETTING
, null, 'export');
1727 return $questionnode;
1731 * @return array all the capabilities that relate to accessing particular questions.
1733 function question_get_question_capabilities() {
1735 'moodle/question:add',
1736 'moodle/question:editmine',
1737 'moodle/question:editall',
1738 'moodle/question:viewmine',
1739 'moodle/question:viewall',
1740 'moodle/question:usemine',
1741 'moodle/question:useall',
1742 'moodle/question:movemine',
1743 'moodle/question:moveall',
1748 * @return array all the question bank capabilities.
1750 function question_get_all_capabilities() {
1751 $caps = question_get_question_capabilities();
1752 $caps[] = 'moodle/question:managecategory';
1753 $caps[] = 'moodle/question:flag';
1759 * Tracks all the contexts related to the one where we are currently editing
1760 * questions, and provides helper methods to check permissions.
1762 * @copyright 2007 Jamie Pratt me@jamiep.org
1763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1765 class question_edit_contexts
{
1767 public static $caps = array(
1768 'editq' => array('moodle/question:add',
1769 'moodle/question:editmine',
1770 'moodle/question:editall',
1771 'moodle/question:viewmine',
1772 'moodle/question:viewall',
1773 'moodle/question:usemine',
1774 'moodle/question:useall',
1775 'moodle/question:movemine',
1776 'moodle/question:moveall'),
1777 'questions'=>array('moodle/question:add',
1778 'moodle/question:editmine',
1779 'moodle/question:editall',
1780 'moodle/question:viewmine',
1781 'moodle/question:viewall',
1782 'moodle/question:movemine',
1783 'moodle/question:moveall'),
1784 'categories'=>array('moodle/question:managecategory'),
1785 'import'=>array('moodle/question:add'),
1786 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1788 protected $allcontexts;
1792 * @param context the current context.
1794 public function __construct(context
$thiscontext) {
1795 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1799 * @return array all parent contexts
1801 public function all() {
1802 return $this->allcontexts
;
1806 * @return object lowest context which must be either the module or course context
1808 public function lowest() {
1809 return $this->allcontexts
[0];
1813 * @param string $cap capability
1814 * @return array parent contexts having capability, zero based index
1816 public function having_cap($cap) {
1817 $contextswithcap = array();
1818 foreach ($this->allcontexts
as $context) {
1819 if (has_capability($cap, $context)) {
1820 $contextswithcap[] = $context;
1823 return $contextswithcap;
1827 * @param array $caps capabilities
1828 * @return array parent contexts having at least one of $caps, zero based index
1830 public function having_one_cap($caps) {
1831 $contextswithacap = array();
1832 foreach ($this->allcontexts
as $context) {
1833 foreach ($caps as $cap) {
1834 if (has_capability($cap, $context)) {
1835 $contextswithacap[] = $context;
1836 break; //done with caps loop
1840 return $contextswithacap;
1844 * @param string $tabname edit tab name
1845 * @return array parent contexts having at least one of $caps, zero based index
1847 public function having_one_edit_tab_cap($tabname) {
1848 return $this->having_one_cap(self
::$caps[$tabname]);
1852 * @return those contexts where a user can add a question and then use it.
1854 public function having_add_and_use() {
1855 $contextswithcap = array();
1856 foreach ($this->allcontexts
as $context) {
1857 if (!has_capability('moodle/question:add', $context)) {
1860 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1863 $contextswithcap[] = $context;
1865 return $contextswithcap;
1869 * Has at least one parent context got the cap $cap?
1871 * @param string $cap capability
1874 public function have_cap($cap) {
1875 return (count($this->having_cap($cap)));
1879 * Has at least one parent context got one of the caps $caps?
1881 * @param array $caps capability
1884 public function have_one_cap($caps) {
1885 foreach ($caps as $cap) {
1886 if ($this->have_cap($cap)) {
1894 * Has at least one parent context got one of the caps for actions on $tabname
1896 * @param string $tabname edit tab name
1899 public function have_one_edit_tab_cap($tabname) {
1900 return $this->have_one_cap(self
::$caps[$tabname]);
1904 * Throw error if at least one parent context hasn't got the cap $cap
1906 * @param string $cap capability
1908 public function require_cap($cap) {
1909 if (!$this->have_cap($cap)) {
1910 print_error('nopermissions', '', '', $cap);
1915 * Throw error if at least one parent context hasn't got one of the caps $caps
1917 * @param array $cap capabilities
1919 public function require_one_cap($caps) {
1920 if (!$this->have_one_cap($caps)) {
1921 $capsstring = join($caps, ', ');
1922 print_error('nopermissions', '', '', $capsstring);
1927 * Throw error if at least one parent context hasn't got one of the caps $caps
1929 * @param string $tabname edit tab name
1931 public function require_one_edit_tab_cap($tabname) {
1932 if (!$this->have_one_edit_tab_cap($tabname)) {
1933 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1940 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1942 * @package core_question
1944 * @param string $text text being processed
1945 * @param string $file the php script used to serve files
1946 * @param int $contextid context ID
1947 * @param string $component component
1948 * @param string $filearea filearea
1949 * @param array $ids other IDs will be used to check file permission
1950 * @param int $itemid item ID
1951 * @param array $options options
1954 function question_rewrite_question_urls($text, $file, $contextid, $component,
1955 $filearea, array $ids, $itemid, array $options=null) {
1959 $idsstr .= implode('/', $ids);
1961 if ($itemid !== null) {
1962 $idsstr .= '/' . $itemid;
1964 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1965 $filearea, $idsstr, $options);
1969 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1970 * viewing the question outside an attempt (for example, in the question bank
1971 * listing or in the quiz statistics report).
1973 * @param string $text the question text.
1974 * @param int $questionid the question id.
1975 * @param int $filecontextid the context id of the question being displayed.
1976 * @param string $filecomponent the component that owns the file area.
1977 * @param string $filearea the file area name.
1978 * @param int|null $itemid the file's itemid
1979 * @param int $previewcontextid the context id where the preview is being displayed.
1980 * @param string $previewcomponent component responsible for displaying the preview.
1981 * @param array $options text and file options ('forcehttps'=>false)
1982 * @return string $questiontext with URLs rewritten.
1984 function question_rewrite_question_preview_urls($text, $questionid,
1985 $filecontextid, $filecomponent, $filearea, $itemid,
1986 $previewcontextid, $previewcomponent, $options = null) {
1988 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1990 $path .= '/' . $itemid;
1993 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1994 $filecomponent, $filearea, $path, $options);
1998 * Called by pluginfile.php to serve files related to the 'question' core
1999 * component and for files belonging to qtypes.
2001 * For files that relate to questions in a question_attempt, then we delegate to
2002 * a function in the component that owns the attempt (for example in the quiz,
2003 * or in core question preview) to get necessary inforation.
2005 * (Note that, at the moment, all question file areas relate to questions in
2006 * attempts, so the If at the start of the last paragraph is always true.)
2008 * Does not return, either calls send_file_not_found(); or serves the file.
2010 * @package core_question
2012 * @param stdClass $course course settings object
2013 * @param stdClass $context context object
2014 * @param string $component the name of the component we are serving files for.
2015 * @param string $filearea the name of the file area.
2016 * @param array $args the remaining bits of the file path.
2017 * @param bool $forcedownload whether the user must be forced to download the file.
2018 * @param array $options additional options affecting the file serving
2020 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
2023 // Special case, sending a question bank export.
2024 if ($filearea === 'export') {
2025 list($context, $course, $cm) = get_context_info_array($context->id
);
2026 require_login($course, false, $cm);
2028 require_once($CFG->dirroot
. '/question/editlib.php');
2029 $contexts = new question_edit_contexts($context);
2030 // check export capability
2031 $contexts->require_one_edit_tab_cap('export');
2032 $category_id = (int)array_shift($args);
2033 $format = array_shift($args);
2034 $cattofile = array_shift($args);
2035 $contexttofile = array_shift($args);
2036 $filename = array_shift($args);
2038 // load parent class for import/export
2039 require_once($CFG->dirroot
. '/question/format.php');
2040 require_once($CFG->dirroot
. '/question/editlib.php');
2041 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
2043 $classname = 'qformat_' . $format;
2044 if (!class_exists($classname)) {
2045 send_file_not_found();
2048 $qformat = new $classname();
2050 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2051 send_file_not_found();
2054 $qformat->setCategory($category);
2055 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2056 $qformat->setCourse($course);
2058 if ($cattofile == 'withcategories') {
2059 $qformat->setCattofile(true);
2061 $qformat->setCattofile(false);
2064 if ($contexttofile == 'withcontexts') {
2065 $qformat->setContexttofile(true);
2067 $qformat->setContexttofile(false);
2070 if (!$qformat->exportpreprocess()) {
2071 send_file_not_found();
2072 print_error('exporterror', 'question', $thispageurl->out());
2075 // export data to moodle file pool
2076 if (!$content = $qformat->exportprocess()) {
2077 send_file_not_found();
2080 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
2083 // Normal case, a file belonging to a question.
2084 $qubaidorpreview = array_shift($args);
2086 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2087 if ($qubaidorpreview === 'preview') {
2088 $previewcontextid = (int)array_shift($args);
2089 $previewcomponent = array_shift($args);
2090 $questionid = (int) array_shift($args);
2091 $previewcontext = context_helper
::instance_by_id($previewcontextid);
2093 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2094 $previewcontext, $questionid,
2095 $context, $component, $filearea, $args,
2096 $forcedownload, $options), 'callbackmissing');
2098 if ($result === 'callbackmissing') {
2099 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2100 "{$previewcomponent}_question_preview_pluginfile callback. " .
2101 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER
);
2104 send_file_not_found();
2107 // 2. A question being attempted in the normal way.
2108 $qubaid = (int)$qubaidorpreview;
2109 $slot = (int)array_shift($args);
2111 $module = $DB->get_field('question_usages', 'component',
2112 array('id' => $qubaid));
2114 send_file_not_found();
2117 if ($module === 'core_question_preview') {
2118 require_once($CFG->dirroot
. '/question/previewlib.php');
2119 return question_preview_question_pluginfile($course, $context,
2120 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
2123 $dir = core_component
::get_component_directory($module);
2124 if (!file_exists("$dir/lib.php")) {
2125 send_file_not_found();
2127 include_once("$dir/lib.php");
2129 $filefunction = $module . '_question_pluginfile';
2130 if (function_exists($filefunction)) {
2131 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2132 $args, $forcedownload, $options);
2135 // Okay, we're here so lets check for function without 'mod_'.
2136 if (strpos($module, 'mod_') === 0) {
2137 $filefunctionold = substr($module, 4) . '_question_pluginfile';
2138 if (function_exists($filefunctionold)) {
2139 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2140 $args, $forcedownload, $options);
2144 send_file_not_found();
2149 * Serve questiontext files in the question text when they are displayed in this report.
2151 * @package core_files
2153 * @param context $previewcontext the context in which the preview is happening.
2154 * @param int $questionid the question id.
2155 * @param context $filecontext the file (question) context.
2156 * @param string $filecomponent the component the file belongs to.
2157 * @param string $filearea the file area.
2158 * @param array $args remaining file args.
2159 * @param bool $forcedownload.
2160 * @param array $options additional options affecting the file serving.
2162 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2163 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2166 // Verify that contextid matches the question.
2167 $question = $DB->get_record_sql('
2168 SELECT q.*, qc.contextid
2170 JOIN {question_categories} qc ON qc.id = q.category
2171 WHERE q.id = :id AND qc.contextid = :contextid',
2172 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
2174 // Check the capability.
2175 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
2176 require_login($course, false, $cm);
2178 question_require_capability_on($question, 'use');
2180 $fs = get_file_storage();
2181 $relativepath = implode('/', $args);
2182 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2183 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2184 send_file_not_found();
2187 send_stored_file($file, 0, 0, $forcedownload, $options);
2191 * Create url for question export
2193 * @param int $contextid, current context
2194 * @param int $categoryid, categoryid
2195 * @param string $format
2196 * @param string $withcategories
2197 * @param string $ithcontexts
2198 * @param moodle_url export file url
2200 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2201 $withcontexts, $filename) {
2203 $urlbase = "$CFG->wwwroot/pluginfile.php";
2204 return moodle_url
::make_file_url($urlbase,
2205 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2206 "/{$withcontexts}/{$filename}", true);
2210 * Return a list of page types
2211 * @param string $pagetype current page type
2212 * @param stdClass $parentcontext Block's parent context
2213 * @param stdClass $currentcontext Current context of block
2215 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2218 'question-*'=>get_string('page-question-x', 'question'),
2219 'question-edit'=>get_string('page-question-edit', 'question'),
2220 'question-category'=>get_string('page-question-category', 'question'),
2221 'question-export'=>get_string('page-question-export', 'question'),
2222 'question-import'=>get_string('page-question-import', 'question')
2224 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
2225 require_once($CFG->dirroot
. '/course/lib.php');
2226 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2233 * Does an activity module use the question bank?
2235 * @param string $modname The name of the module (without mod_ prefix).
2236 * @return bool true if the module uses questions.
2238 function question_module_uses_questions($modname) {
2239 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
2243 $component = 'mod_'.$modname;
2244 if (component_callback_exists($component, 'question_pluginfile')) {
2245 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);