MDL-56303 quiz: lack of quiz filtering
[moodle.git] / lib / questionlib.php
blob5d766ee21c70747eb3d466badc01fe367cb62cb9
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|coursecat $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 $DB->delete_records('tag_instance', array('component' => 'core_question', 'itemid' => $question->id));
370 // Now recursively delete all child questions
371 if ($children = $DB->get_records('question',
372 array('parent' => $questionid), '', 'id, qtype')) {
373 foreach ($children as $child) {
374 if ($child->id != $questionid) {
375 question_delete_question($child->id);
380 // Finally delete the question record itself
381 $DB->delete_records('question', array('id' => $questionid));
382 question_bank::notify_question_edited($questionid);
386 * All question categories and their questions are deleted for this context id.
388 * @param object $contextid The contextid to delete question categories from
389 * @return array Feedback from deletes (if any)
391 function question_delete_context($contextid) {
392 global $DB;
394 //To store feedback to be showed at the end of the process
395 $feedbackdata = array();
397 //Cache some strings
398 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
399 $fields = 'id, parent, name, contextid';
400 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
401 //Sort categories following their tree (parent-child) relationships
402 //this will make the feedback more readable
403 $categories = sort_categories_by_tree($categories);
405 foreach ($categories as $category) {
406 question_category_delete_safe($category);
408 //Fill feedback
409 $feedbackdata[] = array($category->name, $strcatdeleted);
412 return $feedbackdata;
416 * All question categories and their questions are deleted for this course.
418 * @param stdClass $course an object representing the activity
419 * @param boolean $feedback to specify if the process must output a summary of its work
420 * @return boolean
422 function question_delete_course($course, $feedback=true) {
423 $coursecontext = context_course::instance($course->id);
424 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
426 // Inform about changes performed if feedback is enabled.
427 if ($feedback && $feedbackdata) {
428 $table = new html_table();
429 $table->head = array(get_string('category', 'question'), get_string('action'));
430 $table->data = $feedbackdata;
431 echo html_writer::table($table);
433 return true;
437 * Category is about to be deleted,
438 * 1/ All question categories and their questions are deleted for this course category.
439 * 2/ All questions are moved to new category
441 * @param object|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
445 * @return boolean
447 function question_delete_course_category($category, $newcategory, $feedback=true) {
448 global $DB, $OUTPUT;
450 $context = context_coursecat::instance($category->id);
451 if (empty($newcategory)) {
452 $feedbackdata = question_delete_context($context->id, $feedback);
454 // Output feedback if requested.
455 if ($feedback && $feedbackdata) {
456 $table = new html_table();
457 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
458 $table->data = $feedbackdata;
459 echo html_writer::table($table);
462 } else {
463 // Move question categories to the new context.
464 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
465 return false;
468 // Update the contextid for any tag instances for questions in the old context.
469 $DB->set_field('tag_instance', 'contextid', $newcontext->id, array('component' => 'core_question',
470 'contextid' => $context->id));
472 $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid' => $context->id));
474 if ($feedback) {
475 $a = new stdClass();
476 $a->oldplace = $context->get_context_name();
477 $a->newplace = $newcontext->get_context_name();
478 echo $OUTPUT->notification(
479 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
483 return true;
487 * Enter description here...
489 * @param array $questionids of question ids
490 * @param object $newcontextid the context to create the saved category in.
491 * @param string $oldplace a textual description of the think being deleted,
492 * e.g. from get_context_name
493 * @param object $newcategory
494 * @return mixed false on
496 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
497 $newcategory = null) {
498 global $DB;
500 // Make a category in the parent context to move the questions to.
501 if (is_null($newcategory)) {
502 $newcategory = new stdClass();
503 $newcategory->parent = 0;
504 $newcategory->contextid = $newcontextid;
505 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
506 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
507 $newcategory->sortorder = 999;
508 $newcategory->stamp = make_unique_id_code();
509 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
512 // Move any remaining questions to the 'saved' category.
513 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
514 return false;
516 return $newcategory;
520 * All question categories and their questions are deleted for this activity.
522 * @param object $cm the course module object representing the activity
523 * @param boolean $feedback to specify if the process must output a summary of its work
524 * @return boolean
526 function question_delete_activity($cm, $feedback=true) {
527 global $DB;
529 $modcontext = context_module::instance($cm->id);
530 $feedbackdata = question_delete_context($modcontext->id, $feedback);
531 // Inform about changes performed if feedback is enabled.
532 if ($feedback && $feedbackdata) {
533 $table = new html_table();
534 $table->head = array(get_string('category', 'question'), get_string('action'));
535 $table->data = $feedbackdata;
536 echo html_writer::table($table);
538 return true;
542 * This function should be considered private to the question bank, it is called from
543 * question/editlib.php question/contextmoveq.php and a few similar places to to the
544 * work of acutally moving questions and associated data. However, callers of this
545 * function also have to do other work, which is why you should not call this method
546 * directly from outside the questionbank.
548 * @param array $questionids of question ids.
549 * @param integer $newcategoryid the id of the category to move to.
551 function question_move_questions_to_category($questionids, $newcategoryid) {
552 global $DB;
554 $newcontextid = $DB->get_field('question_categories', 'contextid',
555 array('id' => $newcategoryid));
556 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
557 $questions = $DB->get_records_sql("
558 SELECT q.id, q.qtype, qc.contextid
559 FROM {question} q
560 JOIN {question_categories} qc ON q.category = qc.id
561 WHERE q.id $questionidcondition", $params);
562 foreach ($questions as $question) {
563 if ($newcontextid != $question->contextid) {
564 question_bank::get_qtype($question->qtype)->move_files(
565 $question->id, $question->contextid, $newcontextid);
569 // Move the questions themselves.
570 $DB->set_field_select('question', 'category', $newcategoryid,
571 "id $questionidcondition", $params);
573 // Move any subquestions belonging to them.
574 $DB->set_field_select('question', 'category', $newcategoryid,
575 "parent $questionidcondition", $params);
577 // Update the contextid for any tag instances that may exist for these questions.
578 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
579 "component = 'core_question' AND itemid $questionidcondition", $params);
581 // TODO Deal with datasets.
583 // Purge these questions from the cache.
584 foreach ($questions as $question) {
585 question_bank::notify_question_edited($question->id);
588 return true;
592 * This function helps move a question cateogry to a new context by moving all
593 * the files belonging to all the questions to the new context.
594 * Also moves subcategories.
595 * @param integer $categoryid the id of the category being moved.
596 * @param integer $oldcontextid the old context id.
597 * @param integer $newcontextid the new context id.
599 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
600 global $DB;
602 $questionids = $DB->get_records_menu('question',
603 array('category' => $categoryid), '', 'id,qtype');
604 foreach ($questionids as $questionid => $qtype) {
605 question_bank::get_qtype($qtype)->move_files(
606 $questionid, $oldcontextid, $newcontextid);
607 // Purge this question from the cache.
608 question_bank::notify_question_edited($questionid);
611 if ($questionids) {
612 // Update the contextid for any tag instances that may exist for these questions.
613 list($questionids, $params) = $DB->get_in_or_equal(array_keys($questionids));
614 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
615 "component = 'core_question' AND itemid $questionids", $params);
618 $subcatids = $DB->get_records_menu('question_categories',
619 array('parent' => $categoryid), '', 'id,1');
620 foreach ($subcatids as $subcatid => $notused) {
621 $DB->set_field('question_categories', 'contextid', $newcontextid,
622 array('id' => $subcatid));
623 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
628 * Generate the URL for starting a new preview of a given question with the given options.
629 * @param integer $questionid the question to preview.
630 * @param string $preferredbehaviour the behaviour to use for the preview.
631 * @param float $maxmark the maximum to mark the question out of.
632 * @param question_display_options $displayoptions the display options to use.
633 * @param int $variant the variant of the question to preview. If null, one will
634 * be picked randomly.
635 * @param object $context context to run the preview in (affects things like
636 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
637 * @return moodle_url the URL.
639 function question_preview_url($questionid, $preferredbehaviour = null,
640 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
642 $params = array('id' => $questionid);
644 if (is_null($context)) {
645 global $PAGE;
646 $context = $PAGE->context;
648 if ($context->contextlevel == CONTEXT_MODULE) {
649 $params['cmid'] = $context->instanceid;
650 } else if ($context->contextlevel == CONTEXT_COURSE) {
651 $params['courseid'] = $context->instanceid;
654 if (!is_null($preferredbehaviour)) {
655 $params['behaviour'] = $preferredbehaviour;
658 if (!is_null($maxmark)) {
659 $params['maxmark'] = $maxmark;
662 if (!is_null($displayoptions)) {
663 $params['correctness'] = $displayoptions->correctness;
664 $params['marks'] = $displayoptions->marks;
665 $params['markdp'] = $displayoptions->markdp;
666 $params['feedback'] = (bool) $displayoptions->feedback;
667 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
668 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
669 $params['history'] = (bool) $displayoptions->history;
672 if ($variant) {
673 $params['variant'] = $variant;
676 return new moodle_url('/question/preview.php', $params);
680 * @return array that can be passed as $params to the {@link popup_action} constructor.
682 function question_preview_popup_params() {
683 return array(
684 'height' => 600,
685 'width' => 800,
690 * Given a list of ids, load the basic information about a set of questions from
691 * the questions table. The $join and $extrafields arguments can be used together
692 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
693 * read the code below to see how the SQL is assembled. Throws exceptions on error.
695 * @param array $questionids array of question ids to load. If null, then all
696 * questions matched by $join will be loaded.
697 * @param string $extrafields extra SQL code to be added to the query.
698 * @param string $join extra SQL code to be added to the query.
699 * @param array $extraparams values for any placeholders in $join.
700 * You must use named placeholders.
701 * @param string $orderby what to order the results by. Optional, default is unspecified order.
703 * @return array partially complete question objects. You need to call get_question_options
704 * on them before they can be properly used.
706 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
707 $extraparams = array(), $orderby = '') {
708 global $DB;
710 if ($questionids === null) {
711 $where = '';
712 $params = array();
713 } else {
714 if (empty($questionids)) {
715 return array();
718 list($questionidcondition, $params) = $DB->get_in_or_equal(
719 $questionids, SQL_PARAMS_NAMED, 'qid0000');
720 $where = 'WHERE q.id ' . $questionidcondition;
723 if ($join) {
724 $join = 'JOIN ' . $join;
727 if ($extrafields) {
728 $extrafields = ', ' . $extrafields;
731 if ($orderby) {
732 $orderby = 'ORDER BY ' . $orderby;
735 $sql = "SELECT q.*, qc.contextid{$extrafields}
736 FROM {question} q
737 JOIN {question_categories} qc ON q.category = qc.id
738 {$join}
739 {$where}
740 {$orderby}";
742 // Load the questions.
743 $questions = $DB->get_records_sql($sql, $extraparams + $params);
744 foreach ($questions as $question) {
745 $question->_partiallyloaded = true;
748 return $questions;
752 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
753 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
754 * read the code below to see how the SQL is assembled. Throws exceptions on error.
756 * @param array $questionids array of question ids.
757 * @param string $extrafields extra SQL code to be added to the query.
758 * @param string $join extra SQL code to be added to the query.
759 * @param array $extraparams values for any placeholders in $join.
760 * You are strongly recommended to use named placeholder.
762 * @return array question objects.
764 function question_load_questions($questionids, $extrafields = '', $join = '') {
765 $questions = question_preload_questions($questionids, $extrafields, $join);
767 // Load the question type specific information
768 if (!get_question_options($questions)) {
769 return 'Could not load the question options';
772 return $questions;
776 * Private function to factor common code out of get_question_options().
778 * @param object $question the question to tidy.
779 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
781 function _tidy_question($question, $loadtags = false) {
782 global $CFG;
784 // Load question-type specific fields.
785 if (!question_bank::is_qtype_installed($question->qtype)) {
786 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
787 'qtype_missingtype')) . $question->questiontext;
789 question_bank::get_qtype($question->qtype)->get_question_options($question);
791 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
792 $question->defaultmark += 0;
793 $question->penalty += 0;
795 if (isset($question->_partiallyloaded)) {
796 unset($question->_partiallyloaded);
799 if ($loadtags && !empty($CFG->usetags)) {
800 require_once($CFG->dirroot . '/tag/lib.php');
801 $question->tags = tag_get_tags_array('question', $question->id);
806 * Updates the question objects with question type specific
807 * information by calling {@link get_question_options()}
809 * Can be called either with an array of question objects or with a single
810 * question object.
812 * @param mixed $questions Either an array of question objects to be updated
813 * or just a single question object
814 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
815 * @return bool Indicates success or failure.
817 function get_question_options(&$questions, $loadtags = false) {
818 if (is_array($questions)) { // deal with an array of questions
819 foreach ($questions as $i => $notused) {
820 _tidy_question($questions[$i], $loadtags);
822 } else { // deal with single question
823 _tidy_question($questions, $loadtags);
825 return true;
829 * Print the icon for the question type
831 * @param object $question The question object for which the icon is required.
832 * Only $question->qtype is used.
833 * @return string the HTML for the img tag.
835 function print_question_icon($question) {
836 global $PAGE;
837 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
841 * Creates a stamp that uniquely identifies this version of the question
843 * In future we want this to use a hash of the question data to guarantee that
844 * identical versions have the same version stamp.
846 * @param object $question
847 * @return string A unique version stamp
849 function question_hash($question) {
850 return make_unique_id_code();
853 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
856 * returns the categories with their names ordered following parent-child relationships
857 * finally it tries to return pending categories (those being orphaned, whose parent is
858 * incorrect) to avoid missing any category from original array.
860 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
861 global $DB;
863 $children = array();
864 $keys = array_keys($categories);
866 foreach ($keys as $key) {
867 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
868 $children[$key] = $categories[$key];
869 $categories[$key]->processed = true;
870 $children = $children + sort_categories_by_tree(
871 $categories, $children[$key]->id, $level+1);
874 //If level = 1, we have finished, try to look for non processed categories
875 // (bad parent) and sort them too
876 if ($level == 1) {
877 foreach ($keys as $key) {
878 // If not processed and it's a good candidate to start (because its
879 // parent doesn't exist in the course)
880 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
881 array('contextid' => $categories[$key]->contextid,
882 'id' => $categories[$key]->parent))) {
883 $children[$key] = $categories[$key];
884 $categories[$key]->processed = true;
885 $children = $children + sort_categories_by_tree(
886 $categories, $children[$key]->id, $level + 1);
890 return $children;
894 * Private method, only for the use of add_indented_names().
896 * Recursively adds an indentedname field to each category, starting with the category
897 * with id $id, and dealing with that category and all its children, and
898 * return a new array, with those categories in the right order.
900 * @param array $categories an array of categories which has had childids
901 * fields added by flatten_category_tree(). Passed by reference for
902 * performance only. It is not modfied.
903 * @param int $id the category to start the indenting process from.
904 * @param int $depth the indent depth. Used in recursive calls.
905 * @return array a new array of categories, in the right order for the tree.
907 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
909 // Indent the name of this category.
910 $newcategories = array();
911 $newcategories[$id] = $categories[$id];
912 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
913 $categories[$id]->name;
915 // Recursively indent the children.
916 foreach ($categories[$id]->childids as $childid) {
917 if ($childid != $nochildrenof) {
918 $newcategories = $newcategories + flatten_category_tree(
919 $categories, $childid, $depth + 1, $nochildrenof);
923 // Remove the childids array that were temporarily added.
924 unset($newcategories[$id]->childids);
926 return $newcategories;
930 * Format categories into an indented list reflecting the tree structure.
932 * @param array $categories An array of category objects, for example from the.
933 * @return array The formatted list of categories.
935 function add_indented_names($categories, $nochildrenof = -1) {
937 // Add an array to each category to hold the child category ids. This array
938 // will be removed again by flatten_category_tree(). It should not be used
939 // outside these two functions.
940 foreach (array_keys($categories) as $id) {
941 $categories[$id]->childids = array();
944 // Build the tree structure, and record which categories are top-level.
945 // We have to be careful, because the categories array may include published
946 // categories from other courses, but not their parents.
947 $toplevelcategoryids = array();
948 foreach (array_keys($categories) as $id) {
949 if (!empty($categories[$id]->parent) &&
950 array_key_exists($categories[$id]->parent, $categories)) {
951 $categories[$categories[$id]->parent]->childids[] = $id;
952 } else {
953 $toplevelcategoryids[] = $id;
957 // Flatten the tree to and add the indents.
958 $newcategories = array();
959 foreach ($toplevelcategoryids as $id) {
960 $newcategories = $newcategories + flatten_category_tree(
961 $categories, $id, 0, $nochildrenof);
964 return $newcategories;
968 * Output a select menu of question categories.
970 * Categories from this course and (optionally) published categories from other courses
971 * are included. Optionally, only categories the current user may edit can be included.
973 * @param integer $courseid the id of the course to get the categories for.
974 * @param integer $published if true, include publised categories from other courses.
975 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
976 * @param integer $selected optionally, the id of a category to be selected by
977 * default in the dropdown.
979 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
980 $selected = "", $nochildrenof = -1) {
981 global $OUTPUT;
982 $categoriesarray = question_category_options($contexts, $top, $currentcat,
983 false, $nochildrenof);
984 if ($selected) {
985 $choose = '';
986 } else {
987 $choose = 'choosedots';
989 $options = array();
990 foreach ($categoriesarray as $group => $opts) {
991 $options[] = array($group => $opts);
993 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
994 echo html_writer::select($options, 'category', $selected, $choose, array('id' => 'id_movetocategory'));
998 * @param integer $contextid a context id.
999 * @return object the default question category for that context, or false if none.
1001 function question_get_default_category($contextid) {
1002 global $DB;
1003 $category = $DB->get_records('question_categories',
1004 array('contextid' => $contextid), 'id', '*', 0, 1);
1005 if (!empty($category)) {
1006 return reset($category);
1007 } else {
1008 return false;
1013 * Gets the default category in the most specific context.
1014 * If no categories exist yet then default ones are created in all contexts.
1016 * @param array $contexts The context objects for this context and all parent contexts.
1017 * @return object The default category - the category in the course context
1019 function question_make_default_categories($contexts) {
1020 global $DB;
1021 static $preferredlevels = array(
1022 CONTEXT_COURSE => 4,
1023 CONTEXT_MODULE => 3,
1024 CONTEXT_COURSECAT => 2,
1025 CONTEXT_SYSTEM => 1,
1028 $toreturn = null;
1029 $preferredness = 0;
1030 // If it already exists, just return it.
1031 foreach ($contexts as $key => $context) {
1032 if (!$exists = $DB->record_exists("question_categories",
1033 array('contextid' => $context->id))) {
1034 // Otherwise, we need to make one
1035 $category = new stdClass();
1036 $contextname = $context->get_context_name(false, true);
1037 $category->name = get_string('defaultfor', 'question', $contextname);
1038 $category->info = get_string('defaultinfofor', 'question', $contextname);
1039 $category->contextid = $context->id;
1040 $category->parent = 0;
1041 // By default, all categories get this number, and are sorted alphabetically.
1042 $category->sortorder = 999;
1043 $category->stamp = make_unique_id_code();
1044 $category->id = $DB->insert_record('question_categories', $category);
1045 } else {
1046 $category = question_get_default_category($context->id);
1048 $thispreferredness = $preferredlevels[$context->contextlevel];
1049 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1050 $thispreferredness += 10;
1052 if ($thispreferredness > $preferredness) {
1053 $toreturn = $category;
1054 $preferredness = $thispreferredness;
1058 if (!is_null($toreturn)) {
1059 $toreturn = clone($toreturn);
1061 return $toreturn;
1065 * Get all the category objects, including a count of the number of questions in that category,
1066 * for all the categories in the lists $contexts.
1068 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1069 * @param string $sortorder used as the ORDER BY clause in the select statement.
1070 * @return array of category objects.
1072 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1073 global $DB;
1074 return $DB->get_records_sql("
1075 SELECT c.*, (SELECT count(1) FROM {question} q
1076 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1077 FROM {question_categories} c
1078 WHERE c.contextid IN ($contexts)
1079 ORDER BY $sortorder");
1083 * Output an array of question categories.
1085 function question_category_options($contexts, $top = false, $currentcat = 0,
1086 $popupform = false, $nochildrenof = -1) {
1087 global $CFG;
1088 $pcontexts = array();
1089 foreach ($contexts as $context) {
1090 $pcontexts[] = $context->id;
1092 $contextslist = join($pcontexts, ', ');
1094 $categories = get_categories_for_contexts($contextslist);
1096 $categories = question_add_context_in_key($categories);
1098 if ($top) {
1099 $categories = question_add_tops($categories, $pcontexts);
1101 $categories = add_indented_names($categories, $nochildrenof);
1103 // sort cats out into different contexts
1104 $categoriesarray = array();
1105 foreach ($pcontexts as $contextid) {
1106 $context = context::instance_by_id($contextid);
1107 $contextstring = $context->get_context_name(true, true);
1108 foreach ($categories as $category) {
1109 if ($category->contextid == $contextid) {
1110 $cid = $category->id;
1111 if ($currentcat != $cid || $currentcat == 0) {
1112 $countstring = !empty($category->questioncount) ?
1113 " ($category->questioncount)" : '';
1114 $categoriesarray[$contextstring][$cid] =
1115 format_string($category->indentedname, true,
1116 array('context' => $context)) . $countstring;
1121 if ($popupform) {
1122 $popupcats = array();
1123 foreach ($categoriesarray as $contextstring => $optgroup) {
1124 $group = array();
1125 foreach ($optgroup as $key => $value) {
1126 $key = str_replace($CFG->wwwroot, '', $key);
1127 $group[$key] = $value;
1129 $popupcats[] = array($contextstring => $group);
1131 return $popupcats;
1132 } else {
1133 return $categoriesarray;
1137 function question_add_context_in_key($categories) {
1138 $newcatarray = array();
1139 foreach ($categories as $id => $category) {
1140 $category->parent = "$category->parent,$category->contextid";
1141 $category->id = "$category->id,$category->contextid";
1142 $newcatarray["$id,$category->contextid"] = $category;
1144 return $newcatarray;
1147 function question_add_tops($categories, $pcontexts) {
1148 $topcats = array();
1149 foreach ($pcontexts as $context) {
1150 $newcat = new stdClass();
1151 $newcat->id = "0,$context";
1152 $newcat->name = get_string('top');
1153 $newcat->parent = -1;
1154 $newcat->contextid = $context;
1155 $topcats["0,$context"] = $newcat;
1157 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1158 return array_merge($topcats, $categories);
1162 * @return array of question category ids of the category and all subcategories.
1164 function question_categorylist($categoryid) {
1165 global $DB;
1167 // final list of category IDs
1168 $categorylist = array();
1170 // a list of category IDs to check for any sub-categories
1171 $subcategories = array($categoryid);
1173 while ($subcategories) {
1174 foreach ($subcategories as $subcategory) {
1175 // if anything from the temporary list was added already, then we have a loop
1176 if (isset($categorylist[$subcategory])) {
1177 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1179 $categorylist[$subcategory] = $subcategory;
1182 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1184 $subcategories = $DB->get_records_select_menu('question_categories',
1185 "parent $in", $params, NULL, 'id,id AS id2');
1188 return $categorylist;
1191 //===========================
1192 // Import/Export Functions
1193 //===========================
1196 * Get list of available import or export formats
1197 * @param string $type 'import' if import list, otherwise export list assumed
1198 * @return array sorted list of import/export formats available
1200 function get_import_export_formats($type) {
1201 global $CFG;
1202 require_once($CFG->dirroot . '/question/format.php');
1204 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1206 $fileformatname = array();
1207 foreach ($formatclasses as $component => $formatclass) {
1209 $format = new $formatclass();
1210 if ($type == 'import') {
1211 $provided = $format->provide_import();
1212 } else {
1213 $provided = $format->provide_export();
1216 if ($provided) {
1217 list($notused, $fileformat) = explode('_', $component, 2);
1218 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1222 core_collator::asort($fileformatnames);
1223 return $fileformatnames;
1228 * Create a reasonable default file name for exporting questions from a particular
1229 * category.
1230 * @param object $course the course the questions are in.
1231 * @param object $category the question category.
1232 * @return string the filename.
1234 function question_default_export_filename($course, $category) {
1235 // We build a string that is an appropriate name (questions) from the lang pack,
1236 // then the corse shortname, then the question category name, then a timestamp.
1238 $base = clean_filename(get_string('exportfilename', 'question'));
1240 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1241 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1243 $shortname = clean_filename($course->shortname);
1244 if ($shortname == '' || $shortname == '_' ) {
1245 $shortname = $course->id;
1248 $categoryname = clean_filename(format_string($category->name));
1250 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1252 return $export_name;
1256 * Converts contextlevels to strings and back to help with reading/writing contexts
1257 * to/from import/export files.
1259 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1260 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1262 class context_to_string_translator{
1264 * @var array used to translate between contextids and strings for this context.
1266 protected $contexttostringarray = array();
1268 public function __construct($contexts) {
1269 $this->generate_context_to_string_array($contexts);
1272 public function context_to_string($contextid) {
1273 return $this->contexttostringarray[$contextid];
1276 public function string_to_context($contextname) {
1277 $contextid = array_search($contextname, $this->contexttostringarray);
1278 return $contextid;
1281 protected function generate_context_to_string_array($contexts) {
1282 if (!$this->contexttostringarray) {
1283 $catno = 1;
1284 foreach ($contexts as $context) {
1285 switch ($context->contextlevel) {
1286 case CONTEXT_MODULE :
1287 $contextstring = 'module';
1288 break;
1289 case CONTEXT_COURSE :
1290 $contextstring = 'course';
1291 break;
1292 case CONTEXT_COURSECAT :
1293 $contextstring = "cat$catno";
1294 $catno++;
1295 break;
1296 case CONTEXT_SYSTEM :
1297 $contextstring = 'system';
1298 break;
1300 $this->contexttostringarray[$context->id] = $contextstring;
1308 * Check capability on category
1310 * @param mixed $question object or id
1311 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1312 * @param integer $cachecat useful to cache all question records in a category
1313 * @return boolean this user has the capability $cap for this question $question?
1315 function question_has_capability_on($question, $cap, $cachecat = -1) {
1316 global $USER, $DB;
1318 // these are capabilities on existing questions capabilties are
1319 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1320 $question_questioncaps = array('edit', 'view', 'use', 'move');
1321 static $questions = array();
1322 static $categories = array();
1323 static $cachedcat = array();
1324 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1325 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1326 $cachedcat[] = $cachecat;
1328 if (!is_object($question)) {
1329 if (!isset($questions[$question])) {
1330 if (!$questions[$question] = $DB->get_record('question',
1331 array('id' => $question), 'id,category,createdby')) {
1332 print_error('questiondoesnotexist', 'question');
1335 $question = $questions[$question];
1337 if (empty($question->category)) {
1338 // This can happen when we have created a fake 'missingtype' question to
1339 // take the place of a deleted question.
1340 return false;
1342 if (!isset($categories[$question->category])) {
1343 if (!$categories[$question->category] = $DB->get_record('question_categories',
1344 array('id'=>$question->category))) {
1345 print_error('invalidcategory', 'question');
1348 $category = $categories[$question->category];
1349 $context = context::instance_by_id($category->contextid);
1351 if (array_search($cap, $question_questioncaps)!== false) {
1352 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1353 if ($question->createdby == $USER->id) {
1354 return has_capability('moodle/question:' . $cap . 'mine', $context);
1355 } else {
1356 return false;
1358 } else {
1359 return true;
1361 } else {
1362 return has_capability('moodle/question:' . $cap, $context);
1368 * Require capability on question.
1370 function question_require_capability_on($question, $cap) {
1371 if (!question_has_capability_on($question, $cap)) {
1372 print_error('nopermissions', '', '', $cap);
1374 return true;
1378 * @param object $context a context
1379 * @return string A URL for editing questions in this context.
1381 function question_edit_url($context) {
1382 global $CFG, $SITE;
1383 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1384 return false;
1386 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1387 $defaultcategory = question_get_default_category($context->id);
1388 if ($defaultcategory) {
1389 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1391 switch ($context->contextlevel) {
1392 case CONTEXT_SYSTEM:
1393 return $baseurl . 'courseid=' . $SITE->id;
1394 case CONTEXT_COURSECAT:
1395 // This is nasty, becuase we can only edit questions in a course
1396 // context at the moment, so for now we just return false.
1397 return false;
1398 case CONTEXT_COURSE:
1399 return $baseurl . 'courseid=' . $context->instanceid;
1400 case CONTEXT_MODULE:
1401 return $baseurl . 'cmid=' . $context->instanceid;
1407 * Adds question bank setting links to the given navigation node if caps are met.
1409 * @param navigation_node $navigationnode The navigation node to add the question branch to
1410 * @param object $context
1411 * @return navigation_node Returns the question branch that was added
1413 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1414 global $PAGE;
1416 if ($context->contextlevel == CONTEXT_COURSE) {
1417 $params = array('courseid'=>$context->instanceid);
1418 } else if ($context->contextlevel == CONTEXT_MODULE) {
1419 $params = array('cmid'=>$context->instanceid);
1420 } else {
1421 return;
1424 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1425 $params['cat'] = $cat;
1428 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1429 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1431 $contexts = new question_edit_contexts($context);
1432 if ($contexts->have_one_edit_tab_cap('questions')) {
1433 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1434 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1436 if ($contexts->have_one_edit_tab_cap('categories')) {
1437 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1438 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1440 if ($contexts->have_one_edit_tab_cap('import')) {
1441 $questionnode->add(get_string('import', 'question'), new moodle_url(
1442 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1444 if ($contexts->have_one_edit_tab_cap('export')) {
1445 $questionnode->add(get_string('export', 'question'), new moodle_url(
1446 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1449 return $questionnode;
1453 * @return array all the capabilities that relate to accessing particular questions.
1455 function question_get_question_capabilities() {
1456 return array(
1457 'moodle/question:add',
1458 'moodle/question:editmine',
1459 'moodle/question:editall',
1460 'moodle/question:viewmine',
1461 'moodle/question:viewall',
1462 'moodle/question:usemine',
1463 'moodle/question:useall',
1464 'moodle/question:movemine',
1465 'moodle/question:moveall',
1470 * @return array all the question bank capabilities.
1472 function question_get_all_capabilities() {
1473 $caps = question_get_question_capabilities();
1474 $caps[] = 'moodle/question:managecategory';
1475 $caps[] = 'moodle/question:flag';
1476 return $caps;
1481 * Tracks all the contexts related to the one where we are currently editing
1482 * questions, and provides helper methods to check permissions.
1484 * @copyright 2007 Jamie Pratt me@jamiep.org
1485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1487 class question_edit_contexts {
1489 public static $caps = array(
1490 'editq' => array('moodle/question:add',
1491 'moodle/question:editmine',
1492 'moodle/question:editall',
1493 'moodle/question:viewmine',
1494 'moodle/question:viewall',
1495 'moodle/question:usemine',
1496 'moodle/question:useall',
1497 'moodle/question:movemine',
1498 'moodle/question:moveall'),
1499 'questions'=>array('moodle/question:add',
1500 'moodle/question:editmine',
1501 'moodle/question:editall',
1502 'moodle/question:viewmine',
1503 'moodle/question:viewall',
1504 'moodle/question:movemine',
1505 'moodle/question:moveall'),
1506 'categories'=>array('moodle/question:managecategory'),
1507 'import'=>array('moodle/question:add'),
1508 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1510 protected $allcontexts;
1513 * Constructor
1514 * @param context the current context.
1516 public function __construct(context $thiscontext) {
1517 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1521 * @return array all parent contexts
1523 public function all() {
1524 return $this->allcontexts;
1528 * @return object lowest context which must be either the module or course context
1530 public function lowest() {
1531 return $this->allcontexts[0];
1535 * @param string $cap capability
1536 * @return array parent contexts having capability, zero based index
1538 public function having_cap($cap) {
1539 $contextswithcap = array();
1540 foreach ($this->allcontexts as $context) {
1541 if (has_capability($cap, $context)) {
1542 $contextswithcap[] = $context;
1545 return $contextswithcap;
1549 * @param array $caps capabilities
1550 * @return array parent contexts having at least one of $caps, zero based index
1552 public function having_one_cap($caps) {
1553 $contextswithacap = array();
1554 foreach ($this->allcontexts as $context) {
1555 foreach ($caps as $cap) {
1556 if (has_capability($cap, $context)) {
1557 $contextswithacap[] = $context;
1558 break; //done with caps loop
1562 return $contextswithacap;
1566 * @param string $tabname edit tab name
1567 * @return array parent contexts having at least one of $caps, zero based index
1569 public function having_one_edit_tab_cap($tabname) {
1570 return $this->having_one_cap(self::$caps[$tabname]);
1574 * @return those contexts where a user can add a question and then use it.
1576 public function having_add_and_use() {
1577 $contextswithcap = array();
1578 foreach ($this->allcontexts as $context) {
1579 if (!has_capability('moodle/question:add', $context)) {
1580 continue;
1582 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1583 continue;
1585 $contextswithcap[] = $context;
1587 return $contextswithcap;
1591 * Has at least one parent context got the cap $cap?
1593 * @param string $cap capability
1594 * @return boolean
1596 public function have_cap($cap) {
1597 return (count($this->having_cap($cap)));
1601 * Has at least one parent context got one of the caps $caps?
1603 * @param array $caps capability
1604 * @return boolean
1606 public function have_one_cap($caps) {
1607 foreach ($caps as $cap) {
1608 if ($this->have_cap($cap)) {
1609 return true;
1612 return false;
1616 * Has at least one parent context got one of the caps for actions on $tabname
1618 * @param string $tabname edit tab name
1619 * @return boolean
1621 public function have_one_edit_tab_cap($tabname) {
1622 return $this->have_one_cap(self::$caps[$tabname]);
1626 * Throw error if at least one parent context hasn't got the cap $cap
1628 * @param string $cap capability
1630 public function require_cap($cap) {
1631 if (!$this->have_cap($cap)) {
1632 print_error('nopermissions', '', '', $cap);
1637 * Throw error if at least one parent context hasn't got one of the caps $caps
1639 * @param array $cap capabilities
1641 public function require_one_cap($caps) {
1642 if (!$this->have_one_cap($caps)) {
1643 $capsstring = join($caps, ', ');
1644 print_error('nopermissions', '', '', $capsstring);
1649 * Throw error if at least one parent context hasn't got one of the caps $caps
1651 * @param string $tabname edit tab name
1653 public function require_one_edit_tab_cap($tabname) {
1654 if (!$this->have_one_edit_tab_cap($tabname)) {
1655 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1662 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1664 * @package core_question
1665 * @category files
1666 * @param string $text text being processed
1667 * @param string $file the php script used to serve files
1668 * @param int $contextid context ID
1669 * @param string $component component
1670 * @param string $filearea filearea
1671 * @param array $ids other IDs will be used to check file permission
1672 * @param int $itemid item ID
1673 * @param array $options options
1674 * @return string
1676 function question_rewrite_question_urls($text, $file, $contextid, $component,
1677 $filearea, array $ids, $itemid, array $options=null) {
1679 $idsstr = '';
1680 if (!empty($ids)) {
1681 $idsstr .= implode('/', $ids);
1683 if ($itemid !== null) {
1684 $idsstr .= '/' . $itemid;
1686 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1687 $filearea, $idsstr, $options);
1691 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1692 * viewing the question outside an attempt (for example, in the question bank
1693 * listing or in the quiz statistics report).
1695 * @param string $text the question text.
1696 * @param int $questionid the question id.
1697 * @param int $filecontextid the context id of the question being displayed.
1698 * @param string $filecomponent the component that owns the file area.
1699 * @param string $filearea the file area name.
1700 * @param int|null $itemid the file's itemid
1701 * @param int $previewcontextid the context id where the preview is being displayed.
1702 * @param string $previewcomponent component responsible for displaying the preview.
1703 * @param array $options text and file options ('forcehttps'=>false)
1704 * @return string $questiontext with URLs rewritten.
1706 function question_rewrite_question_preview_urls($text, $questionid,
1707 $filecontextid, $filecomponent, $filearea, $itemid,
1708 $previewcontextid, $previewcomponent, $options = null) {
1710 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1711 if ($itemid) {
1712 $path .= '/' . $itemid;
1715 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1716 $filecomponent, $filearea, $path, $options);
1720 * Called by pluginfile.php to serve files related to the 'question' core
1721 * component and for files belonging to qtypes.
1723 * For files that relate to questions in a question_attempt, then we delegate to
1724 * a function in the component that owns the attempt (for example in the quiz,
1725 * or in core question preview) to get necessary inforation.
1727 * (Note that, at the moment, all question file areas relate to questions in
1728 * attempts, so the If at the start of the last paragraph is always true.)
1730 * Does not return, either calls send_file_not_found(); or serves the file.
1732 * @package core_question
1733 * @category files
1734 * @param stdClass $course course settings object
1735 * @param stdClass $context context object
1736 * @param string $component the name of the component we are serving files for.
1737 * @param string $filearea the name of the file area.
1738 * @param array $args the remaining bits of the file path.
1739 * @param bool $forcedownload whether the user must be forced to download the file.
1740 * @param array $options additional options affecting the file serving
1742 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1743 global $DB, $CFG;
1745 // Special case, sending a question bank export.
1746 if ($filearea === 'export') {
1747 list($context, $course, $cm) = get_context_info_array($context->id);
1748 require_login($course, false, $cm);
1750 require_once($CFG->dirroot . '/question/editlib.php');
1751 $contexts = new question_edit_contexts($context);
1752 // check export capability
1753 $contexts->require_one_edit_tab_cap('export');
1754 $category_id = (int)array_shift($args);
1755 $format = array_shift($args);
1756 $cattofile = array_shift($args);
1757 $contexttofile = array_shift($args);
1758 $filename = array_shift($args);
1760 // load parent class for import/export
1761 require_once($CFG->dirroot . '/question/format.php');
1762 require_once($CFG->dirroot . '/question/editlib.php');
1763 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1765 $classname = 'qformat_' . $format;
1766 if (!class_exists($classname)) {
1767 send_file_not_found();
1770 $qformat = new $classname();
1772 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1773 send_file_not_found();
1776 $qformat->setCategory($category);
1777 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1778 $qformat->setCourse($course);
1780 if ($cattofile == 'withcategories') {
1781 $qformat->setCattofile(true);
1782 } else {
1783 $qformat->setCattofile(false);
1786 if ($contexttofile == 'withcontexts') {
1787 $qformat->setContexttofile(true);
1788 } else {
1789 $qformat->setContexttofile(false);
1792 if (!$qformat->exportpreprocess()) {
1793 send_file_not_found();
1794 print_error('exporterror', 'question', $thispageurl->out());
1797 // export data to moodle file pool
1798 if (!$content = $qformat->exportprocess(true)) {
1799 send_file_not_found();
1802 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1805 // Normal case, a file belonging to a question.
1806 $qubaidorpreview = array_shift($args);
1808 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1809 if ($qubaidorpreview === 'preview') {
1810 $previewcontextid = (int)array_shift($args);
1811 $previewcomponent = array_shift($args);
1812 $questionid = (int) array_shift($args);
1813 $previewcontext = context_helper::instance_by_id($previewcontextid);
1815 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1816 $previewcontext, $questionid,
1817 $context, $component, $filearea, $args,
1818 $forcedownload, $options), 'callbackmissing');
1820 if ($result === 'callbackmissing') {
1821 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1822 "{$previewcomponent}_question_preview_pluginfile callback. " .
1823 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
1826 send_file_not_found();
1829 // 2. A question being attempted in the normal way.
1830 $qubaid = (int)$qubaidorpreview;
1831 $slot = (int)array_shift($args);
1833 $module = $DB->get_field('question_usages', 'component',
1834 array('id' => $qubaid));
1835 if (!$module) {
1836 send_file_not_found();
1839 if ($module === 'core_question_preview') {
1840 require_once($CFG->dirroot . '/question/previewlib.php');
1841 return question_preview_question_pluginfile($course, $context,
1842 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1844 } else {
1845 $dir = core_component::get_component_directory($module);
1846 if (!file_exists("$dir/lib.php")) {
1847 send_file_not_found();
1849 include_once("$dir/lib.php");
1851 $filefunction = $module . '_question_pluginfile';
1852 if (function_exists($filefunction)) {
1853 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1854 $args, $forcedownload, $options);
1857 // Okay, we're here so lets check for function without 'mod_'.
1858 if (strpos($module, 'mod_') === 0) {
1859 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1860 if (function_exists($filefunctionold)) {
1861 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1862 $args, $forcedownload, $options);
1866 send_file_not_found();
1871 * Serve questiontext files in the question text when they are displayed in this report.
1873 * @package core_files
1874 * @category files
1875 * @param context $previewcontext the context in which the preview is happening.
1876 * @param int $questionid the question id.
1877 * @param context $filecontext the file (question) context.
1878 * @param string $filecomponent the component the file belongs to.
1879 * @param string $filearea the file area.
1880 * @param array $args remaining file args.
1881 * @param bool $forcedownload.
1882 * @param array $options additional options affecting the file serving.
1884 function core_question_question_preview_pluginfile($previewcontext, $questionid,
1885 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
1886 global $DB;
1888 // Verify that contextid matches the question.
1889 $question = $DB->get_record_sql('
1890 SELECT q.*, qc.contextid
1891 FROM {question} q
1892 JOIN {question_categories} qc ON qc.id = q.category
1893 WHERE q.id = :id AND qc.contextid = :contextid',
1894 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
1896 // Check the capability.
1897 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
1898 require_login($course, false, $cm);
1900 question_require_capability_on($question, 'use');
1902 $fs = get_file_storage();
1903 $relativepath = implode('/', $args);
1904 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1905 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1906 send_file_not_found();
1909 send_stored_file($file, 0, 0, $forcedownload, $options);
1913 * Create url for question export
1915 * @param int $contextid, current context
1916 * @param int $categoryid, categoryid
1917 * @param string $format
1918 * @param string $withcategories
1919 * @param string $ithcontexts
1920 * @param moodle_url export file url
1922 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1923 $withcontexts, $filename) {
1924 global $CFG;
1925 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1926 return moodle_url::make_file_url($urlbase,
1927 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1928 "/{$withcontexts}/{$filename}", true);
1932 * Return a list of page types
1933 * @param string $pagetype current page type
1934 * @param stdClass $parentcontext Block's parent context
1935 * @param stdClass $currentcontext Current context of block
1937 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1938 global $CFG;
1939 $types = array(
1940 'question-*'=>get_string('page-question-x', 'question'),
1941 'question-edit'=>get_string('page-question-edit', 'question'),
1942 'question-category'=>get_string('page-question-category', 'question'),
1943 'question-export'=>get_string('page-question-export', 'question'),
1944 'question-import'=>get_string('page-question-import', 'question')
1946 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1947 require_once($CFG->dirroot . '/course/lib.php');
1948 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1949 } else {
1950 return $types;
1955 * Does an activity module use the question bank?
1957 * @param string $modname The name of the module (without mod_ prefix).
1958 * @return bool true if the module uses questions.
1960 function question_module_uses_questions($modname) {
1961 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
1962 return true;
1965 $component = 'mod_'.$modname;
1966 if (component_callback_exists($component, 'question_pluginfile')) {
1967 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
1968 return true;
1971 return false;