Merge branch 'MDL-35003_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / questionlib.php
blob1d472d58bfc036e377e9f3f911c30bba0356f654
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 * 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 // Now recursively delete all child questions
335 if ($children = $DB->get_records('question',
336 array('parent' => $questionid), '', 'id, qtype')) {
337 foreach ($children as $child) {
338 if ($child->id != $questionid) {
339 question_delete_question($child->id);
344 // Finally delete the question record itself
345 $DB->delete_records('question', array('id' => $questionid));
349 * All question categories and their questions are deleted for this course.
351 * @param stdClass $course an object representing the activity
352 * @param boolean $feedback to specify if the process must output a summary of its work
353 * @return boolean
355 function question_delete_course($course, $feedback=true) {
356 global $DB, $OUTPUT;
358 //To store feedback to be showed at the end of the process
359 $feedbackdata = array();
361 //Cache some strings
362 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
363 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
364 $categoriescourse = $DB->get_records('question_categories',
365 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
367 if ($categoriescourse) {
369 //Sort categories following their tree (parent-child) relationships
370 //this will make the feedback more readable
371 $categoriescourse = sort_categories_by_tree($categoriescourse);
373 foreach ($categoriescourse as $category) {
375 //Delete it completely (questions and category itself)
376 //deleting questions
377 if ($questions = $DB->get_records('question',
378 array('category' => $category->id), '', 'id,qtype')) {
379 foreach ($questions as $question) {
380 question_delete_question($question->id);
382 $DB->delete_records("question", array("category" => $category->id));
384 //delete the category
385 $DB->delete_records('question_categories', array('id' => $category->id));
387 //Fill feedback
388 $feedbackdata[] = array($category->name, $strcatdeleted);
390 //Inform about changes performed if feedback is enabled
391 if ($feedback) {
392 $table = new html_table();
393 $table->head = array(get_string('category', 'quiz'), get_string('action'));
394 $table->data = $feedbackdata;
395 echo html_writer::table($table);
398 return true;
402 * Category is about to be deleted,
403 * 1/ All question categories and their questions are deleted for this course category.
404 * 2/ All questions are moved to new category
406 * @param object $category course category object
407 * @param object $newcategory empty means everything deleted, otherwise id of
408 * category where content moved
409 * @param boolean $feedback to specify if the process must output a summary of its work
410 * @return boolean
412 function question_delete_course_category($category, $newcategory, $feedback=true) {
413 global $DB, $OUTPUT;
415 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
416 if (empty($newcategory)) {
417 $feedbackdata = array(); // To store feedback to be showed at the end of the process
418 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
419 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
421 // Loop over question categories.
422 if ($categories = $DB->get_records('question_categories',
423 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
424 foreach ($categories as $category) {
426 // Deal with any questions in the category.
427 if ($questions = $DB->get_records('question',
428 array('category' => $category->id), '', 'id,qtype')) {
430 // Try to delete each question.
431 foreach ($questions as $question) {
432 question_delete_question($question->id);
435 // Check to see if there were any questions that were kept because
436 // they are still in use somehow, even though quizzes in courses
437 // in this category will already have been deteted. This could
438 // happen, for example, if questions are added to a course,
439 // and then that course is moved to another category (MDL-14802).
440 $questionids = $DB->get_records_menu('question',
441 array('category'=>$category->id), '', 'id, 1');
442 if (!empty($questionids)) {
443 if (!$rescueqcategory = question_save_from_deletion(
444 array_keys($questionids), get_parent_contextid($context),
445 print_context_name($context), $rescueqcategory)) {
446 return false;
448 $feedbackdata[] = array($category->name,
449 get_string('questionsmovedto', 'question', $rescueqcategory->name));
453 // Now delete the category.
454 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
455 return false;
457 $feedbackdata[] = array($category->name, $strcatdeleted);
459 } // End loop over categories.
462 // Output feedback if requested.
463 if ($feedback and $feedbackdata) {
464 $table = new html_table();
465 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
466 $table->data = $feedbackdata;
467 echo html_writer::table($table);
470 } else {
471 // Move question categories ot the new context.
472 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
473 return false;
475 $DB->set_field('question_categories', 'contextid', $newcontext->id,
476 array('contextid'=>$context->id));
477 if ($feedback) {
478 $a = new stdClass();
479 $a->oldplace = print_context_name($context);
480 $a->newplace = print_context_name($newcontext);
481 echo $OUTPUT->notification(
482 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
486 return true;
490 * Enter description here...
492 * @param array $questionids of question ids
493 * @param object $newcontext the context to create the saved category in.
494 * @param string $oldplace a textual description of the think being deleted,
495 * e.g. from get_context_name
496 * @param object $newcategory
497 * @return mixed false on
499 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
500 $newcategory = null) {
501 global $DB;
503 // Make a category in the parent context to move the questions to.
504 if (is_null($newcategory)) {
505 $newcategory = new stdClass();
506 $newcategory->parent = 0;
507 $newcategory->contextid = $newcontextid;
508 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
509 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
510 $newcategory->sortorder = 999;
511 $newcategory->stamp = make_unique_id_code();
512 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
515 // Move any remaining questions to the 'saved' category.
516 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
517 return false;
519 return $newcategory;
523 * All question categories and their questions are deleted for this activity.
525 * @param object $cm the course module object representing the activity
526 * @param boolean $feedback to specify if the process must output a summary of its work
527 * @return boolean
529 function question_delete_activity($cm, $feedback=true) {
530 global $DB, $OUTPUT;
532 //To store feedback to be showed at the end of the process
533 $feedbackdata = array();
535 //Cache some strings
536 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
537 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
538 if ($categoriesmods = $DB->get_records('question_categories',
539 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
540 //Sort categories following their tree (parent-child) relationships
541 //this will make the feedback more readable
542 $categoriesmods = sort_categories_by_tree($categoriesmods);
544 foreach ($categoriesmods as $category) {
546 //Delete it completely (questions and category itself)
547 //deleting questions
548 if ($questions = $DB->get_records('question',
549 array('category' => $category->id), '', 'id,qtype')) {
550 foreach ($questions as $question) {
551 question_delete_question($question->id);
553 $DB->delete_records("question", array("category"=>$category->id));
555 //delete the category
556 $DB->delete_records('question_categories', array('id'=>$category->id));
558 //Fill feedback
559 $feedbackdata[] = array($category->name, $strcatdeleted);
561 //Inform about changes performed if feedback is enabled
562 if ($feedback) {
563 $table = new html_table();
564 $table->head = array(get_string('category', 'quiz'), get_string('action'));
565 $table->data = $feedbackdata;
566 echo html_writer::table($table);
569 return true;
573 * This function should be considered private to the question bank, it is called from
574 * question/editlib.php question/contextmoveq.php and a few similar places to to the
575 * work of acutally moving questions and associated data. However, callers of this
576 * function also have to do other work, which is why you should not call this method
577 * directly from outside the questionbank.
579 * @param array $questionids of question ids.
580 * @param integer $newcategoryid the id of the category to move to.
582 function question_move_questions_to_category($questionids, $newcategoryid) {
583 global $DB;
585 $newcontextid = $DB->get_field('question_categories', 'contextid',
586 array('id' => $newcategoryid));
587 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
588 $questions = $DB->get_records_sql("
589 SELECT q.id, q.qtype, qc.contextid
590 FROM {question} q
591 JOIN {question_categories} qc ON q.category = qc.id
592 WHERE q.id $questionidcondition", $params);
593 foreach ($questions as $question) {
594 if ($newcontextid != $question->contextid) {
595 question_bank::get_qtype($question->qtype)->move_files(
596 $question->id, $question->contextid, $newcontextid);
600 // Move the questions themselves.
601 $DB->set_field_select('question', 'category', $newcategoryid,
602 "id $questionidcondition", $params);
604 // Move any subquestions belonging to them.
605 $DB->set_field_select('question', 'category', $newcategoryid,
606 "parent $questionidcondition", $params);
608 // TODO Deal with datasets.
610 return true;
614 * This function helps move a question cateogry to a new context by moving all
615 * the files belonging to all the questions to the new context.
616 * Also moves subcategories.
617 * @param integer $categoryid the id of the category being moved.
618 * @param integer $oldcontextid the old context id.
619 * @param integer $newcontextid the new context id.
621 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
622 global $DB;
624 $questionids = $DB->get_records_menu('question',
625 array('category' => $categoryid), '', 'id,qtype');
626 foreach ($questionids as $questionid => $qtype) {
627 question_bank::get_qtype($qtype)->move_files(
628 $questionid, $oldcontextid, $newcontextid);
631 $subcatids = $DB->get_records_menu('question_categories',
632 array('parent' => $categoryid), '', 'id,1');
633 foreach ($subcatids as $subcatid => $notused) {
634 $DB->set_field('question_categories', 'contextid', $newcontextid,
635 array('id' => $subcatid));
636 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
641 * Generate the URL for starting a new preview of a given question with the given options.
642 * @param integer $questionid the question to preview.
643 * @param string $preferredbehaviour the behaviour to use for the preview.
644 * @param float $maxmark the maximum to mark the question out of.
645 * @param question_display_options $displayoptions the display options to use.
646 * @param int $variant the variant of the question to preview. If null, one will
647 * be picked randomly.
648 * @param object $context context to run the preview in (affects things like
649 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
650 * @return string the URL.
652 function question_preview_url($questionid, $preferredbehaviour = null,
653 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
655 $params = array('id' => $questionid);
657 if (is_null($context)) {
658 global $PAGE;
659 $context = $PAGE->context;
661 if ($context->contextlevel == CONTEXT_MODULE) {
662 $params['cmid'] = $context->instanceid;
663 } else if ($context->contextlevel == CONTEXT_COURSE) {
664 $params['courseid'] = $context->instanceid;
667 if (!is_null($preferredbehaviour)) {
668 $params['behaviour'] = $preferredbehaviour;
671 if (!is_null($maxmark)) {
672 $params['maxmark'] = $maxmark;
675 if (!is_null($displayoptions)) {
676 $params['correctness'] = $displayoptions->correctness;
677 $params['marks'] = $displayoptions->marks;
678 $params['markdp'] = $displayoptions->markdp;
679 $params['feedback'] = (bool) $displayoptions->feedback;
680 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
681 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
682 $params['history'] = (bool) $displayoptions->history;
685 if ($variant) {
686 $params['variant'] = $variant;
689 return new moodle_url('/question/preview.php', $params);
693 * @return array that can be passed as $params to the {@link popup_action} constructor.
695 function question_preview_popup_params() {
696 return array(
697 'height' => 600,
698 'width' => 800,
703 * Given a list of ids, load the basic information about a set of questions from
704 * the questions table. The $join and $extrafields arguments can be used together
705 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
706 * read the code below to see how the SQL is assembled. Throws exceptions on error.
708 * @global object
709 * @global object
710 * @param array $questionids array of question ids.
711 * @param string $extrafields extra SQL code to be added to the query.
712 * @param string $join extra SQL code to be added to the query.
713 * @param array $extraparams values for any placeholders in $join.
714 * You are strongly recommended to use named placeholder.
716 * @return array partially complete question objects. You need to call get_question_options
717 * on them before they can be properly used.
719 function question_preload_questions($questionids, $extrafields = '', $join = '',
720 $extraparams = array()) {
721 global $DB;
722 if (empty($questionids)) {
723 return array();
725 if ($join) {
726 $join = ' JOIN '.$join;
728 if ($extrafields) {
729 $extrafields = ', ' . $extrafields;
731 list($questionidcondition, $params) = $DB->get_in_or_equal(
732 $questionids, SQL_PARAMS_NAMED, 'qid0000');
733 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
734 JOIN {question_categories} qc ON q.category = qc.id' .
735 $join .
736 ' WHERE q.id ' . $questionidcondition;
738 // Load the questions
739 if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
740 return array();
743 foreach ($questions as $question) {
744 $question->_partiallyloaded = true;
747 // Note, a possible optimisation here would be to not load the TEXT fields
748 // (that is, questiontext and generalfeedback) here, and instead load them in
749 // question_load_questions. That would add one DB query, but reduce the amount
750 // of data transferred most of the time. I am not going to do this optimisation
751 // until it is shown to be worthwhile.
753 return $questions;
757 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
758 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
759 * read the code below to see how the SQL is assembled. Throws exceptions on error.
761 * @param array $questionids array of question ids.
762 * @param string $extrafields extra SQL code to be added to the query.
763 * @param string $join extra SQL code to be added to the query.
764 * @param array $extraparams values for any placeholders in $join.
765 * You are strongly recommended to use named placeholder.
767 * @return array question objects.
769 function question_load_questions($questionids, $extrafields = '', $join = '') {
770 $questions = question_preload_questions($questionids, $extrafields, $join);
772 // Load the question type specific information
773 if (!get_question_options($questions)) {
774 return 'Could not load the question options';
777 return $questions;
781 * Private function to factor common code out of get_question_options().
783 * @param object $question the question to tidy.
784 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
786 function _tidy_question($question, $loadtags = false) {
787 global $CFG;
788 if (!question_bank::is_qtype_installed($question->qtype)) {
789 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
790 'qtype_missingtype')) . $question->questiontext;
792 question_bank::get_qtype($question->qtype)->get_question_options($question);
793 if (isset($question->_partiallyloaded)) {
794 unset($question->_partiallyloaded);
796 if ($loadtags && !empty($CFG->usetags)) {
797 require_once($CFG->dirroot . '/tag/lib.php');
798 $question->tags = tag_get_tags_array('question', $question->id);
803 * Updates the question objects with question type specific
804 * information by calling {@link get_question_options()}
806 * Can be called either with an array of question objects or with a single
807 * question object.
809 * @param mixed $questions Either an array of question objects to be updated
810 * or just a single question object
811 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
812 * @return bool Indicates success or failure.
814 function get_question_options(&$questions, $loadtags = false) {
815 if (is_array($questions)) { // deal with an array of questions
816 foreach ($questions as $i => $notused) {
817 _tidy_question($questions[$i], $loadtags);
819 } else { // deal with single question
820 _tidy_question($questions, $loadtags);
822 return true;
826 * Print the icon for the question type
828 * @param object $question The question object for which the icon is required.
829 * Only $question->qtype is used.
830 * @return string the HTML for the img tag.
832 function print_question_icon($question) {
833 global $PAGE;
834 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
838 * Creates a stamp that uniquely identifies this version of the question
840 * In future we want this to use a hash of the question data to guarantee that
841 * identical versions have the same version stamp.
843 * @param object $question
844 * @return string A unique version stamp
846 function question_hash($question) {
847 return make_unique_id_code();
850 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
852 * Saves question options
854 * Simply calls the question type specific save_question_options() method.
856 function save_question_options($question) {
857 question_bank::get_qtype($question->qtype)->save_question_options($question);
860 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
863 * returns the categories with their names ordered following parent-child relationships
864 * finally it tries to return pending categories (those being orphaned, whose parent is
865 * incorrect) to avoid missing any category from original array.
867 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
868 global $DB;
870 $children = array();
871 $keys = array_keys($categories);
873 foreach ($keys as $key) {
874 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
875 $children[$key] = $categories[$key];
876 $categories[$key]->processed = true;
877 $children = $children + sort_categories_by_tree(
878 $categories, $children[$key]->id, $level+1);
881 //If level = 1, we have finished, try to look for non processed categories
882 // (bad parent) and sort them too
883 if ($level == 1) {
884 foreach ($keys as $key) {
885 // If not processed and it's a good candidate to start (because its
886 // parent doesn't exist in the course)
887 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
888 array('contextid' => $categories[$key]->contextid,
889 'id' => $categories[$key]->parent))) {
890 $children[$key] = $categories[$key];
891 $categories[$key]->processed = true;
892 $children = $children + sort_categories_by_tree(
893 $categories, $children[$key]->id, $level + 1);
897 return $children;
901 * Private method, only for the use of add_indented_names().
903 * Recursively adds an indentedname field to each category, starting with the category
904 * with id $id, and dealing with that category and all its children, and
905 * return a new array, with those categories in the right order.
907 * @param array $categories an array of categories which has had childids
908 * fields added by flatten_category_tree(). Passed by reference for
909 * performance only. It is not modfied.
910 * @param int $id the category to start the indenting process from.
911 * @param int $depth the indent depth. Used in recursive calls.
912 * @return array a new array of categories, in the right order for the tree.
914 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
916 // Indent the name of this category.
917 $newcategories = array();
918 $newcategories[$id] = $categories[$id];
919 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
920 $categories[$id]->name;
922 // Recursively indent the children.
923 foreach ($categories[$id]->childids as $childid) {
924 if ($childid != $nochildrenof) {
925 $newcategories = $newcategories + flatten_category_tree(
926 $categories, $childid, $depth + 1, $nochildrenof);
930 // Remove the childids array that were temporarily added.
931 unset($newcategories[$id]->childids);
933 return $newcategories;
937 * Format categories into an indented list reflecting the tree structure.
939 * @param array $categories An array of category objects, for example from the.
940 * @return array The formatted list of categories.
942 function add_indented_names($categories, $nochildrenof = -1) {
944 // Add an array to each category to hold the child category ids. This array
945 // will be removed again by flatten_category_tree(). It should not be used
946 // outside these two functions.
947 foreach (array_keys($categories) as $id) {
948 $categories[$id]->childids = array();
951 // Build the tree structure, and record which categories are top-level.
952 // We have to be careful, because the categories array may include published
953 // categories from other courses, but not their parents.
954 $toplevelcategoryids = array();
955 foreach (array_keys($categories) as $id) {
956 if (!empty($categories[$id]->parent) &&
957 array_key_exists($categories[$id]->parent, $categories)) {
958 $categories[$categories[$id]->parent]->childids[] = $id;
959 } else {
960 $toplevelcategoryids[] = $id;
964 // Flatten the tree to and add the indents.
965 $newcategories = array();
966 foreach ($toplevelcategoryids as $id) {
967 $newcategories = $newcategories + flatten_category_tree(
968 $categories, $id, 0, $nochildrenof);
971 return $newcategories;
975 * Output a select menu of question categories.
977 * Categories from this course and (optionally) published categories from other courses
978 * are included. Optionally, only categories the current user may edit can be included.
980 * @param integer $courseid the id of the course to get the categories for.
981 * @param integer $published if true, include publised categories from other courses.
982 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
983 * @param integer $selected optionally, the id of a category to be selected by
984 * default in the dropdown.
986 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
987 $selected = "", $nochildrenof = -1) {
988 global $OUTPUT;
989 $categoriesarray = question_category_options($contexts, $top, $currentcat,
990 false, $nochildrenof);
991 if ($selected) {
992 $choose = '';
993 } else {
994 $choose = 'choosedots';
996 $options = array();
997 foreach ($categoriesarray as $group => $opts) {
998 $options[] = array($group => $opts);
1000 echo html_writer::label($selected, 'menucategory', false, array('class' => 'accesshide'));
1001 echo html_writer::select($options, 'category', $selected, $choose);
1005 * @param integer $contextid a context id.
1006 * @return object the default question category for that context, or false if none.
1008 function question_get_default_category($contextid) {
1009 global $DB;
1010 $category = $DB->get_records('question_categories',
1011 array('contextid' => $contextid), 'id', '*', 0, 1);
1012 if (!empty($category)) {
1013 return reset($category);
1014 } else {
1015 return false;
1020 * Gets the default category in the most specific context.
1021 * If no categories exist yet then default ones are created in all contexts.
1023 * @param array $contexts The context objects for this context and all parent contexts.
1024 * @return object The default category - the category in the course context
1026 function question_make_default_categories($contexts) {
1027 global $DB;
1028 static $preferredlevels = array(
1029 CONTEXT_COURSE => 4,
1030 CONTEXT_MODULE => 3,
1031 CONTEXT_COURSECAT => 2,
1032 CONTEXT_SYSTEM => 1,
1035 $toreturn = null;
1036 $preferredness = 0;
1037 // If it already exists, just return it.
1038 foreach ($contexts as $key => $context) {
1039 if (!$exists = $DB->record_exists("question_categories",
1040 array('contextid' => $context->id))) {
1041 // Otherwise, we need to make one
1042 $category = new stdClass();
1043 $contextname = print_context_name($context, false, true);
1044 $category->name = get_string('defaultfor', 'question', $contextname);
1045 $category->info = get_string('defaultinfofor', 'question', $contextname);
1046 $category->contextid = $context->id;
1047 $category->parent = 0;
1048 // By default, all categories get this number, and are sorted alphabetically.
1049 $category->sortorder = 999;
1050 $category->stamp = make_unique_id_code();
1051 $category->id = $DB->insert_record('question_categories', $category);
1052 } else {
1053 $category = question_get_default_category($context->id);
1055 $thispreferredness = $preferredlevels[$context->contextlevel];
1056 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1057 $thispreferredness += 10;
1059 if ($thispreferredness > $preferredness) {
1060 $toreturn = $category;
1061 $preferredness = $thispreferredness;
1065 if (!is_null($toreturn)) {
1066 $toreturn = clone($toreturn);
1068 return $toreturn;
1072 * Get all the category objects, including a count of the number of questions in that category,
1073 * for all the categories in the lists $contexts.
1075 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1076 * @param string $sortorder used as the ORDER BY clause in the select statement.
1077 * @return array of category objects.
1079 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1080 global $DB;
1081 return $DB->get_records_sql("
1082 SELECT c.*, (SELECT count(1) FROM {question} q
1083 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1084 FROM {question_categories} c
1085 WHERE c.contextid IN ($contexts)
1086 ORDER BY $sortorder");
1090 * Output an array of question categories.
1092 function question_category_options($contexts, $top = false, $currentcat = 0,
1093 $popupform = false, $nochildrenof = -1) {
1094 global $CFG;
1095 $pcontexts = array();
1096 foreach ($contexts as $context) {
1097 $pcontexts[] = $context->id;
1099 $contextslist = join($pcontexts, ', ');
1101 $categories = get_categories_for_contexts($contextslist);
1103 $categories = question_add_context_in_key($categories);
1105 if ($top) {
1106 $categories = question_add_tops($categories, $pcontexts);
1108 $categories = add_indented_names($categories, $nochildrenof);
1110 // sort cats out into different contexts
1111 $categoriesarray = array();
1112 foreach ($pcontexts as $pcontext) {
1113 $contextstring = print_context_name(
1114 get_context_instance_by_id($pcontext), true, true);
1115 foreach ($categories as $category) {
1116 if ($category->contextid == $pcontext) {
1117 $cid = $category->id;
1118 if ($currentcat != $cid || $currentcat == 0) {
1119 $countstring = !empty($category->questioncount) ?
1120 " ($category->questioncount)" : '';
1121 $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
1126 if ($popupform) {
1127 $popupcats = array();
1128 foreach ($categoriesarray as $contextstring => $optgroup) {
1129 $group = array();
1130 foreach ($optgroup as $key => $value) {
1131 $key = str_replace($CFG->wwwroot, '', $key);
1132 $group[$key] = $value;
1134 $popupcats[] = array($contextstring => $group);
1136 return $popupcats;
1137 } else {
1138 return $categoriesarray;
1142 function question_add_context_in_key($categories) {
1143 $newcatarray = array();
1144 foreach ($categories as $id => $category) {
1145 $category->parent = "$category->parent,$category->contextid";
1146 $category->id = "$category->id,$category->contextid";
1147 $newcatarray["$id,$category->contextid"] = $category;
1149 return $newcatarray;
1152 function question_add_tops($categories, $pcontexts) {
1153 $topcats = array();
1154 foreach ($pcontexts as $context) {
1155 $newcat = new stdClass();
1156 $newcat->id = "0,$context";
1157 $newcat->name = get_string('top');
1158 $newcat->parent = -1;
1159 $newcat->contextid = $context;
1160 $topcats["0,$context"] = $newcat;
1162 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1163 return array_merge($topcats, $categories);
1167 * @return array of question category ids of the category and all subcategories.
1169 function question_categorylist($categoryid) {
1170 global $DB;
1172 $subcategories = $DB->get_records('question_categories',
1173 array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
1175 $categorylist = array($categoryid);
1176 foreach ($subcategories as $subcategory) {
1177 $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
1180 return $categorylist;
1183 //===========================
1184 // Import/Export Functions
1185 //===========================
1188 * Get list of available import or export formats
1189 * @param string $type 'import' if import list, otherwise export list assumed
1190 * @return array sorted list of import/export formats available
1192 function get_import_export_formats($type) {
1193 global $CFG;
1194 require_once($CFG->dirroot . '/question/format.php');
1196 $formatclasses = get_plugin_list_with_class('qformat', '', 'format.php');
1198 $fileformatname = array();
1199 foreach ($formatclasses as $component => $formatclass) {
1201 $format = new $formatclass();
1202 if ($type == 'import') {
1203 $provided = $format->provide_import();
1204 } else {
1205 $provided = $format->provide_export();
1208 if ($provided) {
1209 list($notused, $fileformat) = explode('_', $component, 2);
1210 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1214 collatorlib::asort($fileformatnames);
1215 return $fileformatnames;
1220 * Create a reasonable default file name for exporting questions from a particular
1221 * category.
1222 * @param object $course the course the questions are in.
1223 * @param object $category the question category.
1224 * @return string the filename.
1226 function question_default_export_filename($course, $category) {
1227 // We build a string that is an appropriate name (questions) from the lang pack,
1228 // then the corse shortname, then the question category name, then a timestamp.
1230 $base = clean_filename(get_string('exportfilename', 'question'));
1232 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1233 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1235 $shortname = clean_filename($course->shortname);
1236 if ($shortname == '' || $shortname == '_' ) {
1237 $shortname = $course->id;
1240 $categoryname = clean_filename(format_string($category->name));
1242 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1244 return $export_name;
1248 * Converts contextlevels to strings and back to help with reading/writing contexts
1249 * to/from import/export files.
1251 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1254 class context_to_string_translator{
1256 * @var array used to translate between contextids and strings for this context.
1258 protected $contexttostringarray = array();
1260 public function __construct($contexts) {
1261 $this->generate_context_to_string_array($contexts);
1264 public function context_to_string($contextid) {
1265 return $this->contexttostringarray[$contextid];
1268 public function string_to_context($contextname) {
1269 $contextid = array_search($contextname, $this->contexttostringarray);
1270 return $contextid;
1273 protected function generate_context_to_string_array($contexts) {
1274 if (!$this->contexttostringarray) {
1275 $catno = 1;
1276 foreach ($contexts as $context) {
1277 switch ($context->contextlevel) {
1278 case CONTEXT_MODULE :
1279 $contextstring = 'module';
1280 break;
1281 case CONTEXT_COURSE :
1282 $contextstring = 'course';
1283 break;
1284 case CONTEXT_COURSECAT :
1285 $contextstring = "cat$catno";
1286 $catno++;
1287 break;
1288 case CONTEXT_SYSTEM :
1289 $contextstring = 'system';
1290 break;
1292 $this->contexttostringarray[$context->id] = $contextstring;
1300 * Check capability on category
1302 * @param mixed $question object or id
1303 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1304 * @param integer $cachecat useful to cache all question records in a category
1305 * @return boolean this user has the capability $cap for this question $question?
1307 function question_has_capability_on($question, $cap, $cachecat = -1) {
1308 global $USER, $DB;
1310 // these are capabilities on existing questions capabilties are
1311 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1312 $question_questioncaps = array('edit', 'view', 'use', 'move');
1313 static $questions = array();
1314 static $categories = array();
1315 static $cachedcat = array();
1316 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1317 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1318 $cachedcat[] = $cachecat;
1320 if (!is_object($question)) {
1321 if (!isset($questions[$question])) {
1322 if (!$questions[$question] = $DB->get_record('question',
1323 array('id' => $question), 'id,category,createdby')) {
1324 print_error('questiondoesnotexist', 'question');
1327 $question = $questions[$question];
1329 if (empty($question->category)) {
1330 // This can happen when we have created a fake 'missingtype' question to
1331 // take the place of a deleted question.
1332 return false;
1334 if (!isset($categories[$question->category])) {
1335 if (!$categories[$question->category] = $DB->get_record('question_categories',
1336 array('id'=>$question->category))) {
1337 print_error('invalidcategory', 'quiz');
1340 $category = $categories[$question->category];
1341 $context = get_context_instance_by_id($category->contextid);
1343 if (array_search($cap, $question_questioncaps)!== false) {
1344 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1345 if ($question->createdby == $USER->id) {
1346 return has_capability('moodle/question:' . $cap . 'mine', $context);
1347 } else {
1348 return false;
1350 } else {
1351 return true;
1353 } else {
1354 return has_capability('moodle/question:' . $cap, $context);
1360 * Require capability on question.
1362 function question_require_capability_on($question, $cap) {
1363 if (!question_has_capability_on($question, $cap)) {
1364 print_error('nopermissions', '', '', $cap);
1366 return true;
1370 * Get the real state - the correct question id and answer - for a random
1371 * question.
1372 * @param object $state with property answer.
1373 * @return mixed return integer real question id or false if there was an
1374 * error..
1376 function question_get_real_state($state) {
1377 global $OUTPUT;
1378 $realstate = clone($state);
1379 $matches = array();
1380 if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)) {
1381 echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics'));
1382 return false;
1383 } else {
1384 $realstate->question = $matches[1];
1385 $realstate->answer = $matches[2];
1386 return $realstate;
1391 * @param object $context a context
1392 * @return string A URL for editing questions in this context.
1394 function question_edit_url($context) {
1395 global $CFG, $SITE;
1396 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1397 return false;
1399 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1400 $defaultcategory = question_get_default_category($context->id);
1401 if ($defaultcategory) {
1402 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1404 switch ($context->contextlevel) {
1405 case CONTEXT_SYSTEM:
1406 return $baseurl . 'courseid=' . $SITE->id;
1407 case CONTEXT_COURSECAT:
1408 // This is nasty, becuase we can only edit questions in a course
1409 // context at the moment, so for now we just return false.
1410 return false;
1411 case CONTEXT_COURSE:
1412 return $baseurl . 'courseid=' . $context->instanceid;
1413 case CONTEXT_MODULE:
1414 return $baseurl . 'cmid=' . $context->instanceid;
1420 * Adds question bank setting links to the given navigation node if caps are met.
1422 * @param navigation_node $navigationnode The navigation node to add the question branch to
1423 * @param object $context
1424 * @return navigation_node Returns the question branch that was added
1426 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1427 global $PAGE;
1429 if ($context->contextlevel == CONTEXT_COURSE) {
1430 $params = array('courseid'=>$context->instanceid);
1431 } else if ($context->contextlevel == CONTEXT_MODULE) {
1432 $params = array('cmid'=>$context->instanceid);
1433 } else {
1434 return;
1437 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1438 $params['cat'] = $cat;
1441 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1442 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1444 $contexts = new question_edit_contexts($context);
1445 if ($contexts->have_one_edit_tab_cap('questions')) {
1446 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1447 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1449 if ($contexts->have_one_edit_tab_cap('categories')) {
1450 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1451 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1453 if ($contexts->have_one_edit_tab_cap('import')) {
1454 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1455 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1457 if ($contexts->have_one_edit_tab_cap('export')) {
1458 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1459 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1462 return $questionnode;
1466 * @return array all the capabilities that relate to accessing particular questions.
1468 function question_get_question_capabilities() {
1469 return array(
1470 'moodle/question:add',
1471 'moodle/question:editmine',
1472 'moodle/question:editall',
1473 'moodle/question:viewmine',
1474 'moodle/question:viewall',
1475 'moodle/question:usemine',
1476 'moodle/question:useall',
1477 'moodle/question:movemine',
1478 'moodle/question:moveall',
1483 * @return array all the question bank capabilities.
1485 function question_get_all_capabilities() {
1486 $caps = question_get_question_capabilities();
1487 $caps[] = 'moodle/question:managecategory';
1488 $caps[] = 'moodle/question:flag';
1489 return $caps;
1494 * Tracks all the contexts related to the one where we are currently editing
1495 * questions, and provides helper methods to check permissions.
1497 * @copyright 2007 Jamie Pratt me@jamiep.org
1498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1500 class question_edit_contexts {
1502 public static $caps = array(
1503 'editq' => array('moodle/question:add',
1504 'moodle/question:editmine',
1505 'moodle/question:editall',
1506 'moodle/question:viewmine',
1507 'moodle/question:viewall',
1508 'moodle/question:usemine',
1509 'moodle/question:useall',
1510 'moodle/question:movemine',
1511 'moodle/question:moveall'),
1512 'questions'=>array('moodle/question:add',
1513 'moodle/question:editmine',
1514 'moodle/question:editall',
1515 'moodle/question:viewmine',
1516 'moodle/question:viewall',
1517 'moodle/question:movemine',
1518 'moodle/question:moveall'),
1519 'categories'=>array('moodle/question:managecategory'),
1520 'import'=>array('moodle/question:add'),
1521 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1523 protected $allcontexts;
1526 * Constructor
1527 * @param context the current context.
1529 public function __construct(context $thiscontext) {
1530 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1534 * @return array all parent contexts
1536 public function all() {
1537 return $this->allcontexts;
1541 * @return object lowest context which must be either the module or course context
1543 public function lowest() {
1544 return $this->allcontexts[0];
1548 * @param string $cap capability
1549 * @return array parent contexts having capability, zero based index
1551 public function having_cap($cap) {
1552 $contextswithcap = array();
1553 foreach ($this->allcontexts as $context) {
1554 if (has_capability($cap, $context)) {
1555 $contextswithcap[] = $context;
1558 return $contextswithcap;
1562 * @param array $caps capabilities
1563 * @return array parent contexts having at least one of $caps, zero based index
1565 public function having_one_cap($caps) {
1566 $contextswithacap = array();
1567 foreach ($this->allcontexts as $context) {
1568 foreach ($caps as $cap) {
1569 if (has_capability($cap, $context)) {
1570 $contextswithacap[] = $context;
1571 break; //done with caps loop
1575 return $contextswithacap;
1579 * @param string $tabname edit tab name
1580 * @return array parent contexts having at least one of $caps, zero based index
1582 public function having_one_edit_tab_cap($tabname) {
1583 return $this->having_one_cap(self::$caps[$tabname]);
1587 * @return those contexts where a user can add a question and then use it.
1589 public function having_add_and_use() {
1590 $contextswithcap = array();
1591 foreach ($this->allcontexts as $context) {
1592 if (!has_capability('moodle/question:add', $context)) {
1593 continue;
1595 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1596 continue;
1598 $contextswithcap[] = $context;
1600 return $contextswithcap;
1604 * Has at least one parent context got the cap $cap?
1606 * @param string $cap capability
1607 * @return boolean
1609 public function have_cap($cap) {
1610 return (count($this->having_cap($cap)));
1614 * Has at least one parent context got one of the caps $caps?
1616 * @param array $caps capability
1617 * @return boolean
1619 public function have_one_cap($caps) {
1620 foreach ($caps as $cap) {
1621 if ($this->have_cap($cap)) {
1622 return true;
1625 return false;
1629 * Has at least one parent context got one of the caps for actions on $tabname
1631 * @param string $tabname edit tab name
1632 * @return boolean
1634 public function have_one_edit_tab_cap($tabname) {
1635 return $this->have_one_cap(self::$caps[$tabname]);
1639 * Throw error if at least one parent context hasn't got the cap $cap
1641 * @param string $cap capability
1643 public function require_cap($cap) {
1644 if (!$this->have_cap($cap)) {
1645 print_error('nopermissions', '', '', $cap);
1650 * Throw error if at least one parent context hasn't got one of the caps $caps
1652 * @param array $cap capabilities
1654 public function require_one_cap($caps) {
1655 if (!$this->have_one_cap($caps)) {
1656 $capsstring = join($caps, ', ');
1657 print_error('nopermissions', '', '', $capsstring);
1662 * Throw error if at least one parent context hasn't got one of the caps $caps
1664 * @param string $tabname edit tab name
1666 public function require_one_edit_tab_cap($tabname) {
1667 if (!$this->have_one_edit_tab_cap($tabname)) {
1668 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1675 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1677 * @param string $text text being processed
1678 * @param string $file the php script used to serve files
1679 * @param int $contextid
1680 * @param string $component component
1681 * @param string $filearea filearea
1682 * @param array $ids other IDs will be used to check file permission
1683 * @param int $itemid
1684 * @param array $options
1685 * @return string
1687 function question_rewrite_question_urls($text, $file, $contextid, $component,
1688 $filearea, array $ids, $itemid, array $options=null) {
1690 $idsstr = '';
1691 if (!empty($ids)) {
1692 $idsstr .= implode('/', $ids);
1694 if ($itemid !== null) {
1695 $idsstr .= '/' . $itemid;
1697 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1698 $filearea, $idsstr, $options);
1702 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1703 * text outside and attempt (for example, in the question bank listing or in the
1704 * quiz statistics report).
1706 * @param string $questiontext the question text.
1707 * @param int $contextid the context the text is being displayed in.
1708 * @param string $component component
1709 * @param array $ids other IDs will be used to check file permission
1710 * @param array $options
1711 * @return string $questiontext with URLs rewritten.
1713 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1714 $component, $questionid, $options=null) {
1716 return file_rewrite_pluginfile_urls($questiontext, 'pluginfile.php', $contextid,
1717 'question', 'questiontext_preview', "$component/$questionid", $options);
1721 * Send a file from the question text of a question.
1722 * @param int $questionid the question id
1723 * @param array $args the remaining file arguments (file path).
1724 * @param bool $forcedownload whether the user must be forced to download the file.
1726 function question_send_questiontext_file($questionid, $args, $forcedownload) {
1727 global $DB;
1729 $question = $DB->get_record_sql('
1730 SELECT q.id, qc.contextid
1731 FROM {question} q
1732 JOIN {question_categories} qc ON qc.id = q.category
1733 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1735 $fs = get_file_storage();
1736 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1737 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1738 send_file_not_found();
1741 send_stored_file($file, 0, 0, $forcedownload);
1745 * Called by pluginfile.php to serve files related to the 'question' core
1746 * component and for files belonging to qtypes.
1748 * For files that relate to questions in a question_attempt, then we delegate to
1749 * a function in the component that owns the attempt (for example in the quiz,
1750 * or in core question preview) to get necessary inforation.
1752 * (Note that, at the moment, all question file areas relate to questions in
1753 * attempts, so the If at the start of the last paragraph is always true.)
1755 * Does not return, either calls send_file_not_found(); or serves the file.
1757 * @param object $course course settings object
1758 * @param object $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.
1764 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload) {
1765 global $DB, $CFG;
1767 if ($filearea === 'questiontext_preview') {
1768 $component = array_shift($args);
1769 $questionid = array_shift($args);
1771 component_callback($component, 'questiontext_preview_pluginfile', array(
1772 $context, $questionid, $args, $forcedownload));
1774 send_file_not_found();
1777 list($context, $course, $cm) = get_context_info_array($context->id);
1778 require_login($course, false, $cm);
1780 if ($filearea === 'export') {
1781 require_once($CFG->dirroot . '/question/editlib.php');
1782 $contexts = new question_edit_contexts($context);
1783 // check export capability
1784 $contexts->require_one_edit_tab_cap('export');
1785 $category_id = (int)array_shift($args);
1786 $format = array_shift($args);
1787 $cattofile = array_shift($args);
1788 $contexttofile = array_shift($args);
1789 $filename = array_shift($args);
1791 // load parent class for import/export
1792 require_once($CFG->dirroot . '/question/format.php');
1793 require_once($CFG->dirroot . '/question/editlib.php');
1794 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1796 $classname = 'qformat_' . $format;
1797 if (!class_exists($classname)) {
1798 send_file_not_found();
1801 $qformat = new $classname();
1803 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1804 send_file_not_found();
1807 $qformat->setCategory($category);
1808 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1809 $qformat->setCourse($course);
1811 if ($cattofile == 'withcategories') {
1812 $qformat->setCattofile(true);
1813 } else {
1814 $qformat->setCattofile(false);
1817 if ($contexttofile == 'withcontexts') {
1818 $qformat->setContexttofile(true);
1819 } else {
1820 $qformat->setContexttofile(false);
1823 if (!$qformat->exportpreprocess()) {
1824 send_file_not_found();
1825 print_error('exporterror', 'question', $thispageurl->out());
1828 // export data to moodle file pool
1829 if (!$content = $qformat->exportprocess(true)) {
1830 send_file_not_found();
1833 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1836 $qubaid = (int)array_shift($args);
1837 $slot = (int)array_shift($args);
1839 $module = $DB->get_field('question_usages', 'component',
1840 array('id' => $qubaid));
1842 if ($module === 'core_question_preview') {
1843 require_once($CFG->dirroot . '/question/previewlib.php');
1844 return question_preview_question_pluginfile($course, $context,
1845 $component, $filearea, $qubaid, $slot, $args, $forcedownload);
1847 } else {
1848 $dir = get_component_directory($module);
1849 if (!file_exists("$dir/lib.php")) {
1850 send_file_not_found();
1852 include_once("$dir/lib.php");
1854 $filefunction = $module . '_question_pluginfile';
1855 if (!function_exists($filefunction)) {
1856 send_file_not_found();
1859 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1860 $args, $forcedownload);
1862 send_file_not_found();
1867 * Serve questiontext files in the question text when they are displayed in this report.
1868 * @param context $context the context
1869 * @param int $questionid the question id
1870 * @param array $args remaining file args
1871 * @param bool $forcedownload
1873 function core_question_questiontext_preview_pluginfile($context, $questionid, $args, $forcedownload) {
1874 global $DB;
1876 // Verify that contextid matches the question.
1877 $question = $DB->get_record_sql('
1878 SELECT q.*, qc.contextid
1879 FROM {question} q
1880 JOIN {question_categories} qc ON qc.id = q.category
1881 WHERE q.id = :id AND qc.contextid = :contextid',
1882 array('id' => $questionid, 'contextid' => $context->id), MUST_EXIST);
1884 // Check the capability.
1885 list($context, $course, $cm) = get_context_info_array($context->id);
1886 require_login($course, false, $cm);
1888 question_require_capability_on($question, 'use');
1890 question_send_questiontext_file($questionid, $args, $forcedownload);
1894 * Create url for question export
1896 * @param int $contextid, current context
1897 * @param int $categoryid, categoryid
1898 * @param string $format
1899 * @param string $withcategories
1900 * @param string $ithcontexts
1901 * @param moodle_url export file url
1903 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1904 $withcontexts, $filename) {
1905 global $CFG;
1906 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1907 return moodle_url::make_file_url($urlbase,
1908 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1909 "/{$withcontexts}/{$filename}", true);
1913 * Return a list of page types
1914 * @param string $pagetype current page type
1915 * @param stdClass $parentcontext Block's parent context
1916 * @param stdClass $currentcontext Current context of block
1918 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1919 global $CFG;
1920 $types = array(
1921 'question-*'=>get_string('page-question-x', 'question'),
1922 'question-edit'=>get_string('page-question-edit', 'question'),
1923 'question-category'=>get_string('page-question-category', 'question'),
1924 'question-export'=>get_string('page-question-export', 'question'),
1925 'question-import'=>get_string('page-question-import', 'question')
1927 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1928 require_once($CFG->dirroot . '/course/lib.php');
1929 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1930 } else {
1931 return $types;