Merge branch 'wip-MDL-44686-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / questionlib.php
blob21bdeb3f5cafc2172f7094260729020635208b81
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 * Returns an array of names of activity modules that use this question
120 * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
122 * @param object $questionid
123 * @return array of strings
125 function question_list_instances($questionid) {
126 throw new coding_exception('question_list_instances has been deprectated. ' .
127 'Please use questions_in_use instead.');
131 * @param array $questionids of question ids.
132 * @return boolean whether any of these questions are being used by any part of Moodle.
134 function questions_in_use($questionids) {
135 global $CFG;
137 if (question_engine::questions_in_use($questionids)) {
138 return true;
141 foreach (core_component::get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
144 include_once($lib);
146 $fn = $module . '_questions_in_use';
147 if (function_exists($fn)) {
148 if ($fn($questionids)) {
149 return true;
151 } else {
153 // Fallback for legacy modules.
154 $fn = $module . '_question_list_instances';
155 if (function_exists($fn)) {
156 foreach ($questionids as $questionid) {
157 $instances = $fn($questionid);
158 if (!empty($instances)) {
159 return true;
167 return false;
171 * Determine whether there arey any questions belonging to this context, that is whether any of its
172 * question categories contain any questions. This will return true even if all the questions are
173 * hidden.
175 * @param mixed $context either a context object, or a context id.
176 * @return boolean whether any of the question categories beloning to this context have
177 * any questions in them.
179 function question_context_has_any_questions($context) {
180 global $DB;
181 if (is_object($context)) {
182 $contextid = $context->id;
183 } else if (is_numeric($context)) {
184 $contextid = $context;
185 } else {
186 print_error('invalidcontextinhasanyquestions', 'question');
188 return $DB->record_exists_sql("SELECT *
189 FROM {question} q
190 JOIN {question_categories} qc ON qc.id = q.category
191 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
195 * Returns list of 'allowed' grades for grade selection
196 * formatted suitably for dropdown box function
198 * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
199 * {@link question_bank::fraction_options_full()} instead.
201 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
203 function get_grade_options() {
204 $grades = new stdClass();
205 $grades->gradeoptions = question_bank::fraction_options();
206 $grades->gradeoptionsfull = question_bank::fraction_options_full();
208 return $grades;
212 * Check whether a given grade is one of a list of allowed options. If not,
213 * depending on $matchgrades, either return the nearest match, or return false
214 * to signal an error.
215 * @param array $gradeoptionsfull list of valid options
216 * @param int $grade grade to be tested
217 * @param string $matchgrades 'error' or 'nearest'
218 * @return mixed either 'fixed' value or false if error.
220 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
222 if ($matchgrades == 'error') {
223 // (Almost) exact match, or an error.
224 foreach ($gradeoptionsfull as $value => $option) {
225 // Slightly fuzzy test, never check floats for equality.
226 if (abs($grade - $value) < 0.00001) {
227 return $value; // Be sure the return the proper value.
230 // Didn't find a match so that's an error.
231 return false;
233 } else if ($matchgrades == 'nearest') {
234 // Work out nearest value
235 $best = false;
236 $bestmismatch = 2;
237 foreach ($gradeoptionsfull as $value => $option) {
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
240 $best = $value;
241 $bestmismatch = $newmismatch;
244 return $best;
246 } else {
247 // Unknow option passed.
248 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
249 ' passed to match_grade_options');
254 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
255 * @param integer $categoryid a question category id.
256 * @param boolean $recursive whether to check child categories too.
257 * @return boolean whether any question in this category is in use.
259 function question_category_isused($categoryid, $recursive = false) {
260 throw new coding_exception('question_category_isused has been deprectated. ' .
261 'Please use question_category_in_use instead.');
265 * Tests whether any question in a category is used by any part of Moodle.
267 * @param integer $categoryid a question category id.
268 * @param boolean $recursive whether to check child categories too.
269 * @return boolean whether any question in this category is in use.
271 function question_category_in_use($categoryid, $recursive = false) {
272 global $DB;
274 //Look at each question in the category
275 if ($questions = $DB->get_records_menu('question',
276 array('category' => $categoryid), '', 'id, 1')) {
277 if (questions_in_use(array_keys($questions))) {
278 return true;
281 if (!$recursive) {
282 return false;
285 //Look under child categories recursively
286 if ($children = $DB->get_records('question_categories',
287 array('parent' => $categoryid), '', 'id, 1')) {
288 foreach ($children as $child) {
289 if (question_category_in_use($child->id, $recursive)) {
290 return true;
295 return false;
299 * Deletes question and all associated data from the database
301 * It will not delete a question if it is used by an activity module
302 * @param object $question The question being deleted
304 function question_delete_question($questionid) {
305 global $DB;
307 $question = $DB->get_record_sql('
308 SELECT q.*, qc.contextid
309 FROM {question} q
310 JOIN {question_categories} qc ON qc.id = q.category
311 WHERE q.id = ?', array($questionid));
312 if (!$question) {
313 // In some situations, for example if this was a child of a
314 // Cloze question that was previously deleted, the question may already
315 // have gone. In this case, just do nothing.
316 return;
319 // Do not delete a question if it is used by an activity module
320 if (questions_in_use(array($questionid))) {
321 return;
324 // Check permissions.
325 question_require_capability_on($question, 'edit');
327 $dm = new question_engine_data_mapper();
328 $dm->delete_previews($questionid);
330 // delete questiontype-specific data
331 question_bank::get_qtype($question->qtype, false)->delete_question(
332 $questionid, $question->contextid);
334 // Delete all tag instances.
335 $DB->delete_records('tag_instance', array('component' => 'core_question', 'itemid' => $question->id));
337 // Now recursively delete all child questions
338 if ($children = $DB->get_records('question',
339 array('parent' => $questionid), '', 'id, qtype')) {
340 foreach ($children as $child) {
341 if ($child->id != $questionid) {
342 question_delete_question($child->id);
347 // Finally delete the question record itself
348 $DB->delete_records('question', array('id' => $questionid));
349 question_bank::notify_question_edited($questionid);
353 * All question categories and their questions are deleted for this course.
355 * @param stdClass $course an object representing the activity
356 * @param boolean $feedback to specify if the process must output a summary of its work
357 * @return boolean
359 function question_delete_course($course, $feedback=true) {
360 global $DB, $OUTPUT;
362 //To store feedback to be showed at the end of the process
363 $feedbackdata = array();
365 //Cache some strings
366 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
367 $coursecontext = context_course::instance($course->id);
368 $categoriescourse = $DB->get_records('question_categories',
369 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
371 if ($categoriescourse) {
373 //Sort categories following their tree (parent-child) relationships
374 //this will make the feedback more readable
375 $categoriescourse = sort_categories_by_tree($categoriescourse);
377 foreach ($categoriescourse as $category) {
379 //Delete it completely (questions and category itself)
380 //deleting questions
381 if ($questions = $DB->get_records('question',
382 array('category' => $category->id), '', 'id,qtype')) {
383 foreach ($questions as $question) {
384 question_delete_question($question->id);
386 $DB->delete_records("question", array("category" => $category->id));
388 //delete the category
389 $DB->delete_records('question_categories', array('id' => $category->id));
391 //Fill feedback
392 $feedbackdata[] = array($category->name, $strcatdeleted);
394 //Inform about changes performed if feedback is enabled
395 if ($feedback) {
396 $table = new html_table();
397 $table->head = array(get_string('category', 'quiz'), get_string('action'));
398 $table->data = $feedbackdata;
399 echo html_writer::table($table);
402 return true;
406 * Category is about to be deleted,
407 * 1/ All question categories and their questions are deleted for this course category.
408 * 2/ All questions are moved to new category
410 * @param object|coursecat $category course category object
411 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
412 * category where content moved
413 * @param boolean $feedback to specify if the process must output a summary of its work
414 * @return boolean
416 function question_delete_course_category($category, $newcategory, $feedback=true) {
417 global $DB, $OUTPUT;
419 $context = context_coursecat::instance($category->id);
420 if (empty($newcategory)) {
421 $feedbackdata = array(); // To store feedback to be showed at the end of the process
422 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
423 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
425 // Loop over question categories.
426 if ($categories = $DB->get_records('question_categories',
427 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
428 foreach ($categories as $category) {
430 // Deal with any questions in the category.
431 if ($questions = $DB->get_records('question',
432 array('category' => $category->id), '', 'id,qtype')) {
434 // Try to delete each question.
435 foreach ($questions as $question) {
436 question_delete_question($question->id);
439 // Check to see if there were any questions that were kept because
440 // they are still in use somehow, even though quizzes in courses
441 // in this category will already have been deleted. This could
442 // happen, for example, if questions are added to a course,
443 // and then that course is moved to another category (MDL-14802).
444 $questionids = $DB->get_records_menu('question',
445 array('category'=>$category->id), '', 'id, 1');
446 if (!empty($questionids)) {
447 $parentcontextid = false;
448 $parentcontext = $context->get_parent_context();
449 if ($parentcontext) {
450 $parentcontextid = $parentcontext->id;
452 if (!$rescueqcategory = question_save_from_deletion(
453 array_keys($questionids), $parentcontextid,
454 $context->get_context_name(), $rescueqcategory)) {
455 return false;
457 $feedbackdata[] = array($category->name,
458 get_string('questionsmovedto', 'question', $rescueqcategory->name));
462 // Now delete the category.
463 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
464 return false;
466 $feedbackdata[] = array($category->name, $strcatdeleted);
468 } // End loop over categories.
471 // Output feedback if requested.
472 if ($feedback and $feedbackdata) {
473 $table = new html_table();
474 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
475 $table->data = $feedbackdata;
476 echo html_writer::table($table);
479 } else {
480 // Move question categories to the new context.
481 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
482 return false;
485 // Update the contextid for any tag instances for questions in the old context.
486 $DB->set_field('tag_instance', 'contextid', $newcontext->id, array('component' => 'core_question',
487 'contextid' => $context->id));
489 $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid' => $context->id));
491 if ($feedback) {
492 $a = new stdClass();
493 $a->oldplace = $context->get_context_name();
494 $a->newplace = $newcontext->get_context_name();
495 echo $OUTPUT->notification(
496 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
500 return true;
504 * Enter description here...
506 * @param array $questionids of question ids
507 * @param object $newcontext the context to create the saved category in.
508 * @param string $oldplace a textual description of the think being deleted,
509 * e.g. from get_context_name
510 * @param object $newcategory
511 * @return mixed false on
513 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
514 $newcategory = null) {
515 global $DB;
517 // Make a category in the parent context to move the questions to.
518 if (is_null($newcategory)) {
519 $newcategory = new stdClass();
520 $newcategory->parent = 0;
521 $newcategory->contextid = $newcontextid;
522 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
523 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
524 $newcategory->sortorder = 999;
525 $newcategory->stamp = make_unique_id_code();
526 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
529 // Move any remaining questions to the 'saved' category.
530 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
531 return false;
533 return $newcategory;
537 * All question categories and their questions are deleted for this activity.
539 * @param object $cm the course module object representing the activity
540 * @param boolean $feedback to specify if the process must output a summary of its work
541 * @return boolean
543 function question_delete_activity($cm, $feedback=true) {
544 global $DB, $OUTPUT;
546 //To store feedback to be showed at the end of the process
547 $feedbackdata = array();
549 //Cache some strings
550 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
551 $modcontext = context_module::instance($cm->id);
552 if ($categoriesmods = $DB->get_records('question_categories',
553 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
554 //Sort categories following their tree (parent-child) relationships
555 //this will make the feedback more readable
556 $categoriesmods = sort_categories_by_tree($categoriesmods);
558 foreach ($categoriesmods as $category) {
560 //Delete it completely (questions and category itself)
561 //deleting questions
562 if ($questions = $DB->get_records('question',
563 array('category' => $category->id), '', 'id,qtype')) {
564 foreach ($questions as $question) {
565 question_delete_question($question->id);
567 $DB->delete_records("question", array("category"=>$category->id));
569 //delete the category
570 $DB->delete_records('question_categories', array('id'=>$category->id));
572 //Fill feedback
573 $feedbackdata[] = array($category->name, $strcatdeleted);
575 //Inform about changes performed if feedback is enabled
576 if ($feedback) {
577 $table = new html_table();
578 $table->head = array(get_string('category', 'quiz'), get_string('action'));
579 $table->data = $feedbackdata;
580 echo html_writer::table($table);
583 return true;
587 * This function should be considered private to the question bank, it is called from
588 * question/editlib.php question/contextmoveq.php and a few similar places to to the
589 * work of acutally moving questions and associated data. However, callers of this
590 * function also have to do other work, which is why you should not call this method
591 * directly from outside the questionbank.
593 * @param array $questionids of question ids.
594 * @param integer $newcategoryid the id of the category to move to.
596 function question_move_questions_to_category($questionids, $newcategoryid) {
597 global $DB;
599 $newcontextid = $DB->get_field('question_categories', 'contextid',
600 array('id' => $newcategoryid));
601 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
602 $questions = $DB->get_records_sql("
603 SELECT q.id, q.qtype, qc.contextid
604 FROM {question} q
605 JOIN {question_categories} qc ON q.category = qc.id
606 WHERE q.id $questionidcondition", $params);
607 foreach ($questions as $question) {
608 if ($newcontextid != $question->contextid) {
609 question_bank::get_qtype($question->qtype)->move_files(
610 $question->id, $question->contextid, $newcontextid);
614 // Move the questions themselves.
615 $DB->set_field_select('question', 'category', $newcategoryid,
616 "id $questionidcondition", $params);
618 // Move any subquestions belonging to them.
619 $DB->set_field_select('question', 'category', $newcategoryid,
620 "parent $questionidcondition", $params);
622 // Update the contextid for any tag instances that may exist for these questions.
623 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
624 "component = 'core_question' AND itemid $questionidcondition", $params);
626 // TODO Deal with datasets.
628 // Purge these questions from the cache.
629 foreach ($questions as $question) {
630 question_bank::notify_question_edited($question->id);
633 return true;
637 * This function helps move a question cateogry to a new context by moving all
638 * the files belonging to all the questions to the new context.
639 * Also moves subcategories.
640 * @param integer $categoryid the id of the category being moved.
641 * @param integer $oldcontextid the old context id.
642 * @param integer $newcontextid the new context id.
644 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
645 global $DB;
647 $questionids = $DB->get_records_menu('question',
648 array('category' => $categoryid), '', 'id,qtype');
649 foreach ($questionids as $questionid => $qtype) {
650 question_bank::get_qtype($qtype)->move_files(
651 $questionid, $oldcontextid, $newcontextid);
652 // Purge this question from the cache.
653 question_bank::notify_question_edited($questionid);
656 if ($questionids) {
657 // Update the contextid for any tag instances that may exist for these questions.
658 list($questionids, $params) = $DB->get_in_or_equal(array_keys($questionids));
659 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
660 "component = 'core_question' AND itemid $questionids", $params);
663 $subcatids = $DB->get_records_menu('question_categories',
664 array('parent' => $categoryid), '', 'id,1');
665 foreach ($subcatids as $subcatid => $notused) {
666 $DB->set_field('question_categories', 'contextid', $newcontextid,
667 array('id' => $subcatid));
668 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
673 * Generate the URL for starting a new preview of a given question with the given options.
674 * @param integer $questionid the question to preview.
675 * @param string $preferredbehaviour the behaviour to use for the preview.
676 * @param float $maxmark the maximum to mark the question out of.
677 * @param question_display_options $displayoptions the display options to use.
678 * @param int $variant the variant of the question to preview. If null, one will
679 * be picked randomly.
680 * @param object $context context to run the preview in (affects things like
681 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
682 * @return moodle_url the URL.
684 function question_preview_url($questionid, $preferredbehaviour = null,
685 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
687 $params = array('id' => $questionid);
689 if (is_null($context)) {
690 global $PAGE;
691 $context = $PAGE->context;
693 if ($context->contextlevel == CONTEXT_MODULE) {
694 $params['cmid'] = $context->instanceid;
695 } else if ($context->contextlevel == CONTEXT_COURSE) {
696 $params['courseid'] = $context->instanceid;
699 if (!is_null($preferredbehaviour)) {
700 $params['behaviour'] = $preferredbehaviour;
703 if (!is_null($maxmark)) {
704 $params['maxmark'] = $maxmark;
707 if (!is_null($displayoptions)) {
708 $params['correctness'] = $displayoptions->correctness;
709 $params['marks'] = $displayoptions->marks;
710 $params['markdp'] = $displayoptions->markdp;
711 $params['feedback'] = (bool) $displayoptions->feedback;
712 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
713 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
714 $params['history'] = (bool) $displayoptions->history;
717 if ($variant) {
718 $params['variant'] = $variant;
721 return new moodle_url('/question/preview.php', $params);
725 * @return array that can be passed as $params to the {@link popup_action} constructor.
727 function question_preview_popup_params() {
728 return array(
729 'height' => 600,
730 'width' => 800,
735 * Given a list of ids, load the basic information about a set of questions from
736 * the questions table. The $join and $extrafields arguments can be used together
737 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
738 * read the code below to see how the SQL is assembled. Throws exceptions on error.
740 * @param array $questionids array of question ids to load. If null, then all
741 * questions matched by $join will be loaded.
742 * @param string $extrafields extra SQL code to be added to the query.
743 * @param string $join extra SQL code to be added to the query.
744 * @param array $extraparams values for any placeholders in $join.
745 * You must use named placeholders.
746 * @param string $orderby what to order the results by. Optional, default is unspecified order.
748 * @return array partially complete question objects. You need to call get_question_options
749 * on them before they can be properly used.
751 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
752 $extraparams = array(), $orderby = '') {
753 global $DB;
755 if ($questionids === null) {
756 $where = '';
757 $params = array();
758 } else {
759 if (empty($questionids)) {
760 return array();
763 list($questionidcondition, $params) = $DB->get_in_or_equal(
764 $questionids, SQL_PARAMS_NAMED, 'qid0000');
765 $where = 'WHERE q.id ' . $questionidcondition;
768 if ($join) {
769 $join = 'JOIN ' . $join;
772 if ($extrafields) {
773 $extrafields = ', ' . $extrafields;
776 if ($orderby) {
777 $orderby = 'ORDER BY ' . $orderby;
780 $sql = "SELECT q.*, qc.contextid{$extrafields}
781 FROM {question} q
782 JOIN {question_categories} qc ON q.category = qc.id
783 {$join}
784 {$where}
785 {$orderby}";
787 // Load the questions.
788 $questions = $DB->get_records_sql($sql, $extraparams + $params);
789 foreach ($questions as $question) {
790 $question->_partiallyloaded = true;
793 return $questions;
797 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
798 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
799 * read the code below to see how the SQL is assembled. Throws exceptions on error.
801 * @param array $questionids array of question ids.
802 * @param string $extrafields extra SQL code to be added to the query.
803 * @param string $join extra SQL code to be added to the query.
804 * @param array $extraparams values for any placeholders in $join.
805 * You are strongly recommended to use named placeholder.
807 * @return array question objects.
809 function question_load_questions($questionids, $extrafields = '', $join = '') {
810 $questions = question_preload_questions($questionids, $extrafields, $join);
812 // Load the question type specific information
813 if (!get_question_options($questions)) {
814 return 'Could not load the question options';
817 return $questions;
821 * Private function to factor common code out of get_question_options().
823 * @param object $question the question to tidy.
824 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
826 function _tidy_question($question, $loadtags = false) {
827 global $CFG;
829 // Load question-type specific fields.
830 if (!question_bank::is_qtype_installed($question->qtype)) {
831 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
832 'qtype_missingtype')) . $question->questiontext;
834 question_bank::get_qtype($question->qtype)->get_question_options($question);
836 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
837 $question->defaultmark += 0;
838 $question->penalty += 0;
840 if (isset($question->_partiallyloaded)) {
841 unset($question->_partiallyloaded);
844 if ($loadtags && !empty($CFG->usetags)) {
845 require_once($CFG->dirroot . '/tag/lib.php');
846 $question->tags = tag_get_tags_array('question', $question->id);
851 * Updates the question objects with question type specific
852 * information by calling {@link get_question_options()}
854 * Can be called either with an array of question objects or with a single
855 * question object.
857 * @param mixed $questions Either an array of question objects to be updated
858 * or just a single question object
859 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
860 * @return bool Indicates success or failure.
862 function get_question_options(&$questions, $loadtags = false) {
863 if (is_array($questions)) { // deal with an array of questions
864 foreach ($questions as $i => $notused) {
865 _tidy_question($questions[$i], $loadtags);
867 } else { // deal with single question
868 _tidy_question($questions, $loadtags);
870 return true;
874 * Print the icon for the question type
876 * @param object $question The question object for which the icon is required.
877 * Only $question->qtype is used.
878 * @return string the HTML for the img tag.
880 function print_question_icon($question) {
881 global $PAGE;
882 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
886 * Creates a stamp that uniquely identifies this version of the question
888 * In future we want this to use a hash of the question data to guarantee that
889 * identical versions have the same version stamp.
891 * @param object $question
892 * @return string A unique version stamp
894 function question_hash($question) {
895 return make_unique_id_code();
898 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
900 * Saves question options
902 * Simply calls the question type specific save_question_options() method.
903 * @deprecated all code should now call the question type method directly.
905 function save_question_options($question) {
906 debugging('Please do not call save_question_options any more. Call the question type method directly.',
907 DEBUG_DEVELOPER);
908 question_bank::get_qtype($question->qtype)->save_question_options($question);
911 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
914 * returns the categories with their names ordered following parent-child relationships
915 * finally it tries to return pending categories (those being orphaned, whose parent is
916 * incorrect) to avoid missing any category from original array.
918 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
919 global $DB;
921 $children = array();
922 $keys = array_keys($categories);
924 foreach ($keys as $key) {
925 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
926 $children[$key] = $categories[$key];
927 $categories[$key]->processed = true;
928 $children = $children + sort_categories_by_tree(
929 $categories, $children[$key]->id, $level+1);
932 //If level = 1, we have finished, try to look for non processed categories
933 // (bad parent) and sort them too
934 if ($level == 1) {
935 foreach ($keys as $key) {
936 // If not processed and it's a good candidate to start (because its
937 // parent doesn't exist in the course)
938 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
939 array('contextid' => $categories[$key]->contextid,
940 'id' => $categories[$key]->parent))) {
941 $children[$key] = $categories[$key];
942 $categories[$key]->processed = true;
943 $children = $children + sort_categories_by_tree(
944 $categories, $children[$key]->id, $level + 1);
948 return $children;
952 * Private method, only for the use of add_indented_names().
954 * Recursively adds an indentedname field to each category, starting with the category
955 * with id $id, and dealing with that category and all its children, and
956 * return a new array, with those categories in the right order.
958 * @param array $categories an array of categories which has had childids
959 * fields added by flatten_category_tree(). Passed by reference for
960 * performance only. It is not modfied.
961 * @param int $id the category to start the indenting process from.
962 * @param int $depth the indent depth. Used in recursive calls.
963 * @return array a new array of categories, in the right order for the tree.
965 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
967 // Indent the name of this category.
968 $newcategories = array();
969 $newcategories[$id] = $categories[$id];
970 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
971 $categories[$id]->name;
973 // Recursively indent the children.
974 foreach ($categories[$id]->childids as $childid) {
975 if ($childid != $nochildrenof) {
976 $newcategories = $newcategories + flatten_category_tree(
977 $categories, $childid, $depth + 1, $nochildrenof);
981 // Remove the childids array that were temporarily added.
982 unset($newcategories[$id]->childids);
984 return $newcategories;
988 * Format categories into an indented list reflecting the tree structure.
990 * @param array $categories An array of category objects, for example from the.
991 * @return array The formatted list of categories.
993 function add_indented_names($categories, $nochildrenof = -1) {
995 // Add an array to each category to hold the child category ids. This array
996 // will be removed again by flatten_category_tree(). It should not be used
997 // outside these two functions.
998 foreach (array_keys($categories) as $id) {
999 $categories[$id]->childids = array();
1002 // Build the tree structure, and record which categories are top-level.
1003 // We have to be careful, because the categories array may include published
1004 // categories from other courses, but not their parents.
1005 $toplevelcategoryids = array();
1006 foreach (array_keys($categories) as $id) {
1007 if (!empty($categories[$id]->parent) &&
1008 array_key_exists($categories[$id]->parent, $categories)) {
1009 $categories[$categories[$id]->parent]->childids[] = $id;
1010 } else {
1011 $toplevelcategoryids[] = $id;
1015 // Flatten the tree to and add the indents.
1016 $newcategories = array();
1017 foreach ($toplevelcategoryids as $id) {
1018 $newcategories = $newcategories + flatten_category_tree(
1019 $categories, $id, 0, $nochildrenof);
1022 return $newcategories;
1026 * Output a select menu of question categories.
1028 * Categories from this course and (optionally) published categories from other courses
1029 * are included. Optionally, only categories the current user may edit can be included.
1031 * @param integer $courseid the id of the course to get the categories for.
1032 * @param integer $published if true, include publised categories from other courses.
1033 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1034 * @param integer $selected optionally, the id of a category to be selected by
1035 * default in the dropdown.
1037 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1038 $selected = "", $nochildrenof = -1) {
1039 global $OUTPUT;
1040 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1041 false, $nochildrenof);
1042 if ($selected) {
1043 $choose = '';
1044 } else {
1045 $choose = 'choosedots';
1047 $options = array();
1048 foreach ($categoriesarray as $group => $opts) {
1049 $options[] = array($group => $opts);
1051 echo html_writer::label($selected, 'menucategory', false, array('class' => 'accesshide'));
1052 echo html_writer::select($options, 'category', $selected, $choose);
1056 * @param integer $contextid a context id.
1057 * @return object the default question category for that context, or false if none.
1059 function question_get_default_category($contextid) {
1060 global $DB;
1061 $category = $DB->get_records('question_categories',
1062 array('contextid' => $contextid), 'id', '*', 0, 1);
1063 if (!empty($category)) {
1064 return reset($category);
1065 } else {
1066 return false;
1071 * Gets the default category in the most specific context.
1072 * If no categories exist yet then default ones are created in all contexts.
1074 * @param array $contexts The context objects for this context and all parent contexts.
1075 * @return object The default category - the category in the course context
1077 function question_make_default_categories($contexts) {
1078 global $DB;
1079 static $preferredlevels = array(
1080 CONTEXT_COURSE => 4,
1081 CONTEXT_MODULE => 3,
1082 CONTEXT_COURSECAT => 2,
1083 CONTEXT_SYSTEM => 1,
1086 $toreturn = null;
1087 $preferredness = 0;
1088 // If it already exists, just return it.
1089 foreach ($contexts as $key => $context) {
1090 if (!$exists = $DB->record_exists("question_categories",
1091 array('contextid' => $context->id))) {
1092 // Otherwise, we need to make one
1093 $category = new stdClass();
1094 $contextname = $context->get_context_name(false, true);
1095 $category->name = get_string('defaultfor', 'question', $contextname);
1096 $category->info = get_string('defaultinfofor', 'question', $contextname);
1097 $category->contextid = $context->id;
1098 $category->parent = 0;
1099 // By default, all categories get this number, and are sorted alphabetically.
1100 $category->sortorder = 999;
1101 $category->stamp = make_unique_id_code();
1102 $category->id = $DB->insert_record('question_categories', $category);
1103 } else {
1104 $category = question_get_default_category($context->id);
1106 $thispreferredness = $preferredlevels[$context->contextlevel];
1107 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1108 $thispreferredness += 10;
1110 if ($thispreferredness > $preferredness) {
1111 $toreturn = $category;
1112 $preferredness = $thispreferredness;
1116 if (!is_null($toreturn)) {
1117 $toreturn = clone($toreturn);
1119 return $toreturn;
1123 * Get all the category objects, including a count of the number of questions in that category,
1124 * for all the categories in the lists $contexts.
1126 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1127 * @param string $sortorder used as the ORDER BY clause in the select statement.
1128 * @return array of category objects.
1130 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1131 global $DB;
1132 return $DB->get_records_sql("
1133 SELECT c.*, (SELECT count(1) FROM {question} q
1134 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1135 FROM {question_categories} c
1136 WHERE c.contextid IN ($contexts)
1137 ORDER BY $sortorder");
1141 * Output an array of question categories.
1143 function question_category_options($contexts, $top = false, $currentcat = 0,
1144 $popupform = false, $nochildrenof = -1) {
1145 global $CFG;
1146 $pcontexts = array();
1147 foreach ($contexts as $context) {
1148 $pcontexts[] = $context->id;
1150 $contextslist = join($pcontexts, ', ');
1152 $categories = get_categories_for_contexts($contextslist);
1154 $categories = question_add_context_in_key($categories);
1156 if ($top) {
1157 $categories = question_add_tops($categories, $pcontexts);
1159 $categories = add_indented_names($categories, $nochildrenof);
1161 // sort cats out into different contexts
1162 $categoriesarray = array();
1163 foreach ($pcontexts as $contextid) {
1164 $context = context::instance_by_id($contextid);
1165 $contextstring = $context->get_context_name(true, true);
1166 foreach ($categories as $category) {
1167 if ($category->contextid == $contextid) {
1168 $cid = $category->id;
1169 if ($currentcat != $cid || $currentcat == 0) {
1170 $countstring = !empty($category->questioncount) ?
1171 " ($category->questioncount)" : '';
1172 $categoriesarray[$contextstring][$cid] =
1173 format_string($category->indentedname, true,
1174 array('context' => $context)) . $countstring;
1179 if ($popupform) {
1180 $popupcats = array();
1181 foreach ($categoriesarray as $contextstring => $optgroup) {
1182 $group = array();
1183 foreach ($optgroup as $key => $value) {
1184 $key = str_replace($CFG->wwwroot, '', $key);
1185 $group[$key] = $value;
1187 $popupcats[] = array($contextstring => $group);
1189 return $popupcats;
1190 } else {
1191 return $categoriesarray;
1195 function question_add_context_in_key($categories) {
1196 $newcatarray = array();
1197 foreach ($categories as $id => $category) {
1198 $category->parent = "$category->parent,$category->contextid";
1199 $category->id = "$category->id,$category->contextid";
1200 $newcatarray["$id,$category->contextid"] = $category;
1202 return $newcatarray;
1205 function question_add_tops($categories, $pcontexts) {
1206 $topcats = array();
1207 foreach ($pcontexts as $context) {
1208 $newcat = new stdClass();
1209 $newcat->id = "0,$context";
1210 $newcat->name = get_string('top');
1211 $newcat->parent = -1;
1212 $newcat->contextid = $context;
1213 $topcats["0,$context"] = $newcat;
1215 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1216 return array_merge($topcats, $categories);
1220 * @return array of question category ids of the category and all subcategories.
1222 function question_categorylist($categoryid) {
1223 global $DB;
1225 // final list of category IDs
1226 $categorylist = array();
1228 // a list of category IDs to check for any sub-categories
1229 $subcategories = array($categoryid);
1231 while ($subcategories) {
1232 foreach ($subcategories as $subcategory) {
1233 // if anything from the temporary list was added already, then we have a loop
1234 if (isset($categorylist[$subcategory])) {
1235 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1237 $categorylist[$subcategory] = $subcategory;
1240 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1242 $subcategories = $DB->get_records_select_menu('question_categories',
1243 "parent $in", $params, NULL, 'id,id AS id2');
1246 return $categorylist;
1249 //===========================
1250 // Import/Export Functions
1251 //===========================
1254 * Get list of available import or export formats
1255 * @param string $type 'import' if import list, otherwise export list assumed
1256 * @return array sorted list of import/export formats available
1258 function get_import_export_formats($type) {
1259 global $CFG;
1260 require_once($CFG->dirroot . '/question/format.php');
1262 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1264 $fileformatname = array();
1265 foreach ($formatclasses as $component => $formatclass) {
1267 $format = new $formatclass();
1268 if ($type == 'import') {
1269 $provided = $format->provide_import();
1270 } else {
1271 $provided = $format->provide_export();
1274 if ($provided) {
1275 list($notused, $fileformat) = explode('_', $component, 2);
1276 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1280 core_collator::asort($fileformatnames);
1281 return $fileformatnames;
1286 * Create a reasonable default file name for exporting questions from a particular
1287 * category.
1288 * @param object $course the course the questions are in.
1289 * @param object $category the question category.
1290 * @return string the filename.
1292 function question_default_export_filename($course, $category) {
1293 // We build a string that is an appropriate name (questions) from the lang pack,
1294 // then the corse shortname, then the question category name, then a timestamp.
1296 $base = clean_filename(get_string('exportfilename', 'question'));
1298 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1299 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1301 $shortname = clean_filename($course->shortname);
1302 if ($shortname == '' || $shortname == '_' ) {
1303 $shortname = $course->id;
1306 $categoryname = clean_filename(format_string($category->name));
1308 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1310 return $export_name;
1314 * Converts contextlevels to strings and back to help with reading/writing contexts
1315 * to/from import/export files.
1317 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1320 class context_to_string_translator{
1322 * @var array used to translate between contextids and strings for this context.
1324 protected $contexttostringarray = array();
1326 public function __construct($contexts) {
1327 $this->generate_context_to_string_array($contexts);
1330 public function context_to_string($contextid) {
1331 return $this->contexttostringarray[$contextid];
1334 public function string_to_context($contextname) {
1335 $contextid = array_search($contextname, $this->contexttostringarray);
1336 return $contextid;
1339 protected function generate_context_to_string_array($contexts) {
1340 if (!$this->contexttostringarray) {
1341 $catno = 1;
1342 foreach ($contexts as $context) {
1343 switch ($context->contextlevel) {
1344 case CONTEXT_MODULE :
1345 $contextstring = 'module';
1346 break;
1347 case CONTEXT_COURSE :
1348 $contextstring = 'course';
1349 break;
1350 case CONTEXT_COURSECAT :
1351 $contextstring = "cat$catno";
1352 $catno++;
1353 break;
1354 case CONTEXT_SYSTEM :
1355 $contextstring = 'system';
1356 break;
1358 $this->contexttostringarray[$context->id] = $contextstring;
1366 * Check capability on category
1368 * @param mixed $question object or id
1369 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1370 * @param integer $cachecat useful to cache all question records in a category
1371 * @return boolean this user has the capability $cap for this question $question?
1373 function question_has_capability_on($question, $cap, $cachecat = -1) {
1374 global $USER, $DB;
1376 // these are capabilities on existing questions capabilties are
1377 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1378 $question_questioncaps = array('edit', 'view', 'use', 'move');
1379 static $questions = array();
1380 static $categories = array();
1381 static $cachedcat = array();
1382 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1383 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1384 $cachedcat[] = $cachecat;
1386 if (!is_object($question)) {
1387 if (!isset($questions[$question])) {
1388 if (!$questions[$question] = $DB->get_record('question',
1389 array('id' => $question), 'id,category,createdby')) {
1390 print_error('questiondoesnotexist', 'question');
1393 $question = $questions[$question];
1395 if (empty($question->category)) {
1396 // This can happen when we have created a fake 'missingtype' question to
1397 // take the place of a deleted question.
1398 return false;
1400 if (!isset($categories[$question->category])) {
1401 if (!$categories[$question->category] = $DB->get_record('question_categories',
1402 array('id'=>$question->category))) {
1403 print_error('invalidcategory', 'quiz');
1406 $category = $categories[$question->category];
1407 $context = context::instance_by_id($category->contextid);
1409 if (array_search($cap, $question_questioncaps)!== false) {
1410 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1411 if ($question->createdby == $USER->id) {
1412 return has_capability('moodle/question:' . $cap . 'mine', $context);
1413 } else {
1414 return false;
1416 } else {
1417 return true;
1419 } else {
1420 return has_capability('moodle/question:' . $cap, $context);
1426 * Require capability on question.
1428 function question_require_capability_on($question, $cap) {
1429 if (!question_has_capability_on($question, $cap)) {
1430 print_error('nopermissions', '', '', $cap);
1432 return true;
1436 * Get the real state - the correct question id and answer - for a random
1437 * question.
1438 * @param object $state with property answer.
1439 * @deprecated this function has not been relevant since Moodle 2.1!
1441 function question_get_real_state($state) {
1442 throw new coding_exception('question_get_real_state has not been relevant since Moodle 2.1. ' .
1443 'I am not sure what you are trying to do, but stop it at once!');
1447 * @param object $context a context
1448 * @return string A URL for editing questions in this context.
1450 function question_edit_url($context) {
1451 global $CFG, $SITE;
1452 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1453 return false;
1455 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1456 $defaultcategory = question_get_default_category($context->id);
1457 if ($defaultcategory) {
1458 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1460 switch ($context->contextlevel) {
1461 case CONTEXT_SYSTEM:
1462 return $baseurl . 'courseid=' . $SITE->id;
1463 case CONTEXT_COURSECAT:
1464 // This is nasty, becuase we can only edit questions in a course
1465 // context at the moment, so for now we just return false.
1466 return false;
1467 case CONTEXT_COURSE:
1468 return $baseurl . 'courseid=' . $context->instanceid;
1469 case CONTEXT_MODULE:
1470 return $baseurl . 'cmid=' . $context->instanceid;
1476 * Adds question bank setting links to the given navigation node if caps are met.
1478 * @param navigation_node $navigationnode The navigation node to add the question branch to
1479 * @param object $context
1480 * @return navigation_node Returns the question branch that was added
1482 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1483 global $PAGE;
1485 if ($context->contextlevel == CONTEXT_COURSE) {
1486 $params = array('courseid'=>$context->instanceid);
1487 } else if ($context->contextlevel == CONTEXT_MODULE) {
1488 $params = array('cmid'=>$context->instanceid);
1489 } else {
1490 return;
1493 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1494 $params['cat'] = $cat;
1497 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1498 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1500 $contexts = new question_edit_contexts($context);
1501 if ($contexts->have_one_edit_tab_cap('questions')) {
1502 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1503 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1505 if ($contexts->have_one_edit_tab_cap('categories')) {
1506 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1507 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1509 if ($contexts->have_one_edit_tab_cap('import')) {
1510 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1511 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1513 if ($contexts->have_one_edit_tab_cap('export')) {
1514 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1515 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1518 return $questionnode;
1522 * @return array all the capabilities that relate to accessing particular questions.
1524 function question_get_question_capabilities() {
1525 return array(
1526 'moodle/question:add',
1527 'moodle/question:editmine',
1528 'moodle/question:editall',
1529 'moodle/question:viewmine',
1530 'moodle/question:viewall',
1531 'moodle/question:usemine',
1532 'moodle/question:useall',
1533 'moodle/question:movemine',
1534 'moodle/question:moveall',
1539 * @return array all the question bank capabilities.
1541 function question_get_all_capabilities() {
1542 $caps = question_get_question_capabilities();
1543 $caps[] = 'moodle/question:managecategory';
1544 $caps[] = 'moodle/question:flag';
1545 return $caps;
1550 * Tracks all the contexts related to the one where we are currently editing
1551 * questions, and provides helper methods to check permissions.
1553 * @copyright 2007 Jamie Pratt me@jamiep.org
1554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1556 class question_edit_contexts {
1558 public static $caps = array(
1559 'editq' => array('moodle/question:add',
1560 'moodle/question:editmine',
1561 'moodle/question:editall',
1562 'moodle/question:viewmine',
1563 'moodle/question:viewall',
1564 'moodle/question:usemine',
1565 'moodle/question:useall',
1566 'moodle/question:movemine',
1567 'moodle/question:moveall'),
1568 'questions'=>array('moodle/question:add',
1569 'moodle/question:editmine',
1570 'moodle/question:editall',
1571 'moodle/question:viewmine',
1572 'moodle/question:viewall',
1573 'moodle/question:movemine',
1574 'moodle/question:moveall'),
1575 'categories'=>array('moodle/question:managecategory'),
1576 'import'=>array('moodle/question:add'),
1577 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1579 protected $allcontexts;
1582 * Constructor
1583 * @param context the current context.
1585 public function __construct(context $thiscontext) {
1586 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1590 * @return array all parent contexts
1592 public function all() {
1593 return $this->allcontexts;
1597 * @return object lowest context which must be either the module or course context
1599 public function lowest() {
1600 return $this->allcontexts[0];
1604 * @param string $cap capability
1605 * @return array parent contexts having capability, zero based index
1607 public function having_cap($cap) {
1608 $contextswithcap = array();
1609 foreach ($this->allcontexts as $context) {
1610 if (has_capability($cap, $context)) {
1611 $contextswithcap[] = $context;
1614 return $contextswithcap;
1618 * @param array $caps capabilities
1619 * @return array parent contexts having at least one of $caps, zero based index
1621 public function having_one_cap($caps) {
1622 $contextswithacap = array();
1623 foreach ($this->allcontexts as $context) {
1624 foreach ($caps as $cap) {
1625 if (has_capability($cap, $context)) {
1626 $contextswithacap[] = $context;
1627 break; //done with caps loop
1631 return $contextswithacap;
1635 * @param string $tabname edit tab name
1636 * @return array parent contexts having at least one of $caps, zero based index
1638 public function having_one_edit_tab_cap($tabname) {
1639 return $this->having_one_cap(self::$caps[$tabname]);
1643 * @return those contexts where a user can add a question and then use it.
1645 public function having_add_and_use() {
1646 $contextswithcap = array();
1647 foreach ($this->allcontexts as $context) {
1648 if (!has_capability('moodle/question:add', $context)) {
1649 continue;
1651 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1652 continue;
1654 $contextswithcap[] = $context;
1656 return $contextswithcap;
1660 * Has at least one parent context got the cap $cap?
1662 * @param string $cap capability
1663 * @return boolean
1665 public function have_cap($cap) {
1666 return (count($this->having_cap($cap)));
1670 * Has at least one parent context got one of the caps $caps?
1672 * @param array $caps capability
1673 * @return boolean
1675 public function have_one_cap($caps) {
1676 foreach ($caps as $cap) {
1677 if ($this->have_cap($cap)) {
1678 return true;
1681 return false;
1685 * Has at least one parent context got one of the caps for actions on $tabname
1687 * @param string $tabname edit tab name
1688 * @return boolean
1690 public function have_one_edit_tab_cap($tabname) {
1691 return $this->have_one_cap(self::$caps[$tabname]);
1695 * Throw error if at least one parent context hasn't got the cap $cap
1697 * @param string $cap capability
1699 public function require_cap($cap) {
1700 if (!$this->have_cap($cap)) {
1701 print_error('nopermissions', '', '', $cap);
1706 * Throw error if at least one parent context hasn't got one of the caps $caps
1708 * @param array $cap capabilities
1710 public function require_one_cap($caps) {
1711 if (!$this->have_one_cap($caps)) {
1712 $capsstring = join($caps, ', ');
1713 print_error('nopermissions', '', '', $capsstring);
1718 * Throw error if at least one parent context hasn't got one of the caps $caps
1720 * @param string $tabname edit tab name
1722 public function require_one_edit_tab_cap($tabname) {
1723 if (!$this->have_one_edit_tab_cap($tabname)) {
1724 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1731 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1733 * @package core_question
1734 * @category files
1735 * @param string $text text being processed
1736 * @param string $file the php script used to serve files
1737 * @param int $contextid context ID
1738 * @param string $component component
1739 * @param string $filearea filearea
1740 * @param array $ids other IDs will be used to check file permission
1741 * @param int $itemid item ID
1742 * @param array $options options
1743 * @return string
1745 function question_rewrite_question_urls($text, $file, $contextid, $component,
1746 $filearea, array $ids, $itemid, array $options=null) {
1748 $idsstr = '';
1749 if (!empty($ids)) {
1750 $idsstr .= implode('/', $ids);
1752 if ($itemid !== null) {
1753 $idsstr .= '/' . $itemid;
1755 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1756 $filearea, $idsstr, $options);
1760 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1761 * text outside an attempt (for example, in the question bank listing or in the
1762 * quiz statistics report).
1764 * @param string $questiontext the question text.
1765 * @param int $contextid the context the text is being displayed in.
1766 * @param string $component component
1767 * @param array $questionid the question id
1768 * @param array $options e.g. forcedownload. Passed to file_rewrite_pluginfile_urls.
1769 * @return string $questiontext with URLs rewritten.
1770 * @deprecated since Moodle 2.6
1772 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1773 $component, $questionid, $options=null) {
1774 global $DB;
1776 debugging('question_rewrite_questiontext_preview_urls has been deprecated. ' .
1777 'Please use question_rewrite_question_preview_urls instead', DEBUG_DEVELOPER);
1778 $questioncontextid = $DB->get_field_sql('
1779 SELECT qc.contextid
1780 FROM {question} q
1781 JOIN {question_categories} qc ON qc.id = q.category
1782 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1784 return question_rewrite_question_preview_urls($questiontext, $questionid,
1785 $questioncontextid, 'question', 'questiontext', $questionid,
1786 $contextid, $component, $options);
1790 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1791 * viewing the question outside an attempt (for example, in the question bank
1792 * listing or in the quiz statistics report).
1794 * @param string $text the question text.
1795 * @param int $questionid the question id.
1796 * @param int $filecontextid the context id of the question being displayed.
1797 * @param string $filecomponent the component that owns the file area.
1798 * @param string $filearea the file area name.
1799 * @param int|null $itemid the file's itemid
1800 * @param int $previewcontextid the context id where the preview is being displayed.
1801 * @param string $previewcomponent component responsible for displaying the preview.
1802 * @param array $options text and file options ('forcehttps'=>false)
1803 * @return string $questiontext with URLs rewritten.
1805 function question_rewrite_question_preview_urls($text, $questionid,
1806 $filecontextid, $filecomponent, $filearea, $itemid,
1807 $previewcontextid, $previewcomponent, $options = null) {
1809 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1810 if ($itemid) {
1811 $path .= '/' . $itemid;
1814 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1815 $filecomponent, $filearea, $path, $options);
1819 * Send a file from the question text of a question.
1820 * @param int $questionid the question id
1821 * @param array $args the remaining file arguments (file path).
1822 * @param bool $forcedownload whether the user must be forced to download the file.
1823 * @param array $options additional options affecting the file serving
1824 * @deprecated since Moodle 2.6.
1826 function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
1827 global $DB;
1829 debugging('question_send_questiontext_file has been deprecated. It is no longer necessary. ' .
1830 'You can now just use send_stored_file.', DEBUG_DEVELOPER);
1831 $question = $DB->get_record_sql('
1832 SELECT q.id, qc.contextid
1833 FROM {question} q
1834 JOIN {question_categories} qc ON qc.id = q.category
1835 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1837 $fs = get_file_storage();
1838 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1840 // Get rid of the redundant questionid.
1841 $fullpath = str_replace("/{$questionid}/{$questionid}/", "/{$questionid}/", $fullpath);
1843 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1844 send_file_not_found();
1847 send_stored_file($file, 0, 0, $forcedownload, $options);
1851 * Called by pluginfile.php to serve files related to the 'question' core
1852 * component and for files belonging to qtypes.
1854 * For files that relate to questions in a question_attempt, then we delegate to
1855 * a function in the component that owns the attempt (for example in the quiz,
1856 * or in core question preview) to get necessary inforation.
1858 * (Note that, at the moment, all question file areas relate to questions in
1859 * attempts, so the If at the start of the last paragraph is always true.)
1861 * Does not return, either calls send_file_not_found(); or serves the file.
1863 * @package core_question
1864 * @category files
1865 * @param stdClass $course course settings object
1866 * @param stdClass $context context object
1867 * @param string $component the name of the component we are serving files for.
1868 * @param string $filearea the name of the file area.
1869 * @param array $args the remaining bits of the file path.
1870 * @param bool $forcedownload whether the user must be forced to download the file.
1871 * @param array $options additional options affecting the file serving
1873 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1874 global $DB, $CFG;
1876 // Special case, sending a question bank export.
1877 if ($filearea === 'export') {
1878 list($context, $course, $cm) = get_context_info_array($context->id);
1879 require_login($course, false, $cm);
1881 require_once($CFG->dirroot . '/question/editlib.php');
1882 $contexts = new question_edit_contexts($context);
1883 // check export capability
1884 $contexts->require_one_edit_tab_cap('export');
1885 $category_id = (int)array_shift($args);
1886 $format = array_shift($args);
1887 $cattofile = array_shift($args);
1888 $contexttofile = array_shift($args);
1889 $filename = array_shift($args);
1891 // load parent class for import/export
1892 require_once($CFG->dirroot . '/question/format.php');
1893 require_once($CFG->dirroot . '/question/editlib.php');
1894 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1896 $classname = 'qformat_' . $format;
1897 if (!class_exists($classname)) {
1898 send_file_not_found();
1901 $qformat = new $classname();
1903 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1904 send_file_not_found();
1907 $qformat->setCategory($category);
1908 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1909 $qformat->setCourse($course);
1911 if ($cattofile == 'withcategories') {
1912 $qformat->setCattofile(true);
1913 } else {
1914 $qformat->setCattofile(false);
1917 if ($contexttofile == 'withcontexts') {
1918 $qformat->setContexttofile(true);
1919 } else {
1920 $qformat->setContexttofile(false);
1923 if (!$qformat->exportpreprocess()) {
1924 send_file_not_found();
1925 print_error('exporterror', 'question', $thispageurl->out());
1928 // export data to moodle file pool
1929 if (!$content = $qformat->exportprocess(true)) {
1930 send_file_not_found();
1933 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1936 // Normal case, a file belonging to a question.
1937 $qubaidorpreview = array_shift($args);
1939 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1940 if ($qubaidorpreview === 'preview') {
1941 $previewcontextid = (int)array_shift($args);
1942 $previewcomponent = array_shift($args);
1943 $questionid = (int) array_shift($args);
1944 $previewcontext = context_helper::instance_by_id($previewcontextid);
1946 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1947 $previewcontext, $questionid,
1948 $context, $component, $filearea, $args,
1949 $forcedownload, $options), 'newcallbackmissing');
1951 if ($result === 'newcallbackmissing' && $filearea = 'questiontext') {
1952 // Fall back to the legacy callback for backwards compatibility.
1953 debugging("Component {$previewcomponent} does not define the expected " .
1954 "{$previewcomponent}_question_preview_pluginfile callback. Falling back to the deprecated " .
1955 "{$previewcomponent}_questiontext_preview_pluginfile callback.", DEBUG_DEVELOPER);
1956 component_callback($previewcomponent, 'questiontext_preview_pluginfile', array(
1957 $previewcontext, $questionid, $args, $forcedownload, $options));
1960 send_file_not_found();
1963 // 2. A question being attempted in the normal way.
1964 $qubaid = (int)$qubaidorpreview;
1965 $slot = (int)array_shift($args);
1967 $module = $DB->get_field('question_usages', 'component',
1968 array('id' => $qubaid));
1970 if ($module === 'core_question_preview') {
1971 require_once($CFG->dirroot . '/question/previewlib.php');
1972 return question_preview_question_pluginfile($course, $context,
1973 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1975 } else {
1976 $dir = core_component::get_component_directory($module);
1977 if (!file_exists("$dir/lib.php")) {
1978 send_file_not_found();
1980 include_once("$dir/lib.php");
1982 $filefunction = $module . '_question_pluginfile';
1983 if (function_exists($filefunction)) {
1984 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1985 $args, $forcedownload, $options);
1988 // Okay, we're here so lets check for function without 'mod_'.
1989 if (strpos($module, 'mod_') === 0) {
1990 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1991 if (function_exists($filefunctionold)) {
1992 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1993 $args, $forcedownload, $options);
1997 send_file_not_found();
2002 * Serve questiontext files in the question text when they are displayed in this report.
2004 * @package core_files
2005 * @category files
2006 * @param context $previewcontext the context in which the preview is happening.
2007 * @param int $questionid the question id.
2008 * @param context $filecontext the file (question) context.
2009 * @param string $filecomponent the component the file belongs to.
2010 * @param string $filearea the file area.
2011 * @param array $args remaining file args.
2012 * @param bool $forcedownload.
2013 * @param array $options additional options affecting the file serving.
2015 function core_question_question_preview_pluginfile($previewcontext, $questionid,
2016 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
2017 global $DB;
2019 // Verify that contextid matches the question.
2020 $question = $DB->get_record_sql('
2021 SELECT q.*, qc.contextid
2022 FROM {question} q
2023 JOIN {question_categories} qc ON qc.id = q.category
2024 WHERE q.id = :id AND qc.contextid = :contextid',
2025 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
2027 // Check the capability.
2028 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
2029 require_login($course, false, $cm);
2031 question_require_capability_on($question, 'use');
2033 $fs = get_file_storage();
2034 $relativepath = implode('/', $args);
2035 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2036 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2037 send_file_not_found();
2040 send_stored_file($file, 0, 0, $forcedownload, $options);
2044 * Create url for question export
2046 * @param int $contextid, current context
2047 * @param int $categoryid, categoryid
2048 * @param string $format
2049 * @param string $withcategories
2050 * @param string $ithcontexts
2051 * @param moodle_url export file url
2053 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2054 $withcontexts, $filename) {
2055 global $CFG;
2056 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
2057 return moodle_url::make_file_url($urlbase,
2058 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2059 "/{$withcontexts}/{$filename}", true);
2063 * Return a list of page types
2064 * @param string $pagetype current page type
2065 * @param stdClass $parentcontext Block's parent context
2066 * @param stdClass $currentcontext Current context of block
2068 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2069 global $CFG;
2070 $types = array(
2071 'question-*'=>get_string('page-question-x', 'question'),
2072 'question-edit'=>get_string('page-question-edit', 'question'),
2073 'question-category'=>get_string('page-question-category', 'question'),
2074 'question-export'=>get_string('page-question-export', 'question'),
2075 'question-import'=>get_string('page-question-import', 'question')
2077 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2078 require_once($CFG->dirroot . '/course/lib.php');
2079 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2080 } else {
2081 return $types;
2086 * Does an activity module use the question bank?
2088 * @param string $modname The name of the module (without mod_ prefix).
2089 * @return bool true if the module uses questions.
2091 function question_module_uses_questions($modname) {
2092 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2093 return true;
2096 $component = 'mod_'.$modname;
2097 if (component_callback_exists($component, 'question_pluginfile')) {
2098 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2099 return true;
2102 return false;