2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * 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) {
137 if (question_engine
::questions_in_use($questionids)) {
141 foreach (core_component
::get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
146 $fn = $module . '_questions_in_use';
147 if (function_exists($fn)) {
148 if ($fn($questionids)) {
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)) {
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
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) {
181 if (is_object($context)) {
182 $contextid = $context->id
;
183 } else if (is_numeric($context)) {
184 $contextid = $context;
186 print_error('invalidcontextinhasanyquestions', 'question');
188 return $DB->record_exists_sql("SELECT *
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();
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.
233 } else if ($matchgrades == 'nearest') {
234 // Work out nearest value
237 foreach ($gradeoptionsfull as $value => $option) {
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
241 $bestmismatch = $newmismatch;
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) {
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))) {
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)) {
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) {
307 $question = $DB->get_record_sql('
308 SELECT q.*, qc.contextid
310 JOIN {question_categories} qc ON qc.id = q.category
311 WHERE q.id = ?', array($questionid));
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.
319 // Do not delete a question if it is used by an activity module
320 if (questions_in_use(array($questionid))) {
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));
346 question_bank
::notify_question_edited($questionid);
350 * All question categories and their questions are deleted for this course.
352 * @param stdClass $course an object representing the activity
353 * @param boolean $feedback to specify if the process must output a summary of its work
356 function question_delete_course($course, $feedback=true) {
359 //To store feedback to be showed at the end of the process
360 $feedbackdata = array();
363 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
364 $coursecontext = context_course
::instance($course->id
);
365 $categoriescourse = $DB->get_records('question_categories',
366 array('contextid' => $coursecontext->id
), 'parent', 'id, parent, name, contextid');
368 if ($categoriescourse) {
370 //Sort categories following their tree (parent-child) relationships
371 //this will make the feedback more readable
372 $categoriescourse = sort_categories_by_tree($categoriescourse);
374 foreach ($categoriescourse as $category) {
376 //Delete it completely (questions and category itself)
378 if ($questions = $DB->get_records('question',
379 array('category' => $category->id
), '', 'id,qtype')) {
380 foreach ($questions as $question) {
381 question_delete_question($question->id
);
383 $DB->delete_records("question", array("category" => $category->id
));
385 //delete the category
386 $DB->delete_records('question_categories', array('id' => $category->id
));
389 $feedbackdata[] = array($category->name
, $strcatdeleted);
391 //Inform about changes performed if feedback is enabled
393 $table = new html_table();
394 $table->head
= array(get_string('category', 'quiz'), get_string('action'));
395 $table->data
= $feedbackdata;
396 echo html_writer
::table($table);
403 * Category is about to be deleted,
404 * 1/ All question categories and their questions are deleted for this course category.
405 * 2/ All questions are moved to new category
407 * @param object|coursecat $category course category object
408 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
409 * category where content moved
410 * @param boolean $feedback to specify if the process must output a summary of its work
413 function question_delete_course_category($category, $newcategory, $feedback=true) {
416 $context = context_coursecat
::instance($category->id
);
417 if (empty($newcategory)) {
418 $feedbackdata = array(); // To store feedback to be showed at the end of the process
419 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
420 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
422 // Loop over question categories.
423 if ($categories = $DB->get_records('question_categories',
424 array('contextid'=>$context->id
), 'parent', 'id, parent, name')) {
425 foreach ($categories as $category) {
427 // Deal with any questions in the category.
428 if ($questions = $DB->get_records('question',
429 array('category' => $category->id
), '', 'id,qtype')) {
431 // Try to delete each question.
432 foreach ($questions as $question) {
433 question_delete_question($question->id
);
436 // Check to see if there were any questions that were kept because
437 // they are still in use somehow, even though quizzes in courses
438 // in this category will already have been deteted. This could
439 // happen, for example, if questions are added to a course,
440 // and then that course is moved to another category (MDL-14802).
441 $questionids = $DB->get_records_menu('question',
442 array('category'=>$category->id
), '', 'id, 1');
443 if (!empty($questionids)) {
444 $parentcontextid = false;
445 $parentcontext = $context->get_parent_context();
446 if ($parentcontext) {
447 $parentcontextid = $parentcontext->id
;
449 if (!$rescueqcategory = question_save_from_deletion(
450 array_keys($questionids), $parentcontextid,
451 $context->get_context_name(), $rescueqcategory)) {
454 $feedbackdata[] = array($category->name
,
455 get_string('questionsmovedto', 'question', $rescueqcategory->name
));
459 // Now delete the category.
460 if (!$DB->delete_records('question_categories', array('id'=>$category->id
))) {
463 $feedbackdata[] = array($category->name
, $strcatdeleted);
465 } // End loop over categories.
468 // Output feedback if requested.
469 if ($feedback and $feedbackdata) {
470 $table = new html_table();
471 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
472 $table->data
= $feedbackdata;
473 echo html_writer
::table($table);
477 // Move question categories ot the new context.
478 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
481 $DB->set_field('question_categories', 'contextid', $newcontext->id
,
482 array('contextid'=>$context->id
));
485 $a->oldplace
= $context->get_context_name();
486 $a->newplace
= $newcontext->get_context_name();
487 echo $OUTPUT->notification(
488 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
496 * Enter description here...
498 * @param array $questionids of question ids
499 * @param object $newcontext the context to create the saved category in.
500 * @param string $oldplace a textual description of the think being deleted,
501 * e.g. from get_context_name
502 * @param object $newcategory
503 * @return mixed false on
505 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
506 $newcategory = null) {
509 // Make a category in the parent context to move the questions to.
510 if (is_null($newcategory)) {
511 $newcategory = new stdClass();
512 $newcategory->parent
= 0;
513 $newcategory->contextid
= $newcontextid;
514 $newcategory->name
= get_string('questionsrescuedfrom', 'question', $oldplace);
515 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
516 $newcategory->sortorder
= 999;
517 $newcategory->stamp
= make_unique_id_code();
518 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
521 // Move any remaining questions to the 'saved' category.
522 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
529 * All question categories and their questions are deleted for this activity.
531 * @param object $cm the course module object representing the activity
532 * @param boolean $feedback to specify if the process must output a summary of its work
535 function question_delete_activity($cm, $feedback=true) {
538 //To store feedback to be showed at the end of the process
539 $feedbackdata = array();
542 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
543 $modcontext = context_module
::instance($cm->id
);
544 if ($categoriesmods = $DB->get_records('question_categories',
545 array('contextid' => $modcontext->id
), 'parent', 'id, parent, name, contextid')) {
546 //Sort categories following their tree (parent-child) relationships
547 //this will make the feedback more readable
548 $categoriesmods = sort_categories_by_tree($categoriesmods);
550 foreach ($categoriesmods as $category) {
552 //Delete it completely (questions and category itself)
554 if ($questions = $DB->get_records('question',
555 array('category' => $category->id
), '', 'id,qtype')) {
556 foreach ($questions as $question) {
557 question_delete_question($question->id
);
559 $DB->delete_records("question", array("category"=>$category->id
));
561 //delete the category
562 $DB->delete_records('question_categories', array('id'=>$category->id
));
565 $feedbackdata[] = array($category->name
, $strcatdeleted);
567 //Inform about changes performed if feedback is enabled
569 $table = new html_table();
570 $table->head
= array(get_string('category', 'quiz'), get_string('action'));
571 $table->data
= $feedbackdata;
572 echo html_writer
::table($table);
579 * This function should be considered private to the question bank, it is called from
580 * question/editlib.php question/contextmoveq.php and a few similar places to to the
581 * work of acutally moving questions and associated data. However, callers of this
582 * function also have to do other work, which is why you should not call this method
583 * directly from outside the questionbank.
585 * @param array $questionids of question ids.
586 * @param integer $newcategoryid the id of the category to move to.
588 function question_move_questions_to_category($questionids, $newcategoryid) {
591 $newcontextid = $DB->get_field('question_categories', 'contextid',
592 array('id' => $newcategoryid));
593 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
594 $questions = $DB->get_records_sql("
595 SELECT q.id, q.qtype, qc.contextid
597 JOIN {question_categories} qc ON q.category = qc.id
598 WHERE q.id $questionidcondition", $params);
599 foreach ($questions as $question) {
600 if ($newcontextid != $question->contextid
) {
601 question_bank
::get_qtype($question->qtype
)->move_files(
602 $question->id
, $question->contextid
, $newcontextid);
606 // Move the questions themselves.
607 $DB->set_field_select('question', 'category', $newcategoryid,
608 "id $questionidcondition", $params);
610 // Move any subquestions belonging to them.
611 $DB->set_field_select('question', 'category', $newcategoryid,
612 "parent $questionidcondition", $params);
614 // TODO Deal with datasets.
616 // Purge these questions from the cache.
617 foreach ($questions as $question) {
618 question_bank
::notify_question_edited($question->id
);
625 * This function helps move a question cateogry to a new context by moving all
626 * the files belonging to all the questions to the new context.
627 * Also moves subcategories.
628 * @param integer $categoryid the id of the category being moved.
629 * @param integer $oldcontextid the old context id.
630 * @param integer $newcontextid the new context id.
632 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
635 $questionids = $DB->get_records_menu('question',
636 array('category' => $categoryid), '', 'id,qtype');
637 foreach ($questionids as $questionid => $qtype) {
638 question_bank
::get_qtype($qtype)->move_files(
639 $questionid, $oldcontextid, $newcontextid);
640 // Purge this question from the cache.
641 question_bank
::notify_question_edited($questionid);
644 $subcatids = $DB->get_records_menu('question_categories',
645 array('parent' => $categoryid), '', 'id,1');
646 foreach ($subcatids as $subcatid => $notused) {
647 $DB->set_field('question_categories', 'contextid', $newcontextid,
648 array('id' => $subcatid));
649 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
654 * Generate the URL for starting a new preview of a given question with the given options.
655 * @param integer $questionid the question to preview.
656 * @param string $preferredbehaviour the behaviour to use for the preview.
657 * @param float $maxmark the maximum to mark the question out of.
658 * @param question_display_options $displayoptions the display options to use.
659 * @param int $variant the variant of the question to preview. If null, one will
660 * be picked randomly.
661 * @param object $context context to run the preview in (affects things like
662 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
663 * @return string the URL.
665 function question_preview_url($questionid, $preferredbehaviour = null,
666 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
668 $params = array('id' => $questionid);
670 if (is_null($context)) {
672 $context = $PAGE->context
;
674 if ($context->contextlevel
== CONTEXT_MODULE
) {
675 $params['cmid'] = $context->instanceid
;
676 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
677 $params['courseid'] = $context->instanceid
;
680 if (!is_null($preferredbehaviour)) {
681 $params['behaviour'] = $preferredbehaviour;
684 if (!is_null($maxmark)) {
685 $params['maxmark'] = $maxmark;
688 if (!is_null($displayoptions)) {
689 $params['correctness'] = $displayoptions->correctness
;
690 $params['marks'] = $displayoptions->marks
;
691 $params['markdp'] = $displayoptions->markdp
;
692 $params['feedback'] = (bool) $displayoptions->feedback
;
693 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
694 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
695 $params['history'] = (bool) $displayoptions->history
;
699 $params['variant'] = $variant;
702 return new moodle_url('/question/preview.php', $params);
706 * @return array that can be passed as $params to the {@link popup_action} constructor.
708 function question_preview_popup_params() {
716 * Given a list of ids, load the basic information about a set of questions from
717 * the questions table. The $join and $extrafields arguments can be used together
718 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
719 * read the code below to see how the SQL is assembled. Throws exceptions on error.
723 * @param array $questionids array of question ids.
724 * @param string $extrafields extra SQL code to be added to the query.
725 * @param string $join extra SQL code to be added to the query.
726 * @param array $extraparams values for any placeholders in $join.
727 * You are strongly recommended to use named placeholder.
729 * @return array partially complete question objects. You need to call get_question_options
730 * on them before they can be properly used.
732 function question_preload_questions($questionids, $extrafields = '', $join = '',
733 $extraparams = array()) {
735 if (empty($questionids)) {
739 $join = ' JOIN '.$join;
742 $extrafields = ', ' . $extrafields;
744 list($questionidcondition, $params) = $DB->get_in_or_equal(
745 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
746 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
747 JOIN {question_categories} qc ON q.category = qc.id' .
749 ' WHERE q.id ' . $questionidcondition;
751 // Load the questions
752 if (!$questions = $DB->get_records_sql($sql, $extraparams +
$params)) {
756 foreach ($questions as $question) {
757 $question->_partiallyloaded
= true;
760 // Note, a possible optimisation here would be to not load the TEXT fields
761 // (that is, questiontext and generalfeedback) here, and instead load them in
762 // question_load_questions. That would add one DB query, but reduce the amount
763 // of data transferred most of the time. I am not going to do this optimisation
764 // until it is shown to be worthwhile.
770 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
771 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
772 * read the code below to see how the SQL is assembled. Throws exceptions on error.
774 * @param array $questionids array of question ids.
775 * @param string $extrafields extra SQL code to be added to the query.
776 * @param string $join extra SQL code to be added to the query.
777 * @param array $extraparams values for any placeholders in $join.
778 * You are strongly recommended to use named placeholder.
780 * @return array question objects.
782 function question_load_questions($questionids, $extrafields = '', $join = '') {
783 $questions = question_preload_questions($questionids, $extrafields, $join);
785 // Load the question type specific information
786 if (!get_question_options($questions)) {
787 return 'Could not load the question options';
794 * Private function to factor common code out of get_question_options().
796 * @param object $question the question to tidy.
797 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
799 function _tidy_question($question, $loadtags = false) {
802 // Load question-type specific fields.
803 if (!question_bank
::is_qtype_installed($question->qtype
)) {
804 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
805 'qtype_missingtype')) . $question->questiontext
;
807 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
809 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
810 $question->defaultmark +
= 0;
811 $question->penalty +
= 0;
813 if (isset($question->_partiallyloaded
)) {
814 unset($question->_partiallyloaded
);
817 if ($loadtags && !empty($CFG->usetags
)) {
818 require_once($CFG->dirroot
. '/tag/lib.php');
819 $question->tags
= tag_get_tags_array('question', $question->id
);
824 * Updates the question objects with question type specific
825 * information by calling {@link get_question_options()}
827 * Can be called either with an array of question objects or with a single
830 * @param mixed $questions Either an array of question objects to be updated
831 * or just a single question object
832 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
833 * @return bool Indicates success or failure.
835 function get_question_options(&$questions, $loadtags = false) {
836 if (is_array($questions)) { // deal with an array of questions
837 foreach ($questions as $i => $notused) {
838 _tidy_question($questions[$i], $loadtags);
840 } else { // deal with single question
841 _tidy_question($questions, $loadtags);
847 * Print the icon for the question type
849 * @param object $question The question object for which the icon is required.
850 * Only $question->qtype is used.
851 * @return string the HTML for the img tag.
853 function print_question_icon($question) {
855 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
859 * Creates a stamp that uniquely identifies this version of the question
861 * In future we want this to use a hash of the question data to guarantee that
862 * identical versions have the same version stamp.
864 * @param object $question
865 * @return string A unique version stamp
867 function question_hash($question) {
868 return make_unique_id_code();
871 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
873 * Saves question options
875 * Simply calls the question type specific save_question_options() method.
876 * @deprecated all code should now call the question type method directly.
878 function save_question_options($question) {
879 debugging('Please do not call save_question_options any more. Call the question type method directly.',
881 question_bank
::get_qtype($question->qtype
)->save_question_options($question);
884 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
887 * returns the categories with their names ordered following parent-child relationships
888 * finally it tries to return pending categories (those being orphaned, whose parent is
889 * incorrect) to avoid missing any category from original array.
891 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
895 $keys = array_keys($categories);
897 foreach ($keys as $key) {
898 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
899 $children[$key] = $categories[$key];
900 $categories[$key]->processed
= true;
901 $children = $children +
sort_categories_by_tree(
902 $categories, $children[$key]->id
, $level+
1);
905 //If level = 1, we have finished, try to look for non processed categories
906 // (bad parent) and sort them too
908 foreach ($keys as $key) {
909 // If not processed and it's a good candidate to start (because its
910 // parent doesn't exist in the course)
911 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
912 array('contextid' => $categories[$key]->contextid
,
913 'id' => $categories[$key]->parent
))) {
914 $children[$key] = $categories[$key];
915 $categories[$key]->processed
= true;
916 $children = $children +
sort_categories_by_tree(
917 $categories, $children[$key]->id
, $level +
1);
925 * Private method, only for the use of add_indented_names().
927 * Recursively adds an indentedname field to each category, starting with the category
928 * with id $id, and dealing with that category and all its children, and
929 * return a new array, with those categories in the right order.
931 * @param array $categories an array of categories which has had childids
932 * fields added by flatten_category_tree(). Passed by reference for
933 * performance only. It is not modfied.
934 * @param int $id the category to start the indenting process from.
935 * @param int $depth the indent depth. Used in recursive calls.
936 * @return array a new array of categories, in the right order for the tree.
938 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
940 // Indent the name of this category.
941 $newcategories = array();
942 $newcategories[$id] = $categories[$id];
943 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
944 $categories[$id]->name
;
946 // Recursively indent the children.
947 foreach ($categories[$id]->childids
as $childid) {
948 if ($childid != $nochildrenof) {
949 $newcategories = $newcategories +
flatten_category_tree(
950 $categories, $childid, $depth +
1, $nochildrenof);
954 // Remove the childids array that were temporarily added.
955 unset($newcategories[$id]->childids
);
957 return $newcategories;
961 * Format categories into an indented list reflecting the tree structure.
963 * @param array $categories An array of category objects, for example from the.
964 * @return array The formatted list of categories.
966 function add_indented_names($categories, $nochildrenof = -1) {
968 // Add an array to each category to hold the child category ids. This array
969 // will be removed again by flatten_category_tree(). It should not be used
970 // outside these two functions.
971 foreach (array_keys($categories) as $id) {
972 $categories[$id]->childids
= array();
975 // Build the tree structure, and record which categories are top-level.
976 // We have to be careful, because the categories array may include published
977 // categories from other courses, but not their parents.
978 $toplevelcategoryids = array();
979 foreach (array_keys($categories) as $id) {
980 if (!empty($categories[$id]->parent
) &&
981 array_key_exists($categories[$id]->parent
, $categories)) {
982 $categories[$categories[$id]->parent
]->childids
[] = $id;
984 $toplevelcategoryids[] = $id;
988 // Flatten the tree to and add the indents.
989 $newcategories = array();
990 foreach ($toplevelcategoryids as $id) {
991 $newcategories = $newcategories +
flatten_category_tree(
992 $categories, $id, 0, $nochildrenof);
995 return $newcategories;
999 * Output a select menu of question categories.
1001 * Categories from this course and (optionally) published categories from other courses
1002 * are included. Optionally, only categories the current user may edit can be included.
1004 * @param integer $courseid the id of the course to get the categories for.
1005 * @param integer $published if true, include publised categories from other courses.
1006 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1007 * @param integer $selected optionally, the id of a category to be selected by
1008 * default in the dropdown.
1010 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1011 $selected = "", $nochildrenof = -1) {
1013 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1014 false, $nochildrenof);
1018 $choose = 'choosedots';
1021 foreach ($categoriesarray as $group => $opts) {
1022 $options[] = array($group => $opts);
1024 echo html_writer
::label($selected, 'menucategory', false, array('class' => 'accesshide'));
1025 echo html_writer
::select($options, 'category', $selected, $choose);
1029 * @param integer $contextid a context id.
1030 * @return object the default question category for that context, or false if none.
1032 function question_get_default_category($contextid) {
1034 $category = $DB->get_records('question_categories',
1035 array('contextid' => $contextid), 'id', '*', 0, 1);
1036 if (!empty($category)) {
1037 return reset($category);
1044 * Gets the default category in the most specific context.
1045 * If no categories exist yet then default ones are created in all contexts.
1047 * @param array $contexts The context objects for this context and all parent contexts.
1048 * @return object The default category - the category in the course context
1050 function question_make_default_categories($contexts) {
1052 static $preferredlevels = array(
1053 CONTEXT_COURSE
=> 4,
1054 CONTEXT_MODULE
=> 3,
1055 CONTEXT_COURSECAT
=> 2,
1056 CONTEXT_SYSTEM
=> 1,
1061 // If it already exists, just return it.
1062 foreach ($contexts as $key => $context) {
1063 if (!$exists = $DB->record_exists("question_categories",
1064 array('contextid' => $context->id
))) {
1065 // Otherwise, we need to make one
1066 $category = new stdClass();
1067 $contextname = $context->get_context_name(false, true);
1068 $category->name
= get_string('defaultfor', 'question', $contextname);
1069 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1070 $category->contextid
= $context->id
;
1071 $category->parent
= 0;
1072 // By default, all categories get this number, and are sorted alphabetically.
1073 $category->sortorder
= 999;
1074 $category->stamp
= make_unique_id_code();
1075 $category->id
= $DB->insert_record('question_categories', $category);
1077 $category = question_get_default_category($context->id
);
1079 $thispreferredness = $preferredlevels[$context->contextlevel
];
1080 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1081 $thispreferredness +
= 10;
1083 if ($thispreferredness > $preferredness) {
1084 $toreturn = $category;
1085 $preferredness = $thispreferredness;
1089 if (!is_null($toreturn)) {
1090 $toreturn = clone($toreturn);
1096 * Get all the category objects, including a count of the number of questions in that category,
1097 * for all the categories in the lists $contexts.
1099 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1100 * @param string $sortorder used as the ORDER BY clause in the select statement.
1101 * @return array of category objects.
1103 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1105 return $DB->get_records_sql("
1106 SELECT c.*, (SELECT count(1) FROM {question} q
1107 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1108 FROM {question_categories} c
1109 WHERE c.contextid IN ($contexts)
1110 ORDER BY $sortorder");
1114 * Output an array of question categories.
1116 function question_category_options($contexts, $top = false, $currentcat = 0,
1117 $popupform = false, $nochildrenof = -1) {
1119 $pcontexts = array();
1120 foreach ($contexts as $context) {
1121 $pcontexts[] = $context->id
;
1123 $contextslist = join($pcontexts, ', ');
1125 $categories = get_categories_for_contexts($contextslist);
1127 $categories = question_add_context_in_key($categories);
1130 $categories = question_add_tops($categories, $pcontexts);
1132 $categories = add_indented_names($categories, $nochildrenof);
1134 // sort cats out into different contexts
1135 $categoriesarray = array();
1136 foreach ($pcontexts as $contextid) {
1137 $context = context
::instance_by_id($contextid);
1138 $contextstring = $context->get_context_name(true, true);
1139 foreach ($categories as $category) {
1140 if ($category->contextid
== $contextid) {
1141 $cid = $category->id
;
1142 if ($currentcat != $cid ||
$currentcat == 0) {
1143 $countstring = !empty($category->questioncount
) ?
1144 " ($category->questioncount)" : '';
1145 $categoriesarray[$contextstring][$cid] =
1146 format_string($category->indentedname
, true,
1147 array('context' => $context)) . $countstring;
1153 $popupcats = array();
1154 foreach ($categoriesarray as $contextstring => $optgroup) {
1156 foreach ($optgroup as $key => $value) {
1157 $key = str_replace($CFG->wwwroot
, '', $key);
1158 $group[$key] = $value;
1160 $popupcats[] = array($contextstring => $group);
1164 return $categoriesarray;
1168 function question_add_context_in_key($categories) {
1169 $newcatarray = array();
1170 foreach ($categories as $id => $category) {
1171 $category->parent
= "$category->parent,$category->contextid";
1172 $category->id
= "$category->id,$category->contextid";
1173 $newcatarray["$id,$category->contextid"] = $category;
1175 return $newcatarray;
1178 function question_add_tops($categories, $pcontexts) {
1180 foreach ($pcontexts as $context) {
1181 $newcat = new stdClass();
1182 $newcat->id
= "0,$context";
1183 $newcat->name
= get_string('top');
1184 $newcat->parent
= -1;
1185 $newcat->contextid
= $context;
1186 $topcats["0,$context"] = $newcat;
1188 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1189 return array_merge($topcats, $categories);
1193 * @return array of question category ids of the category and all subcategories.
1195 function question_categorylist($categoryid) {
1198 // final list of category IDs
1199 $categorylist = array();
1201 // a list of category IDs to check for any sub-categories
1202 $subcategories = array($categoryid);
1204 while ($subcategories) {
1205 foreach ($subcategories as $subcategory) {
1206 // if anything from the temporary list was added already, then we have a loop
1207 if (isset($categorylist[$subcategory])) {
1208 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1210 $categorylist[$subcategory] = $subcategory;
1213 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1215 $subcategories = $DB->get_records_select_menu('question_categories',
1216 "parent $in", $params, NULL, 'id,id AS id2');
1219 return $categorylist;
1222 //===========================
1223 // Import/Export Functions
1224 //===========================
1227 * Get list of available import or export formats
1228 * @param string $type 'import' if import list, otherwise export list assumed
1229 * @return array sorted list of import/export formats available
1231 function get_import_export_formats($type) {
1233 require_once($CFG->dirroot
. '/question/format.php');
1235 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1237 $fileformatname = array();
1238 foreach ($formatclasses as $component => $formatclass) {
1240 $format = new $formatclass();
1241 if ($type == 'import') {
1242 $provided = $format->provide_import();
1244 $provided = $format->provide_export();
1248 list($notused, $fileformat) = explode('_', $component, 2);
1249 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1253 core_collator
::asort($fileformatnames);
1254 return $fileformatnames;
1259 * Create a reasonable default file name for exporting questions from a particular
1261 * @param object $course the course the questions are in.
1262 * @param object $category the question category.
1263 * @return string the filename.
1265 function question_default_export_filename($course, $category) {
1266 // We build a string that is an appropriate name (questions) from the lang pack,
1267 // then the corse shortname, then the question category name, then a timestamp.
1269 $base = clean_filename(get_string('exportfilename', 'question'));
1271 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1272 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1274 $shortname = clean_filename($course->shortname
);
1275 if ($shortname == '' ||
$shortname == '_' ) {
1276 $shortname = $course->id
;
1279 $categoryname = clean_filename(format_string($category->name
));
1281 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1283 return $export_name;
1287 * Converts contextlevels to strings and back to help with reading/writing contexts
1288 * to/from import/export files.
1290 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1293 class context_to_string_translator
{
1295 * @var array used to translate between contextids and strings for this context.
1297 protected $contexttostringarray = array();
1299 public function __construct($contexts) {
1300 $this->generate_context_to_string_array($contexts);
1303 public function context_to_string($contextid) {
1304 return $this->contexttostringarray
[$contextid];
1307 public function string_to_context($contextname) {
1308 $contextid = array_search($contextname, $this->contexttostringarray
);
1312 protected function generate_context_to_string_array($contexts) {
1313 if (!$this->contexttostringarray
) {
1315 foreach ($contexts as $context) {
1316 switch ($context->contextlevel
) {
1317 case CONTEXT_MODULE
:
1318 $contextstring = 'module';
1320 case CONTEXT_COURSE
:
1321 $contextstring = 'course';
1323 case CONTEXT_COURSECAT
:
1324 $contextstring = "cat$catno";
1327 case CONTEXT_SYSTEM
:
1328 $contextstring = 'system';
1331 $this->contexttostringarray
[$context->id
] = $contextstring;
1339 * Check capability on category
1341 * @param mixed $question object or id
1342 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1343 * @param integer $cachecat useful to cache all question records in a category
1344 * @return boolean this user has the capability $cap for this question $question?
1346 function question_has_capability_on($question, $cap, $cachecat = -1) {
1349 // these are capabilities on existing questions capabilties are
1350 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1351 $question_questioncaps = array('edit', 'view', 'use', 'move');
1352 static $questions = array();
1353 static $categories = array();
1354 static $cachedcat = array();
1355 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1356 $questions +
= $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1357 $cachedcat[] = $cachecat;
1359 if (!is_object($question)) {
1360 if (!isset($questions[$question])) {
1361 if (!$questions[$question] = $DB->get_record('question',
1362 array('id' => $question), 'id,category,createdby')) {
1363 print_error('questiondoesnotexist', 'question');
1366 $question = $questions[$question];
1368 if (empty($question->category
)) {
1369 // This can happen when we have created a fake 'missingtype' question to
1370 // take the place of a deleted question.
1373 if (!isset($categories[$question->category
])) {
1374 if (!$categories[$question->category
] = $DB->get_record('question_categories',
1375 array('id'=>$question->category
))) {
1376 print_error('invalidcategory', 'quiz');
1379 $category = $categories[$question->category
];
1380 $context = context
::instance_by_id($category->contextid
);
1382 if (array_search($cap, $question_questioncaps)!== false) {
1383 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1384 if ($question->createdby
== $USER->id
) {
1385 return has_capability('moodle/question:' . $cap . 'mine', $context);
1393 return has_capability('moodle/question:' . $cap, $context);
1399 * Require capability on question.
1401 function question_require_capability_on($question, $cap) {
1402 if (!question_has_capability_on($question, $cap)) {
1403 print_error('nopermissions', '', '', $cap);
1409 * Get the real state - the correct question id and answer - for a random
1411 * @param object $state with property answer.
1412 * @deprecated this function has not been relevant since Moodle 2.1!
1414 function question_get_real_state($state) {
1415 throw new coding_exception('question_get_real_state has not been relevant since Moodle 2.1. ' .
1416 'I am not sure what you are trying to do, but stop it at once!');
1420 * @param object $context a context
1421 * @return string A URL for editing questions in this context.
1423 function question_edit_url($context) {
1425 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1428 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1429 $defaultcategory = question_get_default_category($context->id
);
1430 if ($defaultcategory) {
1431 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1433 switch ($context->contextlevel
) {
1434 case CONTEXT_SYSTEM
:
1435 return $baseurl . 'courseid=' . $SITE->id
;
1436 case CONTEXT_COURSECAT
:
1437 // This is nasty, becuase we can only edit questions in a course
1438 // context at the moment, so for now we just return false.
1440 case CONTEXT_COURSE
:
1441 return $baseurl . 'courseid=' . $context->instanceid
;
1442 case CONTEXT_MODULE
:
1443 return $baseurl . 'cmid=' . $context->instanceid
;
1449 * Adds question bank setting links to the given navigation node if caps are met.
1451 * @param navigation_node $navigationnode The navigation node to add the question branch to
1452 * @param object $context
1453 * @return navigation_node Returns the question branch that was added
1455 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1458 if ($context->contextlevel
== CONTEXT_COURSE
) {
1459 $params = array('courseid'=>$context->instanceid
);
1460 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1461 $params = array('cmid'=>$context->instanceid
);
1466 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1467 $params['cat'] = $cat;
1470 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1471 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
);
1473 $contexts = new question_edit_contexts($context);
1474 if ($contexts->have_one_edit_tab_cap('questions')) {
1475 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1476 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
);
1478 if ($contexts->have_one_edit_tab_cap('categories')) {
1479 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1480 '/question/category.php', $params), navigation_node
::TYPE_SETTING
);
1482 if ($contexts->have_one_edit_tab_cap('import')) {
1483 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1484 '/question/import.php', $params), navigation_node
::TYPE_SETTING
);
1486 if ($contexts->have_one_edit_tab_cap('export')) {
1487 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1488 '/question/export.php', $params), navigation_node
::TYPE_SETTING
);
1491 return $questionnode;
1495 * @return array all the capabilities that relate to accessing particular questions.
1497 function question_get_question_capabilities() {
1499 'moodle/question:add',
1500 'moodle/question:editmine',
1501 'moodle/question:editall',
1502 'moodle/question:viewmine',
1503 'moodle/question:viewall',
1504 'moodle/question:usemine',
1505 'moodle/question:useall',
1506 'moodle/question:movemine',
1507 'moodle/question:moveall',
1512 * @return array all the question bank capabilities.
1514 function question_get_all_capabilities() {
1515 $caps = question_get_question_capabilities();
1516 $caps[] = 'moodle/question:managecategory';
1517 $caps[] = 'moodle/question:flag';
1523 * Tracks all the contexts related to the one where we are currently editing
1524 * questions, and provides helper methods to check permissions.
1526 * @copyright 2007 Jamie Pratt me@jamiep.org
1527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1529 class question_edit_contexts
{
1531 public static $caps = array(
1532 'editq' => array('moodle/question:add',
1533 'moodle/question:editmine',
1534 'moodle/question:editall',
1535 'moodle/question:viewmine',
1536 'moodle/question:viewall',
1537 'moodle/question:usemine',
1538 'moodle/question:useall',
1539 'moodle/question:movemine',
1540 'moodle/question:moveall'),
1541 'questions'=>array('moodle/question:add',
1542 'moodle/question:editmine',
1543 'moodle/question:editall',
1544 'moodle/question:viewmine',
1545 'moodle/question:viewall',
1546 'moodle/question:movemine',
1547 'moodle/question:moveall'),
1548 'categories'=>array('moodle/question:managecategory'),
1549 'import'=>array('moodle/question:add'),
1550 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1552 protected $allcontexts;
1556 * @param context the current context.
1558 public function __construct(context
$thiscontext) {
1559 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1563 * @return array all parent contexts
1565 public function all() {
1566 return $this->allcontexts
;
1570 * @return object lowest context which must be either the module or course context
1572 public function lowest() {
1573 return $this->allcontexts
[0];
1577 * @param string $cap capability
1578 * @return array parent contexts having capability, zero based index
1580 public function having_cap($cap) {
1581 $contextswithcap = array();
1582 foreach ($this->allcontexts
as $context) {
1583 if (has_capability($cap, $context)) {
1584 $contextswithcap[] = $context;
1587 return $contextswithcap;
1591 * @param array $caps capabilities
1592 * @return array parent contexts having at least one of $caps, zero based index
1594 public function having_one_cap($caps) {
1595 $contextswithacap = array();
1596 foreach ($this->allcontexts
as $context) {
1597 foreach ($caps as $cap) {
1598 if (has_capability($cap, $context)) {
1599 $contextswithacap[] = $context;
1600 break; //done with caps loop
1604 return $contextswithacap;
1608 * @param string $tabname edit tab name
1609 * @return array parent contexts having at least one of $caps, zero based index
1611 public function having_one_edit_tab_cap($tabname) {
1612 return $this->having_one_cap(self
::$caps[$tabname]);
1616 * @return those contexts where a user can add a question and then use it.
1618 public function having_add_and_use() {
1619 $contextswithcap = array();
1620 foreach ($this->allcontexts
as $context) {
1621 if (!has_capability('moodle/question:add', $context)) {
1624 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1627 $contextswithcap[] = $context;
1629 return $contextswithcap;
1633 * Has at least one parent context got the cap $cap?
1635 * @param string $cap capability
1638 public function have_cap($cap) {
1639 return (count($this->having_cap($cap)));
1643 * Has at least one parent context got one of the caps $caps?
1645 * @param array $caps capability
1648 public function have_one_cap($caps) {
1649 foreach ($caps as $cap) {
1650 if ($this->have_cap($cap)) {
1658 * Has at least one parent context got one of the caps for actions on $tabname
1660 * @param string $tabname edit tab name
1663 public function have_one_edit_tab_cap($tabname) {
1664 return $this->have_one_cap(self
::$caps[$tabname]);
1668 * Throw error if at least one parent context hasn't got the cap $cap
1670 * @param string $cap capability
1672 public function require_cap($cap) {
1673 if (!$this->have_cap($cap)) {
1674 print_error('nopermissions', '', '', $cap);
1679 * Throw error if at least one parent context hasn't got one of the caps $caps
1681 * @param array $cap capabilities
1683 public function require_one_cap($caps) {
1684 if (!$this->have_one_cap($caps)) {
1685 $capsstring = join($caps, ', ');
1686 print_error('nopermissions', '', '', $capsstring);
1691 * Throw error if at least one parent context hasn't got one of the caps $caps
1693 * @param string $tabname edit tab name
1695 public function require_one_edit_tab_cap($tabname) {
1696 if (!$this->have_one_edit_tab_cap($tabname)) {
1697 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1704 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1706 * @package core_question
1708 * @param string $text text being processed
1709 * @param string $file the php script used to serve files
1710 * @param int $contextid context ID
1711 * @param string $component component
1712 * @param string $filearea filearea
1713 * @param array $ids other IDs will be used to check file permission
1714 * @param int $itemid item ID
1715 * @param array $options options
1718 function question_rewrite_question_urls($text, $file, $contextid, $component,
1719 $filearea, array $ids, $itemid, array $options=null) {
1723 $idsstr .= implode('/', $ids);
1725 if ($itemid !== null) {
1726 $idsstr .= '/' . $itemid;
1728 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1729 $filearea, $idsstr, $options);
1733 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1734 * text outside an attempt (for example, in the question bank listing or in the
1735 * quiz statistics report).
1737 * @param string $questiontext the question text.
1738 * @param int $contextid the context the text is being displayed in.
1739 * @param string $component component
1740 * @param array $questionid the question id
1741 * @param array $options e.g. forcedownload. Passed to file_rewrite_pluginfile_urls.
1742 * @return string $questiontext with URLs rewritten.
1743 * @deprecated since Moodle 2.6
1745 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1746 $component, $questionid, $options=null) {
1749 debugging('question_rewrite_questiontext_preview_urls has been deprecated. ' .
1750 'Please use question_rewrite_question_preview_urls instead', DEBUG_DEVELOPER
);
1751 $questioncontextid = $DB->get_field_sql('
1754 JOIN {question_categories} qc ON qc.id = q.category
1755 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST
);
1757 return question_rewrite_question_preview_urls($questiontext, $questionid,
1758 $questioncontextid, 'question', 'questiontext', $questionid,
1759 $contextid, $component, $options);
1763 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1764 * viewing the question outside an attempt (for example, in the question bank
1765 * listing or in the quiz statistics report).
1767 * @param string $text the question text.
1768 * @param int $questionid the question id.
1769 * @param int $filecontextid the context id of the question being displayed.
1770 * @param string $filecomponent the component that owns the file area.
1771 * @param string $filearea the file area name.
1772 * @param int|null $itemid the file's itemid
1773 * @param int $previewcontextid the context id where the preview is being displayed.
1774 * @param string $previewcomponent component responsible for displaying the preview.
1775 * @param array $options text and file options ('forcehttps'=>false)
1776 * @return string $questiontext with URLs rewritten.
1778 function question_rewrite_question_preview_urls($text, $questionid,
1779 $filecontextid, $filecomponent, $filearea, $itemid,
1780 $previewcontextid, $previewcomponent, $options = null) {
1782 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1784 $path .= '/' . $itemid;
1787 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1788 $filecomponent, $filearea, $path, $options);
1792 * Send a file from the question text of a question.
1793 * @param int $questionid the question id
1794 * @param array $args the remaining file arguments (file path).
1795 * @param bool $forcedownload whether the user must be forced to download the file.
1796 * @param array $options additional options affecting the file serving
1797 * @deprecated since Moodle 2.6.
1799 function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
1802 debugging('question_send_questiontext_file has been deprecated. It is no longer necessary. ' .
1803 'You can now just use send_stored_file.', DEBUG_DEVELOPER
);
1804 $question = $DB->get_record_sql('
1805 SELECT q.id, qc.contextid
1807 JOIN {question_categories} qc ON qc.id = q.category
1808 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST
);
1810 $fs = get_file_storage();
1811 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1813 // Get rid of the redundant questionid.
1814 $fullpath = str_replace("/{$questionid}/{$questionid}/", "/{$questionid}/", $fullpath);
1816 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1817 send_file_not_found();
1820 send_stored_file($file, 0, 0, $forcedownload, $options);
1824 * Called by pluginfile.php to serve files related to the 'question' core
1825 * component and for files belonging to qtypes.
1827 * For files that relate to questions in a question_attempt, then we delegate to
1828 * a function in the component that owns the attempt (for example in the quiz,
1829 * or in core question preview) to get necessary inforation.
1831 * (Note that, at the moment, all question file areas relate to questions in
1832 * attempts, so the If at the start of the last paragraph is always true.)
1834 * Does not return, either calls send_file_not_found(); or serves the file.
1836 * @package core_question
1838 * @param stdClass $course course settings object
1839 * @param stdClass $context context object
1840 * @param string $component the name of the component we are serving files for.
1841 * @param string $filearea the name of the file area.
1842 * @param array $args the remaining bits of the file path.
1843 * @param bool $forcedownload whether the user must be forced to download the file.
1844 * @param array $options additional options affecting the file serving
1846 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1849 // Special case, sending a question bank export.
1850 if ($filearea === 'export') {
1851 list($context, $course, $cm) = get_context_info_array($context->id
);
1852 require_login($course, false, $cm);
1854 require_once($CFG->dirroot
. '/question/editlib.php');
1855 $contexts = new question_edit_contexts($context);
1856 // check export capability
1857 $contexts->require_one_edit_tab_cap('export');
1858 $category_id = (int)array_shift($args);
1859 $format = array_shift($args);
1860 $cattofile = array_shift($args);
1861 $contexttofile = array_shift($args);
1862 $filename = array_shift($args);
1864 // load parent class for import/export
1865 require_once($CFG->dirroot
. '/question/format.php');
1866 require_once($CFG->dirroot
. '/question/editlib.php');
1867 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
1869 $classname = 'qformat_' . $format;
1870 if (!class_exists($classname)) {
1871 send_file_not_found();
1874 $qformat = new $classname();
1876 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1877 send_file_not_found();
1880 $qformat->setCategory($category);
1881 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1882 $qformat->setCourse($course);
1884 if ($cattofile == 'withcategories') {
1885 $qformat->setCattofile(true);
1887 $qformat->setCattofile(false);
1890 if ($contexttofile == 'withcontexts') {
1891 $qformat->setContexttofile(true);
1893 $qformat->setContexttofile(false);
1896 if (!$qformat->exportpreprocess()) {
1897 send_file_not_found();
1898 print_error('exporterror', 'question', $thispageurl->out());
1901 // export data to moodle file pool
1902 if (!$content = $qformat->exportprocess(true)) {
1903 send_file_not_found();
1906 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1909 // Normal case, a file belonging to a question.
1910 $qubaidorpreview = array_shift($args);
1912 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1913 if ($qubaidorpreview === 'preview') {
1914 $previewcontextid = (int)array_shift($args);
1915 $previewcomponent = array_shift($args);
1916 $questionid = (int) array_shift($args);
1917 $previewcontext = context_helper
::instance_by_id($previewcontextid);
1919 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1920 $previewcontext, $questionid,
1921 $context, $component, $filearea, $args,
1922 $forcedownload, $options), 'newcallbackmissing');
1924 if ($result === 'newcallbackmissing' && $filearea = 'questiontext') {
1925 // Fall back to the legacy callback for backwards compatibility.
1926 debugging("Component {$previewcomponent} does not define the expected " .
1927 "{$previewcomponent}_question_preview_pluginfile callback. Falling back to the deprecated " .
1928 "{$previewcomponent}_questiontext_preview_pluginfile callback.", DEBUG_DEVELOPER
);
1929 component_callback($previewcomponent, 'questiontext_preview_pluginfile', array(
1930 $previewcontext, $questionid, $args, $forcedownload, $options));
1933 send_file_not_found();
1936 // 2. A question being attempted in the normal way.
1937 $qubaid = (int)$qubaidorpreview;
1938 $slot = (int)array_shift($args);
1940 $module = $DB->get_field('question_usages', 'component',
1941 array('id' => $qubaid));
1943 if ($module === 'core_question_preview') {
1944 require_once($CFG->dirroot
. '/question/previewlib.php');
1945 return question_preview_question_pluginfile($course, $context,
1946 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1949 $dir = core_component
::get_component_directory($module);
1950 if (!file_exists("$dir/lib.php")) {
1951 send_file_not_found();
1953 include_once("$dir/lib.php");
1955 $filefunction = $module . '_question_pluginfile';
1956 if (function_exists($filefunction)) {
1957 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1958 $args, $forcedownload, $options);
1961 // Okay, we're here so lets check for function without 'mod_'.
1962 if (strpos($module, 'mod_') === 0) {
1963 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1964 if (function_exists($filefunctionold)) {
1965 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1966 $args, $forcedownload, $options);
1970 send_file_not_found();
1975 * Serve questiontext files in the question text when they are displayed in this report.
1977 * @package core_files
1979 * @param context $previewcontext the context in which the preview is happening.
1980 * @param int $questionid the question id.
1981 * @param context $filecontext the file (question) context.
1982 * @param string $filecomponent the component the file belongs to.
1983 * @param string $filearea the file area.
1984 * @param array $args remaining file args.
1985 * @param bool $forcedownload.
1986 * @param array $options additional options affecting the file serving.
1988 function core_question_question_preview_pluginfile($previewcontext, $questionid,
1989 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
1992 // Verify that contextid matches the question.
1993 $question = $DB->get_record_sql('
1994 SELECT q.*, qc.contextid
1996 JOIN {question_categories} qc ON qc.id = q.category
1997 WHERE q.id = :id AND qc.contextid = :contextid',
1998 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
2000 // Check the capability.
2001 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
2002 require_login($course, false, $cm);
2004 question_require_capability_on($question, 'use');
2006 $fs = get_file_storage();
2007 $relativepath = implode('/', $args);
2008 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2009 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2010 send_file_not_found();
2013 send_stored_file($file, 0, 0, $forcedownload, $options);
2017 * Create url for question export
2019 * @param int $contextid, current context
2020 * @param int $categoryid, categoryid
2021 * @param string $format
2022 * @param string $withcategories
2023 * @param string $ithcontexts
2024 * @param moodle_url export file url
2026 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2027 $withcontexts, $filename) {
2029 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
2030 return moodle_url
::make_file_url($urlbase,
2031 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2032 "/{$withcontexts}/{$filename}", true);
2036 * Return a list of page types
2037 * @param string $pagetype current page type
2038 * @param stdClass $parentcontext Block's parent context
2039 * @param stdClass $currentcontext Current context of block
2041 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2044 'question-*'=>get_string('page-question-x', 'question'),
2045 'question-edit'=>get_string('page-question-edit', 'question'),
2046 'question-category'=>get_string('page-question-category', 'question'),
2047 'question-export'=>get_string('page-question-export', 'question'),
2048 'question-import'=>get_string('page-question-import', 'question')
2050 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
2051 require_once($CFG->dirroot
. '/course/lib.php');
2052 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2059 * Does an activity module use the question bank?
2061 * @param string $modname The name of the module (without mod_ prefix).
2062 * @return bool true if the module uses questions.
2064 function question_module_uses_questions($modname) {
2065 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
2069 $component = 'mod_'.$modname;
2070 if (component_callback_exists($component, 'question_pluginfile')) {
2071 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);