Merge branch 'MDL-32780-CLEAN' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / questionlib.php
blobe49a09ce5c17ac237d0ab8d5850c3e4132f7c738
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 (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 * match grade options
213 * if no match return error or match nearest
214 * @param array $gradeoptionsfull list of valid options
215 * @param int $grade grade to be tested
216 * @param string $matchgrades 'error' or 'nearest'
217 * @return mixed either 'fixed' value or false if erro
219 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
220 if ($matchgrades == 'error') {
221 // if we just need an error...
222 foreach ($gradeoptionsfull as $value => $option) {
223 // slightly fuzzy test, never check floats for equality :-)
224 if (abs($grade - $value) < 0.00001) {
225 return $grade;
228 // didn't find a match so that's an error
229 return false;
230 } else if ($matchgrades == 'nearest') {
231 // work out nearest value
232 $hownear = array();
233 foreach ($gradeoptionsfull as $value => $option) {
234 if ($grade==$value) {
235 return $grade;
237 $hownear[ $value ] = abs( $grade - $value );
239 // reverse sort list of deltas and grab the last (smallest)
240 asort( $hownear, SORT_NUMERIC );
241 reset( $hownear );
242 return key( $hownear );
243 } else {
244 return false;
249 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
250 * @param integer $categoryid a question category id.
251 * @param boolean $recursive whether to check child categories too.
252 * @return boolean whether any question in this category is in use.
254 function question_category_isused($categoryid, $recursive = false) {
255 throw new coding_exception('question_category_isused has been deprectated. ' .
256 'Please use question_category_in_use instead.');
260 * Tests whether any question in a category is used by any part of Moodle.
262 * @param integer $categoryid a question category id.
263 * @param boolean $recursive whether to check child categories too.
264 * @return boolean whether any question in this category is in use.
266 function question_category_in_use($categoryid, $recursive = false) {
267 global $DB;
269 //Look at each question in the category
270 if ($questions = $DB->get_records_menu('question',
271 array('category' => $categoryid), '', 'id, 1')) {
272 if (questions_in_use(array_keys($questions))) {
273 return true;
276 if (!$recursive) {
277 return false;
280 //Look under child categories recursively
281 if ($children = $DB->get_records('question_categories',
282 array('parent' => $categoryid), '', 'id, 1')) {
283 foreach ($children as $child) {
284 if (question_category_in_use($child->id, $recursive)) {
285 return true;
290 return false;
294 * Deletes question and all associated data from the database
296 * It will not delete a question if it is used by an activity module
297 * @param object $question The question being deleted
299 function question_delete_question($questionid) {
300 global $DB;
302 $question = $DB->get_record_sql('
303 SELECT q.*, qc.contextid
304 FROM {question} q
305 JOIN {question_categories} qc ON qc.id = q.category
306 WHERE q.id = ?', array($questionid));
307 if (!$question) {
308 // In some situations, for example if this was a child of a
309 // Cloze question that was previously deleted, the question may already
310 // have gone. In this case, just do nothing.
311 return;
314 // Do not delete a question if it is used by an activity module
315 if (questions_in_use(array($questionid))) {
316 return;
319 // Check permissions.
320 question_require_capability_on($question, 'edit');
322 $dm = new question_engine_data_mapper();
323 $dm->delete_previews($questionid);
325 // delete questiontype-specific data
326 question_bank::get_qtype($question->qtype, false)->delete_question(
327 $questionid, $question->contextid);
329 // Now recursively delete all child questions
330 if ($children = $DB->get_records('question',
331 array('parent' => $questionid), '', 'id, qtype')) {
332 foreach ($children as $child) {
333 if ($child->id != $questionid) {
334 question_delete_question($child->id);
339 // Finally delete the question record itself
340 $DB->delete_records('question', array('id' => $questionid));
344 * All question categories and their questions are deleted for this course.
346 * @param stdClass $course an object representing the activity
347 * @param boolean $feedback to specify if the process must output a summary of its work
348 * @return boolean
350 function question_delete_course($course, $feedback=true) {
351 global $DB, $OUTPUT;
353 //To store feedback to be showed at the end of the process
354 $feedbackdata = array();
356 //Cache some strings
357 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
358 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
359 $categoriescourse = $DB->get_records('question_categories',
360 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
362 if ($categoriescourse) {
364 //Sort categories following their tree (parent-child) relationships
365 //this will make the feedback more readable
366 $categoriescourse = sort_categories_by_tree($categoriescourse);
368 foreach ($categoriescourse as $category) {
370 //Delete it completely (questions and category itself)
371 //deleting questions
372 if ($questions = $DB->get_records('question',
373 array('category' => $category->id), '', 'id,qtype')) {
374 foreach ($questions as $question) {
375 question_delete_question($question->id);
377 $DB->delete_records("question", array("category" => $category->id));
379 //delete the category
380 $DB->delete_records('question_categories', array('id' => $category->id));
382 //Fill feedback
383 $feedbackdata[] = array($category->name, $strcatdeleted);
385 //Inform about changes performed if feedback is enabled
386 if ($feedback) {
387 $table = new html_table();
388 $table->head = array(get_string('category', 'quiz'), get_string('action'));
389 $table->data = $feedbackdata;
390 echo html_writer::table($table);
393 return true;
397 * Category is about to be deleted,
398 * 1/ All question categories and their questions are deleted for this course category.
399 * 2/ All questions are moved to new category
401 * @param object $category course category object
402 * @param object $newcategory empty means everything deleted, otherwise id of
403 * category where content moved
404 * @param boolean $feedback to specify if the process must output a summary of its work
405 * @return boolean
407 function question_delete_course_category($category, $newcategory, $feedback=true) {
408 global $DB, $OUTPUT;
410 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
411 if (empty($newcategory)) {
412 $feedbackdata = array(); // To store feedback to be showed at the end of the process
413 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
414 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
416 // Loop over question categories.
417 if ($categories = $DB->get_records('question_categories',
418 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
419 foreach ($categories as $category) {
421 // Deal with any questions in the category.
422 if ($questions = $DB->get_records('question',
423 array('category' => $category->id), '', 'id,qtype')) {
425 // Try to delete each question.
426 foreach ($questions as $question) {
427 question_delete_question($question->id);
430 // Check to see if there were any questions that were kept because
431 // they are still in use somehow, even though quizzes in courses
432 // in this category will already have been deteted. This could
433 // happen, for example, if questions are added to a course,
434 // and then that course is moved to another category (MDL-14802).
435 $questionids = $DB->get_records_menu('question',
436 array('category'=>$category->id), '', 'id, 1');
437 if (!empty($questionids)) {
438 if (!$rescueqcategory = question_save_from_deletion(
439 array_keys($questionids), get_parent_contextid($context),
440 print_context_name($context), $rescueqcategory)) {
441 return false;
443 $feedbackdata[] = array($category->name,
444 get_string('questionsmovedto', 'question', $rescueqcategory->name));
448 // Now delete the category.
449 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
450 return false;
452 $feedbackdata[] = array($category->name, $strcatdeleted);
454 } // End loop over categories.
457 // Output feedback if requested.
458 if ($feedback and $feedbackdata) {
459 $table = new html_table();
460 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
461 $table->data = $feedbackdata;
462 echo html_writer::table($table);
465 } else {
466 // Move question categories ot the new context.
467 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
468 return false;
470 $DB->set_field('question_categories', 'contextid', $newcontext->id,
471 array('contextid'=>$context->id));
472 if ($feedback) {
473 $a = new stdClass();
474 $a->oldplace = print_context_name($context);
475 $a->newplace = print_context_name($newcontext);
476 echo $OUTPUT->notification(
477 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
481 return true;
485 * Enter description here...
487 * @param array $questionids of question ids
488 * @param object $newcontext the context to create the saved category in.
489 * @param string $oldplace a textual description of the think being deleted,
490 * e.g. from get_context_name
491 * @param object $newcategory
492 * @return mixed false on
494 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
495 $newcategory = null) {
496 global $DB;
498 // Make a category in the parent context to move the questions to.
499 if (is_null($newcategory)) {
500 $newcategory = new stdClass();
501 $newcategory->parent = 0;
502 $newcategory->contextid = $newcontextid;
503 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
504 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
505 $newcategory->sortorder = 999;
506 $newcategory->stamp = make_unique_id_code();
507 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
510 // Move any remaining questions to the 'saved' category.
511 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
512 return false;
514 return $newcategory;
518 * All question categories and their questions are deleted for this activity.
520 * @param object $cm the course module object representing the activity
521 * @param boolean $feedback to specify if the process must output a summary of its work
522 * @return boolean
524 function question_delete_activity($cm, $feedback=true) {
525 global $DB, $OUTPUT;
527 //To store feedback to be showed at the end of the process
528 $feedbackdata = array();
530 //Cache some strings
531 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
532 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
533 if ($categoriesmods = $DB->get_records('question_categories',
534 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
535 //Sort categories following their tree (parent-child) relationships
536 //this will make the feedback more readable
537 $categoriesmods = sort_categories_by_tree($categoriesmods);
539 foreach ($categoriesmods as $category) {
541 //Delete it completely (questions and category itself)
542 //deleting questions
543 if ($questions = $DB->get_records('question',
544 array('category' => $category->id), '', 'id,qtype')) {
545 foreach ($questions as $question) {
546 question_delete_question($question->id);
548 $DB->delete_records("question", array("category"=>$category->id));
550 //delete the category
551 $DB->delete_records('question_categories', array('id'=>$category->id));
553 //Fill feedback
554 $feedbackdata[] = array($category->name, $strcatdeleted);
556 //Inform about changes performed if feedback is enabled
557 if ($feedback) {
558 $table = new html_table();
559 $table->head = array(get_string('category', 'quiz'), get_string('action'));
560 $table->data = $feedbackdata;
561 echo html_writer::table($table);
564 return true;
568 * This function should be considered private to the question bank, it is called from
569 * question/editlib.php question/contextmoveq.php and a few similar places to to the
570 * work of acutally moving questions and associated data. However, callers of this
571 * function also have to do other work, which is why you should not call this method
572 * directly from outside the questionbank.
574 * @param array $questionids of question ids.
575 * @param integer $newcategoryid the id of the category to move to.
577 function question_move_questions_to_category($questionids, $newcategoryid) {
578 global $DB;
580 $newcontextid = $DB->get_field('question_categories', 'contextid',
581 array('id' => $newcategoryid));
582 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
583 $questions = $DB->get_records_sql("
584 SELECT q.id, q.qtype, qc.contextid
585 FROM {question} q
586 JOIN {question_categories} qc ON q.category = qc.id
587 WHERE q.id $questionidcondition", $params);
588 foreach ($questions as $question) {
589 if ($newcontextid != $question->contextid) {
590 question_bank::get_qtype($question->qtype)->move_files(
591 $question->id, $question->contextid, $newcontextid);
595 // Move the questions themselves.
596 $DB->set_field_select('question', 'category', $newcategoryid,
597 "id $questionidcondition", $params);
599 // Move any subquestions belonging to them.
600 $DB->set_field_select('question', 'category', $newcategoryid,
601 "parent $questionidcondition", $params);
603 // TODO Deal with datasets.
605 return true;
609 * This function helps move a question cateogry to a new context by moving all
610 * the files belonging to all the questions to the new context.
611 * Also moves subcategories.
612 * @param integer $categoryid the id of the category being moved.
613 * @param integer $oldcontextid the old context id.
614 * @param integer $newcontextid the new context id.
616 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
617 global $DB;
619 $questionids = $DB->get_records_menu('question',
620 array('category' => $categoryid), '', 'id,qtype');
621 foreach ($questionids as $questionid => $qtype) {
622 question_bank::get_qtype($qtype)->move_files(
623 $questionid, $oldcontextid, $newcontextid);
626 $subcatids = $DB->get_records_menu('question_categories',
627 array('parent' => $categoryid), '', 'id,1');
628 foreach ($subcatids as $subcatid => $notused) {
629 $DB->set_field('question_categories', 'contextid', $newcontextid,
630 array('id' => $subcatid));
631 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
636 * Generate the URL for starting a new preview of a given question with the given options.
637 * @param integer $questionid the question to preview.
638 * @param string $preferredbehaviour the behaviour to use for the preview.
639 * @param float $maxmark the maximum to mark the question out of.
640 * @param question_display_options $displayoptions the display options to use.
641 * @param int $variant the variant of the question to preview. If null, one will
642 * be picked randomly.
643 * @param object $context context to run the preview in (affects things like
644 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
645 * @return string the URL.
647 function question_preview_url($questionid, $preferredbehaviour = null,
648 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
650 $params = array('id' => $questionid);
652 if (is_null($context)) {
653 global $PAGE;
654 $context = $PAGE->context;
656 if ($context->contextlevel == CONTEXT_MODULE) {
657 $params['cmid'] = $context->instanceid;
658 } else if ($context->contextlevel == CONTEXT_COURSE) {
659 $params['courseid'] = $context->instanceid;
662 if (!is_null($preferredbehaviour)) {
663 $params['behaviour'] = $preferredbehaviour;
666 if (!is_null($maxmark)) {
667 $params['maxmark'] = $maxmark;
670 if (!is_null($displayoptions)) {
671 $params['correctness'] = $displayoptions->correctness;
672 $params['marks'] = $displayoptions->marks;
673 $params['markdp'] = $displayoptions->markdp;
674 $params['feedback'] = (bool) $displayoptions->feedback;
675 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
676 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
677 $params['history'] = (bool) $displayoptions->history;
680 if ($variant) {
681 $params['variant'] = $variant;
684 return new moodle_url('/question/preview.php', $params);
688 * @return array that can be passed as $params to the {@link popup_action} constructor.
690 function question_preview_popup_params() {
691 return array(
692 'height' => 600,
693 'width' => 800,
698 * Given a list of ids, load the basic information about a set of questions from
699 * the questions table. The $join and $extrafields arguments can be used together
700 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
701 * read the code below to see how the SQL is assembled. Throws exceptions on error.
703 * @global object
704 * @global object
705 * @param array $questionids array of question ids.
706 * @param string $extrafields extra SQL code to be added to the query.
707 * @param string $join extra SQL code to be added to the query.
708 * @param array $extraparams values for any placeholders in $join.
709 * You are strongly recommended to use named placeholder.
711 * @return array partially complete question objects. You need to call get_question_options
712 * on them before they can be properly used.
714 function question_preload_questions($questionids, $extrafields = '', $join = '',
715 $extraparams = array()) {
716 global $DB;
717 if (empty($questionids)) {
718 return array();
720 if ($join) {
721 $join = ' JOIN '.$join;
723 if ($extrafields) {
724 $extrafields = ', ' . $extrafields;
726 list($questionidcondition, $params) = $DB->get_in_or_equal(
727 $questionids, SQL_PARAMS_NAMED, 'qid0000');
728 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
729 JOIN {question_categories} qc ON q.category = qc.id' .
730 $join .
731 ' WHERE q.id ' . $questionidcondition;
733 // Load the questions
734 if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
735 return array();
738 foreach ($questions as $question) {
739 $question->_partiallyloaded = true;
742 // Note, a possible optimisation here would be to not load the TEXT fields
743 // (that is, questiontext and generalfeedback) here, and instead load them in
744 // question_load_questions. That would add one DB query, but reduce the amount
745 // of data transferred most of the time. I am not going to do this optimisation
746 // until it is shown to be worthwhile.
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;
783 if (!question_bank::is_qtype_installed($question->qtype)) {
784 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
785 'qtype_missingtype')) . $question->questiontext;
787 question_bank::get_qtype($question->qtype)->get_question_options($question);
788 if (isset($question->_partiallyloaded)) {
789 unset($question->_partiallyloaded);
791 if ($loadtags && !empty($CFG->usetags)) {
792 require_once($CFG->dirroot . '/tag/lib.php');
793 $question->tags = tag_get_tags_array('question', $question->id);
798 * Updates the question objects with question type specific
799 * information by calling {@link get_question_options()}
801 * Can be called either with an array of question objects or with a single
802 * question object.
804 * @param mixed $questions Either an array of question objects to be updated
805 * or just a single question object
806 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
807 * @return bool Indicates success or failure.
809 function get_question_options(&$questions, $loadtags = false) {
810 if (is_array($questions)) { // deal with an array of questions
811 foreach ($questions as $i => $notused) {
812 _tidy_question($questions[$i], $loadtags);
814 } else { // deal with single question
815 _tidy_question($questions, $loadtags);
817 return true;
821 * Print the icon for the question type
823 * @param object $question The question object for which the icon is required.
824 * Only $question->qtype is used.
825 * @return string the HTML for the img tag.
827 function print_question_icon($question) {
828 global $PAGE;
829 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
833 * Creates a stamp that uniquely identifies this version of the question
835 * In future we want this to use a hash of the question data to guarantee that
836 * identical versions have the same version stamp.
838 * @param object $question
839 * @return string A unique version stamp
841 function question_hash($question) {
842 return make_unique_id_code();
845 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
847 * Saves question options
849 * Simply calls the question type specific save_question_options() method.
851 function save_question_options($question) {
852 question_bank::get_qtype($question->qtype)->save_question_options($question);
855 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
858 * returns the categories with their names ordered following parent-child relationships
859 * finally it tries to return pending categories (those being orphaned, whose parent is
860 * incorrect) to avoid missing any category from original array.
862 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
863 global $DB;
865 $children = array();
866 $keys = array_keys($categories);
868 foreach ($keys as $key) {
869 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
870 $children[$key] = $categories[$key];
871 $categories[$key]->processed = true;
872 $children = $children + sort_categories_by_tree(
873 $categories, $children[$key]->id, $level+1);
876 //If level = 1, we have finished, try to look for non processed categories
877 // (bad parent) and sort them too
878 if ($level == 1) {
879 foreach ($keys as $key) {
880 // If not processed and it's a good candidate to start (because its
881 // parent doesn't exist in the course)
882 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
883 array('contextid' => $categories[$key]->contextid,
884 'id' => $categories[$key]->parent))) {
885 $children[$key] = $categories[$key];
886 $categories[$key]->processed = true;
887 $children = $children + sort_categories_by_tree(
888 $categories, $children[$key]->id, $level + 1);
892 return $children;
896 * Private method, only for the use of add_indented_names().
898 * Recursively adds an indentedname field to each category, starting with the category
899 * with id $id, and dealing with that category and all its children, and
900 * return a new array, with those categories in the right order.
902 * @param array $categories an array of categories which has had childids
903 * fields added by flatten_category_tree(). Passed by reference for
904 * performance only. It is not modfied.
905 * @param int $id the category to start the indenting process from.
906 * @param int $depth the indent depth. Used in recursive calls.
907 * @return array a new array of categories, in the right order for the tree.
909 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
911 // Indent the name of this category.
912 $newcategories = array();
913 $newcategories[$id] = $categories[$id];
914 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
915 $categories[$id]->name;
917 // Recursively indent the children.
918 foreach ($categories[$id]->childids as $childid) {
919 if ($childid != $nochildrenof) {
920 $newcategories = $newcategories + flatten_category_tree(
921 $categories, $childid, $depth + 1, $nochildrenof);
925 // Remove the childids array that were temporarily added.
926 unset($newcategories[$id]->childids);
928 return $newcategories;
932 * Format categories into an indented list reflecting the tree structure.
934 * @param array $categories An array of category objects, for example from the.
935 * @return array The formatted list of categories.
937 function add_indented_names($categories, $nochildrenof = -1) {
939 // Add an array to each category to hold the child category ids. This array
940 // will be removed again by flatten_category_tree(). It should not be used
941 // outside these two functions.
942 foreach (array_keys($categories) as $id) {
943 $categories[$id]->childids = array();
946 // Build the tree structure, and record which categories are top-level.
947 // We have to be careful, because the categories array may include published
948 // categories from other courses, but not their parents.
949 $toplevelcategoryids = array();
950 foreach (array_keys($categories) as $id) {
951 if (!empty($categories[$id]->parent) &&
952 array_key_exists($categories[$id]->parent, $categories)) {
953 $categories[$categories[$id]->parent]->childids[] = $id;
954 } else {
955 $toplevelcategoryids[] = $id;
959 // Flatten the tree to and add the indents.
960 $newcategories = array();
961 foreach ($toplevelcategoryids as $id) {
962 $newcategories = $newcategories + flatten_category_tree(
963 $categories, $id, 0, $nochildrenof);
966 return $newcategories;
970 * Output a select menu of question categories.
972 * Categories from this course and (optionally) published categories from other courses
973 * are included. Optionally, only categories the current user may edit can be included.
975 * @param integer $courseid the id of the course to get the categories for.
976 * @param integer $published if true, include publised categories from other courses.
977 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
978 * @param integer $selected optionally, the id of a category to be selected by
979 * default in the dropdown.
981 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
982 $selected = "", $nochildrenof = -1) {
983 global $OUTPUT;
984 $categoriesarray = question_category_options($contexts, $top, $currentcat,
985 false, $nochildrenof);
986 if ($selected) {
987 $choose = '';
988 } else {
989 $choose = 'choosedots';
991 $options = array();
992 foreach ($categoriesarray as $group => $opts) {
993 $options[] = array($group => $opts);
996 echo html_writer::select($options, 'category', $selected, $choose);
1000 * @param integer $contextid a context id.
1001 * @return object the default question category for that context, or false if none.
1003 function question_get_default_category($contextid) {
1004 global $DB;
1005 $category = $DB->get_records('question_categories',
1006 array('contextid' => $contextid), 'id', '*', 0, 1);
1007 if (!empty($category)) {
1008 return reset($category);
1009 } else {
1010 return false;
1015 * Gets the default category in the most specific context.
1016 * If no categories exist yet then default ones are created in all contexts.
1018 * @param array $contexts The context objects for this context and all parent contexts.
1019 * @return object The default category - the category in the course context
1021 function question_make_default_categories($contexts) {
1022 global $DB;
1023 static $preferredlevels = array(
1024 CONTEXT_COURSE => 4,
1025 CONTEXT_MODULE => 3,
1026 CONTEXT_COURSECAT => 2,
1027 CONTEXT_SYSTEM => 1,
1030 $toreturn = null;
1031 $preferredness = 0;
1032 // If it already exists, just return it.
1033 foreach ($contexts as $key => $context) {
1034 if (!$exists = $DB->record_exists("question_categories",
1035 array('contextid' => $context->id))) {
1036 // Otherwise, we need to make one
1037 $category = new stdClass();
1038 $contextname = print_context_name($context, false, true);
1039 $category->name = get_string('defaultfor', 'question', $contextname);
1040 $category->info = get_string('defaultinfofor', 'question', $contextname);
1041 $category->contextid = $context->id;
1042 $category->parent = 0;
1043 // By default, all categories get this number, and are sorted alphabetically.
1044 $category->sortorder = 999;
1045 $category->stamp = make_unique_id_code();
1046 $category->id = $DB->insert_record('question_categories', $category);
1047 } else {
1048 $category = question_get_default_category($context->id);
1050 $thispreferredness = $preferredlevels[$context->contextlevel];
1051 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1052 $thispreferredness += 10;
1054 if ($thispreferredness > $preferredness) {
1055 $toreturn = $category;
1056 $preferredness = $thispreferredness;
1060 if (!is_null($toreturn)) {
1061 $toreturn = clone($toreturn);
1063 return $toreturn;
1067 * Get all the category objects, including a count of the number of questions in that category,
1068 * for all the categories in the lists $contexts.
1070 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1071 * @param string $sortorder used as the ORDER BY clause in the select statement.
1072 * @return array of category objects.
1074 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1075 global $DB;
1076 return $DB->get_records_sql("
1077 SELECT c.*, (SELECT count(1) FROM {question} q
1078 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1079 FROM {question_categories} c
1080 WHERE c.contextid IN ($contexts)
1081 ORDER BY $sortorder");
1085 * Output an array of question categories.
1087 function question_category_options($contexts, $top = false, $currentcat = 0,
1088 $popupform = false, $nochildrenof = -1) {
1089 global $CFG;
1090 $pcontexts = array();
1091 foreach ($contexts as $context) {
1092 $pcontexts[] = $context->id;
1094 $contextslist = join($pcontexts, ', ');
1096 $categories = get_categories_for_contexts($contextslist);
1098 $categories = question_add_context_in_key($categories);
1100 if ($top) {
1101 $categories = question_add_tops($categories, $pcontexts);
1103 $categories = add_indented_names($categories, $nochildrenof);
1105 // sort cats out into different contexts
1106 $categoriesarray = array();
1107 foreach ($pcontexts as $pcontext) {
1108 $contextstring = print_context_name(
1109 get_context_instance_by_id($pcontext), true, true);
1110 foreach ($categories as $category) {
1111 if ($category->contextid == $pcontext) {
1112 $cid = $category->id;
1113 if ($currentcat != $cid || $currentcat == 0) {
1114 $countstring = !empty($category->questioncount) ?
1115 " ($category->questioncount)" : '';
1116 $categoriesarray[$contextstring][$cid] = $category->indentedname.$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 $subcategories = $DB->get_records('question_categories',
1168 array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
1170 $categorylist = array($categoryid);
1171 foreach ($subcategories as $subcategory) {
1172 $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
1175 return $categorylist;
1178 //===========================
1179 // Import/Export Functions
1180 //===========================
1183 * Get list of available import or export formats
1184 * @param string $type 'import' if import list, otherwise export list assumed
1185 * @return array sorted list of import/export formats available
1187 function get_import_export_formats($type) {
1188 global $CFG;
1189 require_once($CFG->dirroot . '/question/format.php');
1191 $formatclasses = get_plugin_list_with_class('qformat', '', 'format.php');
1193 $fileformatname = array();
1194 foreach ($formatclasses as $component => $formatclass) {
1196 $format = new $formatclass();
1197 if ($type == 'import') {
1198 $provided = $format->provide_import();
1199 } else {
1200 $provided = $format->provide_export();
1203 if ($provided) {
1204 list($notused, $fileformat) = explode('_', $component, 2);
1205 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1209 collatorlib::asort($fileformatnames);
1210 return $fileformatnames;
1215 * Create a reasonable default file name for exporting questions from a particular
1216 * category.
1217 * @param object $course the course the questions are in.
1218 * @param object $category the question category.
1219 * @return string the filename.
1221 function question_default_export_filename($course, $category) {
1222 // We build a string that is an appropriate name (questions) from the lang pack,
1223 // then the corse shortname, then the question category name, then a timestamp.
1225 $base = clean_filename(get_string('exportfilename', 'question'));
1227 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1228 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1230 $shortname = clean_filename($course->shortname);
1231 if ($shortname == '' || $shortname == '_' ) {
1232 $shortname = $course->id;
1235 $categoryname = clean_filename(format_string($category->name));
1237 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1239 return $export_name;
1243 * Converts contextlevels to strings and back to help with reading/writing contexts
1244 * to/from import/export files.
1246 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1249 class context_to_string_translator{
1251 * @var array used to translate between contextids and strings for this context.
1253 protected $contexttostringarray = array();
1255 public function __construct($contexts) {
1256 $this->generate_context_to_string_array($contexts);
1259 public function context_to_string($contextid) {
1260 return $this->contexttostringarray[$contextid];
1263 public function string_to_context($contextname) {
1264 $contextid = array_search($contextname, $this->contexttostringarray);
1265 return $contextid;
1268 protected function generate_context_to_string_array($contexts) {
1269 if (!$this->contexttostringarray) {
1270 $catno = 1;
1271 foreach ($contexts as $context) {
1272 switch ($context->contextlevel) {
1273 case CONTEXT_MODULE :
1274 $contextstring = 'module';
1275 break;
1276 case CONTEXT_COURSE :
1277 $contextstring = 'course';
1278 break;
1279 case CONTEXT_COURSECAT :
1280 $contextstring = "cat$catno";
1281 $catno++;
1282 break;
1283 case CONTEXT_SYSTEM :
1284 $contextstring = 'system';
1285 break;
1287 $this->contexttostringarray[$context->id] = $contextstring;
1295 * Check capability on category
1297 * @param mixed $question object or id
1298 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1299 * @param integer $cachecat useful to cache all question records in a category
1300 * @return boolean this user has the capability $cap for this question $question?
1302 function question_has_capability_on($question, $cap, $cachecat = -1) {
1303 global $USER, $DB;
1305 // these are capabilities on existing questions capabilties are
1306 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1307 $question_questioncaps = array('edit', 'view', 'use', 'move');
1308 static $questions = array();
1309 static $categories = array();
1310 static $cachedcat = array();
1311 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1312 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1313 $cachedcat[] = $cachecat;
1315 if (!is_object($question)) {
1316 if (!isset($questions[$question])) {
1317 if (!$questions[$question] = $DB->get_record('question',
1318 array('id' => $question), 'id,category,createdby')) {
1319 print_error('questiondoesnotexist', 'question');
1322 $question = $questions[$question];
1324 if (empty($question->category)) {
1325 // This can happen when we have created a fake 'missingtype' question to
1326 // take the place of a deleted question.
1327 return false;
1329 if (!isset($categories[$question->category])) {
1330 if (!$categories[$question->category] = $DB->get_record('question_categories',
1331 array('id'=>$question->category))) {
1332 print_error('invalidcategory', 'quiz');
1335 $category = $categories[$question->category];
1336 $context = get_context_instance_by_id($category->contextid);
1338 if (array_search($cap, $question_questioncaps)!== false) {
1339 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1340 if ($question->createdby == $USER->id) {
1341 return has_capability('moodle/question:' . $cap . 'mine', $context);
1342 } else {
1343 return false;
1345 } else {
1346 return true;
1348 } else {
1349 return has_capability('moodle/question:' . $cap, $context);
1355 * Require capability on question.
1357 function question_require_capability_on($question, $cap) {
1358 if (!question_has_capability_on($question, $cap)) {
1359 print_error('nopermissions', '', '', $cap);
1361 return true;
1365 * Get the real state - the correct question id and answer - for a random
1366 * question.
1367 * @param object $state with property answer.
1368 * @return mixed return integer real question id or false if there was an
1369 * error..
1371 function question_get_real_state($state) {
1372 global $OUTPUT;
1373 $realstate = clone($state);
1374 $matches = array();
1375 if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)) {
1376 echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics'));
1377 return false;
1378 } else {
1379 $realstate->question = $matches[1];
1380 $realstate->answer = $matches[2];
1381 return $realstate;
1386 * @param object $context a context
1387 * @return string A URL for editing questions in this context.
1389 function question_edit_url($context) {
1390 global $CFG, $SITE;
1391 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1392 return false;
1394 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1395 $defaultcategory = question_get_default_category($context->id);
1396 if ($defaultcategory) {
1397 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1399 switch ($context->contextlevel) {
1400 case CONTEXT_SYSTEM:
1401 return $baseurl . 'courseid=' . $SITE->id;
1402 case CONTEXT_COURSECAT:
1403 // This is nasty, becuase we can only edit questions in a course
1404 // context at the moment, so for now we just return false.
1405 return false;
1406 case CONTEXT_COURSE:
1407 return $baseurl . 'courseid=' . $context->instanceid;
1408 case CONTEXT_MODULE:
1409 return $baseurl . 'cmid=' . $context->instanceid;
1415 * Adds question bank setting links to the given navigation node if caps are met.
1417 * @param navigation_node $navigationnode The navigation node to add the question branch to
1418 * @param object $context
1419 * @return navigation_node Returns the question branch that was added
1421 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1422 global $PAGE;
1424 if ($context->contextlevel == CONTEXT_COURSE) {
1425 $params = array('courseid'=>$context->instanceid);
1426 } else if ($context->contextlevel == CONTEXT_MODULE) {
1427 $params = array('cmid'=>$context->instanceid);
1428 } else {
1429 return;
1432 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1433 $params['cat'] = $cat;
1436 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1437 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1439 $contexts = new question_edit_contexts($context);
1440 if ($contexts->have_one_edit_tab_cap('questions')) {
1441 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1442 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1444 if ($contexts->have_one_edit_tab_cap('categories')) {
1445 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1446 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1448 if ($contexts->have_one_edit_tab_cap('import')) {
1449 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1450 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1452 if ($contexts->have_one_edit_tab_cap('export')) {
1453 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1454 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1457 return $questionnode;
1461 * @return array all the capabilities that relate to accessing particular questions.
1463 function question_get_question_capabilities() {
1464 return array(
1465 'moodle/question:add',
1466 'moodle/question:editmine',
1467 'moodle/question:editall',
1468 'moodle/question:viewmine',
1469 'moodle/question:viewall',
1470 'moodle/question:usemine',
1471 'moodle/question:useall',
1472 'moodle/question:movemine',
1473 'moodle/question:moveall',
1478 * @return array all the question bank capabilities.
1480 function question_get_all_capabilities() {
1481 $caps = question_get_question_capabilities();
1482 $caps[] = 'moodle/question:managecategory';
1483 $caps[] = 'moodle/question:flag';
1484 return $caps;
1489 * Tracks all the contexts related to the one where we are currently editing
1490 * questions, and provides helper methods to check permissions.
1492 * @copyright 2007 Jamie Pratt me@jamiep.org
1493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1495 class question_edit_contexts {
1497 public static $caps = array(
1498 'editq' => array('moodle/question:add',
1499 'moodle/question:editmine',
1500 'moodle/question:editall',
1501 'moodle/question:viewmine',
1502 'moodle/question:viewall',
1503 'moodle/question:usemine',
1504 'moodle/question:useall',
1505 'moodle/question:movemine',
1506 'moodle/question:moveall'),
1507 'questions'=>array('moodle/question:add',
1508 'moodle/question:editmine',
1509 'moodle/question:editall',
1510 'moodle/question:viewmine',
1511 'moodle/question:viewall',
1512 'moodle/question:movemine',
1513 'moodle/question:moveall'),
1514 'categories'=>array('moodle/question:managecategory'),
1515 'import'=>array('moodle/question:add'),
1516 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1518 protected $allcontexts;
1521 * Constructor
1522 * @param context the current context.
1524 public function __construct(context $thiscontext) {
1525 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1529 * @return array all parent contexts
1531 public function all() {
1532 return $this->allcontexts;
1536 * @return object lowest context which must be either the module or course context
1538 public function lowest() {
1539 return $this->allcontexts[0];
1543 * @param string $cap capability
1544 * @return array parent contexts having capability, zero based index
1546 public function having_cap($cap) {
1547 $contextswithcap = array();
1548 foreach ($this->allcontexts as $context) {
1549 if (has_capability($cap, $context)) {
1550 $contextswithcap[] = $context;
1553 return $contextswithcap;
1557 * @param array $caps capabilities
1558 * @return array parent contexts having at least one of $caps, zero based index
1560 public function having_one_cap($caps) {
1561 $contextswithacap = array();
1562 foreach ($this->allcontexts as $context) {
1563 foreach ($caps as $cap) {
1564 if (has_capability($cap, $context)) {
1565 $contextswithacap[] = $context;
1566 break; //done with caps loop
1570 return $contextswithacap;
1574 * @param string $tabname edit tab name
1575 * @return array parent contexts having at least one of $caps, zero based index
1577 public function having_one_edit_tab_cap($tabname) {
1578 return $this->having_one_cap(self::$caps[$tabname]);
1582 * @return those contexts where a user can add a question and then use it.
1584 public function having_add_and_use() {
1585 $contextswithcap = array();
1586 foreach ($this->allcontexts as $context) {
1587 if (!has_capability('moodle/question:add', $context)) {
1588 continue;
1590 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1591 continue;
1593 $contextswithcap[] = $context;
1595 return $contextswithcap;
1599 * Has at least one parent context got the cap $cap?
1601 * @param string $cap capability
1602 * @return boolean
1604 public function have_cap($cap) {
1605 return (count($this->having_cap($cap)));
1609 * Has at least one parent context got one of the caps $caps?
1611 * @param array $caps capability
1612 * @return boolean
1614 public function have_one_cap($caps) {
1615 foreach ($caps as $cap) {
1616 if ($this->have_cap($cap)) {
1617 return true;
1620 return false;
1624 * Has at least one parent context got one of the caps for actions on $tabname
1626 * @param string $tabname edit tab name
1627 * @return boolean
1629 public function have_one_edit_tab_cap($tabname) {
1630 return $this->have_one_cap(self::$caps[$tabname]);
1634 * Throw error if at least one parent context hasn't got the cap $cap
1636 * @param string $cap capability
1638 public function require_cap($cap) {
1639 if (!$this->have_cap($cap)) {
1640 print_error('nopermissions', '', '', $cap);
1645 * Throw error if at least one parent context hasn't got one of the caps $caps
1647 * @param array $cap capabilities
1649 public function require_one_cap($caps) {
1650 if (!$this->have_one_cap($caps)) {
1651 $capsstring = join($caps, ', ');
1652 print_error('nopermissions', '', '', $capsstring);
1657 * Throw error if at least one parent context hasn't got one of the caps $caps
1659 * @param string $tabname edit tab name
1661 public function require_one_edit_tab_cap($tabname) {
1662 if (!$this->have_one_edit_tab_cap($tabname)) {
1663 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1670 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1672 * @package core_question
1673 * @category files
1674 * @param string $text text being processed
1675 * @param string $file the php script used to serve files
1676 * @param int $contextid context ID
1677 * @param string $component component
1678 * @param string $filearea filearea
1679 * @param array $ids other IDs will be used to check file permission
1680 * @param int $itemid item ID
1681 * @param array $options options
1682 * @return string
1684 function question_rewrite_question_urls($text, $file, $contextid, $component,
1685 $filearea, array $ids, $itemid, array $options=null) {
1687 $idsstr = '';
1688 if (!empty($ids)) {
1689 $idsstr .= implode('/', $ids);
1691 if ($itemid !== null) {
1692 $idsstr .= '/' . $itemid;
1694 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1695 $filearea, $idsstr, $options);
1699 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1700 * text outside and attempt (for example, in the question bank listing or in the
1701 * quiz statistics report).
1703 * @param string $questiontext the question text.
1704 * @param int $contextid the context the text is being displayed in.
1705 * @param string $component component
1706 * @param array $ids other IDs will be used to check file permission
1707 * @param array $options
1708 * @return string $questiontext with URLs rewritten.
1710 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1711 $component, $questionid, $options=null) {
1713 return file_rewrite_pluginfile_urls($questiontext, 'pluginfile.php', $contextid,
1714 'question', 'questiontext_preview', "$component/$questionid", $options);
1718 * Send a file from the question text of a question.
1719 * @param int $questionid the question id
1720 * @param array $args the remaining file arguments (file path).
1721 * @param bool $forcedownload whether the user must be forced to download the file.
1722 * @param array $options additional options affecting the file serving
1724 function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
1725 global $DB;
1727 $question = $DB->get_record_sql('
1728 SELECT q.id, qc.contextid
1729 FROM {question} q
1730 JOIN {question_categories} qc ON qc.id = q.category
1731 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1733 $fs = get_file_storage();
1734 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1735 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1736 send_file_not_found();
1739 send_stored_file($file, 0, 0, $forcedownload, $options);
1743 * Called by pluginfile.php to serve files related to the 'question' core
1744 * component and for files belonging to qtypes.
1746 * For files that relate to questions in a question_attempt, then we delegate to
1747 * a function in the component that owns the attempt (for example in the quiz,
1748 * or in core question preview) to get necessary inforation.
1750 * (Note that, at the moment, all question file areas relate to questions in
1751 * attempts, so the If at the start of the last paragraph is always true.)
1753 * Does not return, either calls send_file_not_found(); or serves the file.
1755 * @package core_question
1756 * @category files
1757 * @param stdClass $course course settings object
1758 * @param stdClass $context context object
1759 * @param string $component the name of the component we are serving files for.
1760 * @param string $filearea the name of the file area.
1761 * @param array $args the remaining bits of the file path.
1762 * @param bool $forcedownload whether the user must be forced to download the file.
1763 * @param array $options additional options affecting the file serving
1765 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1766 global $DB, $CFG;
1768 if ($filearea === 'questiontext_preview') {
1769 $component = array_shift($args);
1770 $questionid = array_shift($args);
1772 component_callback($component, 'questiontext_preview_pluginfile', array(
1773 $context, $questionid, $args, $forcedownload, $options));
1775 send_file_not_found();
1778 list($context, $course, $cm) = get_context_info_array($context->id);
1779 require_login($course, false, $cm);
1781 if ($filearea === 'export') {
1782 require_once($CFG->dirroot . '/question/editlib.php');
1783 $contexts = new question_edit_contexts($context);
1784 // check export capability
1785 $contexts->require_one_edit_tab_cap('export');
1786 $category_id = (int)array_shift($args);
1787 $format = array_shift($args);
1788 $cattofile = array_shift($args);
1789 $contexttofile = array_shift($args);
1790 $filename = array_shift($args);
1792 // load parent class for import/export
1793 require_once($CFG->dirroot . '/question/format.php');
1794 require_once($CFG->dirroot . '/question/editlib.php');
1795 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1797 $classname = 'qformat_' . $format;
1798 if (!class_exists($classname)) {
1799 send_file_not_found();
1802 $qformat = new $classname();
1804 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1805 send_file_not_found();
1808 $qformat->setCategory($category);
1809 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1810 $qformat->setCourse($course);
1812 if ($cattofile == 'withcategories') {
1813 $qformat->setCattofile(true);
1814 } else {
1815 $qformat->setCattofile(false);
1818 if ($contexttofile == 'withcontexts') {
1819 $qformat->setContexttofile(true);
1820 } else {
1821 $qformat->setContexttofile(false);
1824 if (!$qformat->exportpreprocess()) {
1825 send_file_not_found();
1826 print_error('exporterror', 'question', $thispageurl->out());
1829 // export data to moodle file pool
1830 if (!$content = $qformat->exportprocess(true)) {
1831 send_file_not_found();
1834 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1837 $qubaid = (int)array_shift($args);
1838 $slot = (int)array_shift($args);
1840 $module = $DB->get_field('question_usages', 'component',
1841 array('id' => $qubaid));
1843 if ($module === 'core_question_preview') {
1844 require_once($CFG->dirroot . '/question/previewlib.php');
1845 return question_preview_question_pluginfile($course, $context,
1846 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1848 } else {
1849 $dir = get_component_directory($module);
1850 if (!file_exists("$dir/lib.php")) {
1851 send_file_not_found();
1853 include_once("$dir/lib.php");
1855 $filefunction = $module . '_question_pluginfile';
1856 if (!function_exists($filefunction)) {
1857 send_file_not_found();
1860 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1861 $args, $forcedownload, $options);
1863 send_file_not_found();
1868 * Serve questiontext files in the question text when they are displayed in this report.
1870 * @package core_files
1871 * @category files
1872 * @param stdClass $context the context
1873 * @param int $questionid the question id
1874 * @param array $args remaining file args
1875 * @param bool $forcedownload
1876 * @param array $options additional options affecting the file serving
1878 function core_question_questiontext_preview_pluginfile($context, $questionid, $args, $forcedownload, array $options=array()) {
1879 global $DB;
1881 // Verify that contextid matches the question.
1882 $question = $DB->get_record_sql('
1883 SELECT q.*, qc.contextid
1884 FROM {question} q
1885 JOIN {question_categories} qc ON qc.id = q.category
1886 WHERE q.id = :id AND qc.contextid = :contextid',
1887 array('id' => $questionid, 'contextid' => $context->id), MUST_EXIST);
1889 // Check the capability.
1890 list($context, $course, $cm) = get_context_info_array($context->id);
1891 require_login($course, false, $cm);
1893 question_require_capability_on($question, 'use');
1895 question_send_questiontext_file($questionid, $args, $forcedownload, $options);
1899 * Create url for question export
1901 * @param int $contextid, current context
1902 * @param int $categoryid, categoryid
1903 * @param string $format
1904 * @param string $withcategories
1905 * @param string $ithcontexts
1906 * @param moodle_url export file url
1908 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1909 $withcontexts, $filename) {
1910 global $CFG;
1911 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1912 return moodle_url::make_file_url($urlbase,
1913 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1914 "/{$withcontexts}/{$filename}", true);
1918 * Return a list of page types
1919 * @param string $pagetype current page type
1920 * @param stdClass $parentcontext Block's parent context
1921 * @param stdClass $currentcontext Current context of block
1923 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1924 global $CFG;
1925 $types = array(
1926 'question-*'=>get_string('page-question-x', 'question'),
1927 'question-edit'=>get_string('page-question-edit', 'question'),
1928 'question-category'=>get_string('page-question-category', 'question'),
1929 'question-export'=>get_string('page-question-export', 'question'),
1930 'question-import'=>get_string('page-question-import', 'question')
1932 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1933 require_once($CFG->dirroot . '/course/lib.php');
1934 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1935 } else {
1936 return $types;