Merge branch 'MDL-48202-M30' of git://github.com/lazydaisy/moodle
[moodle.git] / lib / questionlib.php
blob2a2d106f86e9cf8450763d0b52849cb6fac70a31
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
28 * @package moodlecore
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') || die();
37 require_once($CFG->dirroot . '/question/engine/lib.php');
38 require_once($CFG->dirroot . '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
44 /**
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
50 /**
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
57 /**
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
64 /**
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
79 if ($key === false) {
80 return $neworder;
82 // Work out the other index.
83 $otherkey = $key + $direction;
84 if (!isset($neworder[$otherkey])) {
85 return $neworder;
87 // Do the swap.
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
91 return $neworder;
94 /**
95 * Save a new question type order to the config_plugins table.
96 * @global object
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
101 global $DB;
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
110 set_config($sortvar, $index + 1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
122 global $CFG;
124 if (question_engine::questions_in_use($questionids)) {
125 return true;
128 foreach (core_component::get_plugin_list('mod') as $module => $path) {
129 $lib = $path . '/lib.php';
130 if (is_readable($lib)) {
131 include_once($lib);
133 $fn = $module . '_questions_in_use';
134 if (function_exists($fn)) {
135 if ($fn($questionids)) {
136 return true;
138 } else {
140 // Fallback for legacy modules.
141 $fn = $module . '_question_list_instances';
142 if (function_exists($fn)) {
143 foreach ($questionids as $questionid) {
144 $instances = $fn($questionid);
145 if (!empty($instances)) {
146 return true;
154 return false;
158 * Determine whether there arey any questions belonging to this context, that is whether any of its
159 * question categories contain any questions. This will return true even if all the questions are
160 * hidden.
162 * @param mixed $context either a context object, or a context id.
163 * @return boolean whether any of the question categories beloning to this context have
164 * any questions in them.
166 function question_context_has_any_questions($context) {
167 global $DB;
168 if (is_object($context)) {
169 $contextid = $context->id;
170 } else if (is_numeric($context)) {
171 $contextid = $context;
172 } else {
173 print_error('invalidcontextinhasanyquestions', 'question');
175 return $DB->record_exists_sql("SELECT *
176 FROM {question} q
177 JOIN {question_categories} qc ON qc.id = q.category
178 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
182 * Check whether a given grade is one of a list of allowed options. If not,
183 * depending on $matchgrades, either return the nearest match, or return false
184 * to signal an error.
185 * @param array $gradeoptionsfull list of valid options
186 * @param int $grade grade to be tested
187 * @param string $matchgrades 'error' or 'nearest'
188 * @return mixed either 'fixed' value or false if error.
190 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
192 if ($matchgrades == 'error') {
193 // (Almost) exact match, or an error.
194 foreach ($gradeoptionsfull as $value => $option) {
195 // Slightly fuzzy test, never check floats for equality.
196 if (abs($grade - $value) < 0.00001) {
197 return $value; // Be sure the return the proper value.
200 // Didn't find a match so that's an error.
201 return false;
203 } else if ($matchgrades == 'nearest') {
204 // Work out nearest value
205 $best = false;
206 $bestmismatch = 2;
207 foreach ($gradeoptionsfull as $value => $option) {
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
210 $best = $value;
211 $bestmismatch = $newmismatch;
214 return $best;
216 } else {
217 // Unknow option passed.
218 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
219 ' passed to match_grade_options');
224 * Category is about to be deleted,
225 * 1/ All questions are deleted for this question category.
226 * 2/ Any questions that can't be deleted are moved to a new category
227 * NOTE: this function is called from lib/db/upgrade.php
229 * @param object|coursecat $category course category object
231 function question_category_delete_safe($category) {
232 global $DB;
233 $criteria = array('category' => $category->id);
234 $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
235 $rescue = null; // See the code around the call to question_save_from_deletion.
237 // Deal with any questions in the category.
238 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
240 // Try to delete each question.
241 foreach ($questions as $question) {
242 question_delete_question($question->id);
245 // Check to see if there were any questions that were kept because
246 // they are still in use somehow, even though quizzes in courses
247 // in this category will already have been deleted. This could
248 // happen, for example, if questions are added to a course,
249 // and then that course is moved to another category (MDL-14802).
250 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
251 if (!empty($questionids)) {
252 $parentcontextid = SYSCONTEXTID;
253 $name = get_string('unknown', 'question');
254 if ($context !== false) {
255 $name = $context->get_context_name();
256 $parentcontext = $context->get_parent_context();
257 if ($parentcontext) {
258 $parentcontextid = $parentcontext->id;
261 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
265 // Now delete the category.
266 $DB->delete_records('question_categories', array('id' => $category->id));
270 * Tests whether any question in a category is used by any part of Moodle.
272 * @param integer $categoryid a question category id.
273 * @param boolean $recursive whether to check child categories too.
274 * @return boolean whether any question in this category is in use.
276 function question_category_in_use($categoryid, $recursive = false) {
277 global $DB;
279 //Look at each question in the category
280 if ($questions = $DB->get_records_menu('question',
281 array('category' => $categoryid), '', 'id, 1')) {
282 if (questions_in_use(array_keys($questions))) {
283 return true;
286 if (!$recursive) {
287 return false;
290 //Look under child categories recursively
291 if ($children = $DB->get_records('question_categories',
292 array('parent' => $categoryid), '', 'id, 1')) {
293 foreach ($children as $child) {
294 if (question_category_in_use($child->id, $recursive)) {
295 return true;
300 return false;
304 * Deletes question and all associated data from the database
306 * It will not delete a question if it is used by an activity module
307 * @param object $question The question being deleted
309 function question_delete_question($questionid) {
310 global $DB;
312 $question = $DB->get_record_sql('
313 SELECT q.*, qc.contextid
314 FROM {question} q
315 JOIN {question_categories} qc ON qc.id = q.category
316 WHERE q.id = ?', array($questionid));
317 if (!$question) {
318 // In some situations, for example if this was a child of a
319 // Cloze question that was previously deleted, the question may already
320 // have gone. In this case, just do nothing.
321 return;
324 // Do not delete a question if it is used by an activity module
325 if (questions_in_use(array($questionid))) {
326 return;
329 $dm = new question_engine_data_mapper();
330 $dm->delete_previews($questionid);
332 // delete questiontype-specific data
333 question_bank::get_qtype($question->qtype, false)->delete_question(
334 $questionid, $question->contextid);
336 // Delete all tag instances.
337 $DB->delete_records('tag_instance', array('component' => 'core_question', 'itemid' => $question->id));
339 // Now recursively delete all child questions
340 if ($children = $DB->get_records('question',
341 array('parent' => $questionid), '', 'id, qtype')) {
342 foreach ($children as $child) {
343 if ($child->id != $questionid) {
344 question_delete_question($child->id);
349 // Finally delete the question record itself
350 $DB->delete_records('question', array('id' => $questionid));
351 question_bank::notify_question_edited($questionid);
355 * All question categories and their questions are deleted for this context id.
357 * @param object $contextid The contextid to delete question categories from
358 * @return array Feedback from deletes (if any)
360 function question_delete_context($contextid) {
361 global $DB;
363 //To store feedback to be showed at the end of the process
364 $feedbackdata = array();
366 //Cache some strings
367 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
368 $fields = 'id, parent, name, contextid';
369 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
370 //Sort categories following their tree (parent-child) relationships
371 //this will make the feedback more readable
372 $categories = sort_categories_by_tree($categories);
374 foreach ($categories as $category) {
375 question_category_delete_safe($category);
377 //Fill feedback
378 $feedbackdata[] = array($category->name, $strcatdeleted);
381 return $feedbackdata;
385 * All question categories and their questions are deleted for this course.
387 * @param stdClass $course an object representing the activity
388 * @param boolean $feedback to specify if the process must output a summary of its work
389 * @return boolean
391 function question_delete_course($course, $feedback=true) {
392 $coursecontext = context_course::instance($course->id);
393 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
395 // Inform about changes performed if feedback is enabled.
396 if ($feedback && $feedbackdata) {
397 $table = new html_table();
398 $table->head = array(get_string('category', 'question'), get_string('action'));
399 $table->data = $feedbackdata;
400 echo html_writer::table($table);
402 return true;
406 * Category is about to be deleted,
407 * 1/ All question categories and their questions are deleted for this course category.
408 * 2/ All questions are moved to new category
410 * @param object|coursecat $category course category object
411 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
412 * category where content moved
413 * @param boolean $feedback to specify if the process must output a summary of its work
414 * @return boolean
416 function question_delete_course_category($category, $newcategory, $feedback=true) {
417 global $DB, $OUTPUT;
419 $context = context_coursecat::instance($category->id);
420 if (empty($newcategory)) {
421 $feedbackdata = question_delete_context($context->id, $feedback);
423 // Output feedback if requested.
424 if ($feedback && $feedbackdata) {
425 $table = new html_table();
426 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
427 $table->data = $feedbackdata;
428 echo html_writer::table($table);
431 } else {
432 // Move question categories to the new context.
433 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
434 return false;
437 // Update the contextid for any tag instances for questions in the old context.
438 $DB->set_field('tag_instance', 'contextid', $newcontext->id, array('component' => 'core_question',
439 'contextid' => $context->id));
441 $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid' => $context->id));
443 if ($feedback) {
444 $a = new stdClass();
445 $a->oldplace = $context->get_context_name();
446 $a->newplace = $newcontext->get_context_name();
447 echo $OUTPUT->notification(
448 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
452 return true;
456 * Enter description here...
458 * @param array $questionids of question ids
459 * @param object $newcontextid the context to create the saved category in.
460 * @param string $oldplace a textual description of the think being deleted,
461 * e.g. from get_context_name
462 * @param object $newcategory
463 * @return mixed false on
465 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
466 $newcategory = null) {
467 global $DB;
469 // Make a category in the parent context to move the questions to.
470 if (is_null($newcategory)) {
471 $newcategory = new stdClass();
472 $newcategory->parent = 0;
473 $newcategory->contextid = $newcontextid;
474 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
475 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
476 $newcategory->sortorder = 999;
477 $newcategory->stamp = make_unique_id_code();
478 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
481 // Move any remaining questions to the 'saved' category.
482 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
483 return false;
485 return $newcategory;
489 * All question categories and their questions are deleted for this activity.
491 * @param object $cm the course module object representing the activity
492 * @param boolean $feedback to specify if the process must output a summary of its work
493 * @return boolean
495 function question_delete_activity($cm, $feedback=true) {
496 global $DB;
498 $modcontext = context_module::instance($cm->id);
499 $feedbackdata = question_delete_context($modcontext->id, $feedback);
500 // Inform about changes performed if feedback is enabled.
501 if ($feedback && $feedbackdata) {
502 $table = new html_table();
503 $table->head = array(get_string('category', 'question'), get_string('action'));
504 $table->data = $feedbackdata;
505 echo html_writer::table($table);
507 return true;
511 * This function should be considered private to the question bank, it is called from
512 * question/editlib.php question/contextmoveq.php and a few similar places to to the
513 * work of acutally moving questions and associated data. However, callers of this
514 * function also have to do other work, which is why you should not call this method
515 * directly from outside the questionbank.
517 * @param array $questionids of question ids.
518 * @param integer $newcategoryid the id of the category to move to.
520 function question_move_questions_to_category($questionids, $newcategoryid) {
521 global $DB;
523 $newcontextid = $DB->get_field('question_categories', 'contextid',
524 array('id' => $newcategoryid));
525 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
526 $questions = $DB->get_records_sql("
527 SELECT q.id, q.qtype, qc.contextid
528 FROM {question} q
529 JOIN {question_categories} qc ON q.category = qc.id
530 WHERE q.id $questionidcondition", $params);
531 foreach ($questions as $question) {
532 if ($newcontextid != $question->contextid) {
533 question_bank::get_qtype($question->qtype)->move_files(
534 $question->id, $question->contextid, $newcontextid);
538 // Move the questions themselves.
539 $DB->set_field_select('question', 'category', $newcategoryid,
540 "id $questionidcondition", $params);
542 // Move any subquestions belonging to them.
543 $DB->set_field_select('question', 'category', $newcategoryid,
544 "parent $questionidcondition", $params);
546 // Update the contextid for any tag instances that may exist for these questions.
547 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
548 "component = 'core_question' AND itemid $questionidcondition", $params);
550 // TODO Deal with datasets.
552 // Purge these questions from the cache.
553 foreach ($questions as $question) {
554 question_bank::notify_question_edited($question->id);
557 return true;
561 * This function helps move a question cateogry to a new context by moving all
562 * the files belonging to all the questions to the new context.
563 * Also moves subcategories.
564 * @param integer $categoryid the id of the category being moved.
565 * @param integer $oldcontextid the old context id.
566 * @param integer $newcontextid the new context id.
568 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
569 global $DB;
571 $questionids = $DB->get_records_menu('question',
572 array('category' => $categoryid), '', 'id,qtype');
573 foreach ($questionids as $questionid => $qtype) {
574 question_bank::get_qtype($qtype)->move_files(
575 $questionid, $oldcontextid, $newcontextid);
576 // Purge this question from the cache.
577 question_bank::notify_question_edited($questionid);
580 if ($questionids) {
581 // Update the contextid for any tag instances that may exist for these questions.
582 list($questionids, $params) = $DB->get_in_or_equal(array_keys($questionids));
583 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
584 "component = 'core_question' AND itemid $questionids", $params);
587 $subcatids = $DB->get_records_menu('question_categories',
588 array('parent' => $categoryid), '', 'id,1');
589 foreach ($subcatids as $subcatid => $notused) {
590 $DB->set_field('question_categories', 'contextid', $newcontextid,
591 array('id' => $subcatid));
592 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
597 * Generate the URL for starting a new preview of a given question with the given options.
598 * @param integer $questionid the question to preview.
599 * @param string $preferredbehaviour the behaviour to use for the preview.
600 * @param float $maxmark the maximum to mark the question out of.
601 * @param question_display_options $displayoptions the display options to use.
602 * @param int $variant the variant of the question to preview. If null, one will
603 * be picked randomly.
604 * @param object $context context to run the preview in (affects things like
605 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
606 * @return moodle_url the URL.
608 function question_preview_url($questionid, $preferredbehaviour = null,
609 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
611 $params = array('id' => $questionid);
613 if (is_null($context)) {
614 global $PAGE;
615 $context = $PAGE->context;
617 if ($context->contextlevel == CONTEXT_MODULE) {
618 $params['cmid'] = $context->instanceid;
619 } else if ($context->contextlevel == CONTEXT_COURSE) {
620 $params['courseid'] = $context->instanceid;
623 if (!is_null($preferredbehaviour)) {
624 $params['behaviour'] = $preferredbehaviour;
627 if (!is_null($maxmark)) {
628 $params['maxmark'] = $maxmark;
631 if (!is_null($displayoptions)) {
632 $params['correctness'] = $displayoptions->correctness;
633 $params['marks'] = $displayoptions->marks;
634 $params['markdp'] = $displayoptions->markdp;
635 $params['feedback'] = (bool) $displayoptions->feedback;
636 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
637 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
638 $params['history'] = (bool) $displayoptions->history;
641 if ($variant) {
642 $params['variant'] = $variant;
645 return new moodle_url('/question/preview.php', $params);
649 * @return array that can be passed as $params to the {@link popup_action} constructor.
651 function question_preview_popup_params() {
652 return array(
653 'height' => 600,
654 'width' => 800,
659 * Given a list of ids, load the basic information about a set of questions from
660 * the questions table. The $join and $extrafields arguments can be used together
661 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
662 * read the code below to see how the SQL is assembled. Throws exceptions on error.
664 * @param array $questionids array of question ids to load. If null, then all
665 * questions matched by $join will be loaded.
666 * @param string $extrafields extra SQL code to be added to the query.
667 * @param string $join extra SQL code to be added to the query.
668 * @param array $extraparams values for any placeholders in $join.
669 * You must use named placeholders.
670 * @param string $orderby what to order the results by. Optional, default is unspecified order.
672 * @return array partially complete question objects. You need to call get_question_options
673 * on them before they can be properly used.
675 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
676 $extraparams = array(), $orderby = '') {
677 global $DB;
679 if ($questionids === null) {
680 $where = '';
681 $params = array();
682 } else {
683 if (empty($questionids)) {
684 return array();
687 list($questionidcondition, $params) = $DB->get_in_or_equal(
688 $questionids, SQL_PARAMS_NAMED, 'qid0000');
689 $where = 'WHERE q.id ' . $questionidcondition;
692 if ($join) {
693 $join = 'JOIN ' . $join;
696 if ($extrafields) {
697 $extrafields = ', ' . $extrafields;
700 if ($orderby) {
701 $orderby = 'ORDER BY ' . $orderby;
704 $sql = "SELECT q.*, qc.contextid{$extrafields}
705 FROM {question} q
706 JOIN {question_categories} qc ON q.category = qc.id
707 {$join}
708 {$where}
709 {$orderby}";
711 // Load the questions.
712 $questions = $DB->get_records_sql($sql, $extraparams + $params);
713 foreach ($questions as $question) {
714 $question->_partiallyloaded = true;
717 return $questions;
721 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
722 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
723 * read the code below to see how the SQL is assembled. Throws exceptions on error.
725 * @param array $questionids array of question ids.
726 * @param string $extrafields extra SQL code to be added to the query.
727 * @param string $join extra SQL code to be added to the query.
728 * @param array $extraparams values for any placeholders in $join.
729 * You are strongly recommended to use named placeholder.
731 * @return array question objects.
733 function question_load_questions($questionids, $extrafields = '', $join = '') {
734 $questions = question_preload_questions($questionids, $extrafields, $join);
736 // Load the question type specific information
737 if (!get_question_options($questions)) {
738 return 'Could not load the question options';
741 return $questions;
745 * Private function to factor common code out of get_question_options().
747 * @param object $question the question to tidy.
748 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
750 function _tidy_question($question, $loadtags = false) {
751 global $CFG;
753 // Load question-type specific fields.
754 if (!question_bank::is_qtype_installed($question->qtype)) {
755 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
756 'qtype_missingtype')) . $question->questiontext;
758 question_bank::get_qtype($question->qtype)->get_question_options($question);
760 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
761 $question->defaultmark += 0;
762 $question->penalty += 0;
764 if (isset($question->_partiallyloaded)) {
765 unset($question->_partiallyloaded);
768 if ($loadtags && !empty($CFG->usetags)) {
769 require_once($CFG->dirroot . '/tag/lib.php');
770 $question->tags = tag_get_tags_array('question', $question->id);
775 * Updates the question objects with question type specific
776 * information by calling {@link get_question_options()}
778 * Can be called either with an array of question objects or with a single
779 * question object.
781 * @param mixed $questions Either an array of question objects to be updated
782 * or just a single question object
783 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
784 * @return bool Indicates success or failure.
786 function get_question_options(&$questions, $loadtags = false) {
787 if (is_array($questions)) { // deal with an array of questions
788 foreach ($questions as $i => $notused) {
789 _tidy_question($questions[$i], $loadtags);
791 } else { // deal with single question
792 _tidy_question($questions, $loadtags);
794 return true;
798 * Print the icon for the question type
800 * @param object $question The question object for which the icon is required.
801 * Only $question->qtype is used.
802 * @return string the HTML for the img tag.
804 function print_question_icon($question) {
805 global $PAGE;
806 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
810 * Creates a stamp that uniquely identifies this version of the question
812 * In future we want this to use a hash of the question data to guarantee that
813 * identical versions have the same version stamp.
815 * @param object $question
816 * @return string A unique version stamp
818 function question_hash($question) {
819 return make_unique_id_code();
822 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
825 * returns the categories with their names ordered following parent-child relationships
826 * finally it tries to return pending categories (those being orphaned, whose parent is
827 * incorrect) to avoid missing any category from original array.
829 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
830 global $DB;
832 $children = array();
833 $keys = array_keys($categories);
835 foreach ($keys as $key) {
836 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
837 $children[$key] = $categories[$key];
838 $categories[$key]->processed = true;
839 $children = $children + sort_categories_by_tree(
840 $categories, $children[$key]->id, $level+1);
843 //If level = 1, we have finished, try to look for non processed categories
844 // (bad parent) and sort them too
845 if ($level == 1) {
846 foreach ($keys as $key) {
847 // If not processed and it's a good candidate to start (because its
848 // parent doesn't exist in the course)
849 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
850 array('contextid' => $categories[$key]->contextid,
851 'id' => $categories[$key]->parent))) {
852 $children[$key] = $categories[$key];
853 $categories[$key]->processed = true;
854 $children = $children + sort_categories_by_tree(
855 $categories, $children[$key]->id, $level + 1);
859 return $children;
863 * Private method, only for the use of add_indented_names().
865 * Recursively adds an indentedname field to each category, starting with the category
866 * with id $id, and dealing with that category and all its children, and
867 * return a new array, with those categories in the right order.
869 * @param array $categories an array of categories which has had childids
870 * fields added by flatten_category_tree(). Passed by reference for
871 * performance only. It is not modfied.
872 * @param int $id the category to start the indenting process from.
873 * @param int $depth the indent depth. Used in recursive calls.
874 * @return array a new array of categories, in the right order for the tree.
876 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
878 // Indent the name of this category.
879 $newcategories = array();
880 $newcategories[$id] = $categories[$id];
881 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
882 $categories[$id]->name;
884 // Recursively indent the children.
885 foreach ($categories[$id]->childids as $childid) {
886 if ($childid != $nochildrenof) {
887 $newcategories = $newcategories + flatten_category_tree(
888 $categories, $childid, $depth + 1, $nochildrenof);
892 // Remove the childids array that were temporarily added.
893 unset($newcategories[$id]->childids);
895 return $newcategories;
899 * Format categories into an indented list reflecting the tree structure.
901 * @param array $categories An array of category objects, for example from the.
902 * @return array The formatted list of categories.
904 function add_indented_names($categories, $nochildrenof = -1) {
906 // Add an array to each category to hold the child category ids. This array
907 // will be removed again by flatten_category_tree(). It should not be used
908 // outside these two functions.
909 foreach (array_keys($categories) as $id) {
910 $categories[$id]->childids = array();
913 // Build the tree structure, and record which categories are top-level.
914 // We have to be careful, because the categories array may include published
915 // categories from other courses, but not their parents.
916 $toplevelcategoryids = array();
917 foreach (array_keys($categories) as $id) {
918 if (!empty($categories[$id]->parent) &&
919 array_key_exists($categories[$id]->parent, $categories)) {
920 $categories[$categories[$id]->parent]->childids[] = $id;
921 } else {
922 $toplevelcategoryids[] = $id;
926 // Flatten the tree to and add the indents.
927 $newcategories = array();
928 foreach ($toplevelcategoryids as $id) {
929 $newcategories = $newcategories + flatten_category_tree(
930 $categories, $id, 0, $nochildrenof);
933 return $newcategories;
937 * Output a select menu of question categories.
939 * Categories from this course and (optionally) published categories from other courses
940 * are included. Optionally, only categories the current user may edit can be included.
942 * @param integer $courseid the id of the course to get the categories for.
943 * @param integer $published if true, include publised categories from other courses.
944 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
945 * @param integer $selected optionally, the id of a category to be selected by
946 * default in the dropdown.
948 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
949 $selected = "", $nochildrenof = -1) {
950 global $OUTPUT;
951 $categoriesarray = question_category_options($contexts, $top, $currentcat,
952 false, $nochildrenof);
953 if ($selected) {
954 $choose = '';
955 } else {
956 $choose = 'choosedots';
958 $options = array();
959 foreach ($categoriesarray as $group => $opts) {
960 $options[] = array($group => $opts);
962 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
963 echo html_writer::select($options, 'category', $selected, $choose, array('id' => 'id_movetocategory'));
967 * @param integer $contextid a context id.
968 * @return object the default question category for that context, or false if none.
970 function question_get_default_category($contextid) {
971 global $DB;
972 $category = $DB->get_records('question_categories',
973 array('contextid' => $contextid), 'id', '*', 0, 1);
974 if (!empty($category)) {
975 return reset($category);
976 } else {
977 return false;
982 * Gets the default category in the most specific context.
983 * If no categories exist yet then default ones are created in all contexts.
985 * @param array $contexts The context objects for this context and all parent contexts.
986 * @return object The default category - the category in the course context
988 function question_make_default_categories($contexts) {
989 global $DB;
990 static $preferredlevels = array(
991 CONTEXT_COURSE => 4,
992 CONTEXT_MODULE => 3,
993 CONTEXT_COURSECAT => 2,
994 CONTEXT_SYSTEM => 1,
997 $toreturn = null;
998 $preferredness = 0;
999 // If it already exists, just return it.
1000 foreach ($contexts as $key => $context) {
1001 if (!$exists = $DB->record_exists("question_categories",
1002 array('contextid' => $context->id))) {
1003 // Otherwise, we need to make one
1004 $category = new stdClass();
1005 $contextname = $context->get_context_name(false, true);
1006 $category->name = get_string('defaultfor', 'question', $contextname);
1007 $category->info = get_string('defaultinfofor', 'question', $contextname);
1008 $category->contextid = $context->id;
1009 $category->parent = 0;
1010 // By default, all categories get this number, and are sorted alphabetically.
1011 $category->sortorder = 999;
1012 $category->stamp = make_unique_id_code();
1013 $category->id = $DB->insert_record('question_categories', $category);
1014 } else {
1015 $category = question_get_default_category($context->id);
1017 $thispreferredness = $preferredlevels[$context->contextlevel];
1018 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1019 $thispreferredness += 10;
1021 if ($thispreferredness > $preferredness) {
1022 $toreturn = $category;
1023 $preferredness = $thispreferredness;
1027 if (!is_null($toreturn)) {
1028 $toreturn = clone($toreturn);
1030 return $toreturn;
1034 * Get all the category objects, including a count of the number of questions in that category,
1035 * for all the categories in the lists $contexts.
1037 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1038 * @param string $sortorder used as the ORDER BY clause in the select statement.
1039 * @return array of category objects.
1041 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1042 global $DB;
1043 return $DB->get_records_sql("
1044 SELECT c.*, (SELECT count(1) FROM {question} q
1045 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1046 FROM {question_categories} c
1047 WHERE c.contextid IN ($contexts)
1048 ORDER BY $sortorder");
1052 * Output an array of question categories.
1054 function question_category_options($contexts, $top = false, $currentcat = 0,
1055 $popupform = false, $nochildrenof = -1) {
1056 global $CFG;
1057 $pcontexts = array();
1058 foreach ($contexts as $context) {
1059 $pcontexts[] = $context->id;
1061 $contextslist = join($pcontexts, ', ');
1063 $categories = get_categories_for_contexts($contextslist);
1065 $categories = question_add_context_in_key($categories);
1067 if ($top) {
1068 $categories = question_add_tops($categories, $pcontexts);
1070 $categories = add_indented_names($categories, $nochildrenof);
1072 // sort cats out into different contexts
1073 $categoriesarray = array();
1074 foreach ($pcontexts as $contextid) {
1075 $context = context::instance_by_id($contextid);
1076 $contextstring = $context->get_context_name(true, true);
1077 foreach ($categories as $category) {
1078 if ($category->contextid == $contextid) {
1079 $cid = $category->id;
1080 if ($currentcat != $cid || $currentcat == 0) {
1081 $countstring = !empty($category->questioncount) ?
1082 " ($category->questioncount)" : '';
1083 $categoriesarray[$contextstring][$cid] =
1084 format_string($category->indentedname, true,
1085 array('context' => $context)) . $countstring;
1090 if ($popupform) {
1091 $popupcats = array();
1092 foreach ($categoriesarray as $contextstring => $optgroup) {
1093 $group = array();
1094 foreach ($optgroup as $key => $value) {
1095 $key = str_replace($CFG->wwwroot, '', $key);
1096 $group[$key] = $value;
1098 $popupcats[] = array($contextstring => $group);
1100 return $popupcats;
1101 } else {
1102 return $categoriesarray;
1106 function question_add_context_in_key($categories) {
1107 $newcatarray = array();
1108 foreach ($categories as $id => $category) {
1109 $category->parent = "$category->parent,$category->contextid";
1110 $category->id = "$category->id,$category->contextid";
1111 $newcatarray["$id,$category->contextid"] = $category;
1113 return $newcatarray;
1116 function question_add_tops($categories, $pcontexts) {
1117 $topcats = array();
1118 foreach ($pcontexts as $context) {
1119 $newcat = new stdClass();
1120 $newcat->id = "0,$context";
1121 $newcat->name = get_string('top');
1122 $newcat->parent = -1;
1123 $newcat->contextid = $context;
1124 $topcats["0,$context"] = $newcat;
1126 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1127 return array_merge($topcats, $categories);
1131 * @return array of question category ids of the category and all subcategories.
1133 function question_categorylist($categoryid) {
1134 global $DB;
1136 // final list of category IDs
1137 $categorylist = array();
1139 // a list of category IDs to check for any sub-categories
1140 $subcategories = array($categoryid);
1142 while ($subcategories) {
1143 foreach ($subcategories as $subcategory) {
1144 // if anything from the temporary list was added already, then we have a loop
1145 if (isset($categorylist[$subcategory])) {
1146 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1148 $categorylist[$subcategory] = $subcategory;
1151 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1153 $subcategories = $DB->get_records_select_menu('question_categories',
1154 "parent $in", $params, NULL, 'id,id AS id2');
1157 return $categorylist;
1160 //===========================
1161 // Import/Export Functions
1162 //===========================
1165 * Get list of available import or export formats
1166 * @param string $type 'import' if import list, otherwise export list assumed
1167 * @return array sorted list of import/export formats available
1169 function get_import_export_formats($type) {
1170 global $CFG;
1171 require_once($CFG->dirroot . '/question/format.php');
1173 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1175 $fileformatname = array();
1176 foreach ($formatclasses as $component => $formatclass) {
1178 $format = new $formatclass();
1179 if ($type == 'import') {
1180 $provided = $format->provide_import();
1181 } else {
1182 $provided = $format->provide_export();
1185 if ($provided) {
1186 list($notused, $fileformat) = explode('_', $component, 2);
1187 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1191 core_collator::asort($fileformatnames);
1192 return $fileformatnames;
1197 * Create a reasonable default file name for exporting questions from a particular
1198 * category.
1199 * @param object $course the course the questions are in.
1200 * @param object $category the question category.
1201 * @return string the filename.
1203 function question_default_export_filename($course, $category) {
1204 // We build a string that is an appropriate name (questions) from the lang pack,
1205 // then the corse shortname, then the question category name, then a timestamp.
1207 $base = clean_filename(get_string('exportfilename', 'question'));
1209 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1210 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1212 $shortname = clean_filename($course->shortname);
1213 if ($shortname == '' || $shortname == '_' ) {
1214 $shortname = $course->id;
1217 $categoryname = clean_filename(format_string($category->name));
1219 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1221 return $export_name;
1225 * Converts contextlevels to strings and back to help with reading/writing contexts
1226 * to/from import/export files.
1228 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1229 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1231 class context_to_string_translator{
1233 * @var array used to translate between contextids and strings for this context.
1235 protected $contexttostringarray = array();
1237 public function __construct($contexts) {
1238 $this->generate_context_to_string_array($contexts);
1241 public function context_to_string($contextid) {
1242 return $this->contexttostringarray[$contextid];
1245 public function string_to_context($contextname) {
1246 $contextid = array_search($contextname, $this->contexttostringarray);
1247 return $contextid;
1250 protected function generate_context_to_string_array($contexts) {
1251 if (!$this->contexttostringarray) {
1252 $catno = 1;
1253 foreach ($contexts as $context) {
1254 switch ($context->contextlevel) {
1255 case CONTEXT_MODULE :
1256 $contextstring = 'module';
1257 break;
1258 case CONTEXT_COURSE :
1259 $contextstring = 'course';
1260 break;
1261 case CONTEXT_COURSECAT :
1262 $contextstring = "cat$catno";
1263 $catno++;
1264 break;
1265 case CONTEXT_SYSTEM :
1266 $contextstring = 'system';
1267 break;
1269 $this->contexttostringarray[$context->id] = $contextstring;
1277 * Check capability on category
1279 * @param mixed $question object or id
1280 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1281 * @param integer $cachecat useful to cache all question records in a category
1282 * @return boolean this user has the capability $cap for this question $question?
1284 function question_has_capability_on($question, $cap, $cachecat = -1) {
1285 global $USER, $DB;
1287 // these are capabilities on existing questions capabilties are
1288 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1289 $question_questioncaps = array('edit', 'view', 'use', 'move');
1290 static $questions = array();
1291 static $categories = array();
1292 static $cachedcat = array();
1293 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1294 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1295 $cachedcat[] = $cachecat;
1297 if (!is_object($question)) {
1298 if (!isset($questions[$question])) {
1299 if (!$questions[$question] = $DB->get_record('question',
1300 array('id' => $question), 'id,category,createdby')) {
1301 print_error('questiondoesnotexist', 'question');
1304 $question = $questions[$question];
1306 if (empty($question->category)) {
1307 // This can happen when we have created a fake 'missingtype' question to
1308 // take the place of a deleted question.
1309 return false;
1311 if (!isset($categories[$question->category])) {
1312 if (!$categories[$question->category] = $DB->get_record('question_categories',
1313 array('id'=>$question->category))) {
1314 print_error('invalidcategory', 'question');
1317 $category = $categories[$question->category];
1318 $context = context::instance_by_id($category->contextid);
1320 if (array_search($cap, $question_questioncaps)!== false) {
1321 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1322 if ($question->createdby == $USER->id) {
1323 return has_capability('moodle/question:' . $cap . 'mine', $context);
1324 } else {
1325 return false;
1327 } else {
1328 return true;
1330 } else {
1331 return has_capability('moodle/question:' . $cap, $context);
1337 * Require capability on question.
1339 function question_require_capability_on($question, $cap) {
1340 if (!question_has_capability_on($question, $cap)) {
1341 print_error('nopermissions', '', '', $cap);
1343 return true;
1347 * @param object $context a context
1348 * @return string A URL for editing questions in this context.
1350 function question_edit_url($context) {
1351 global $CFG, $SITE;
1352 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1353 return false;
1355 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1356 $defaultcategory = question_get_default_category($context->id);
1357 if ($defaultcategory) {
1358 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1360 switch ($context->contextlevel) {
1361 case CONTEXT_SYSTEM:
1362 return $baseurl . 'courseid=' . $SITE->id;
1363 case CONTEXT_COURSECAT:
1364 // This is nasty, becuase we can only edit questions in a course
1365 // context at the moment, so for now we just return false.
1366 return false;
1367 case CONTEXT_COURSE:
1368 return $baseurl . 'courseid=' . $context->instanceid;
1369 case CONTEXT_MODULE:
1370 return $baseurl . 'cmid=' . $context->instanceid;
1376 * Adds question bank setting links to the given navigation node if caps are met.
1378 * @param navigation_node $navigationnode The navigation node to add the question branch to
1379 * @param object $context
1380 * @return navigation_node Returns the question branch that was added
1382 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1383 global $PAGE;
1385 if ($context->contextlevel == CONTEXT_COURSE) {
1386 $params = array('courseid'=>$context->instanceid);
1387 } else if ($context->contextlevel == CONTEXT_MODULE) {
1388 $params = array('cmid'=>$context->instanceid);
1389 } else {
1390 return;
1393 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1394 $params['cat'] = $cat;
1397 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1398 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1400 $contexts = new question_edit_contexts($context);
1401 if ($contexts->have_one_edit_tab_cap('questions')) {
1402 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1403 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1405 if ($contexts->have_one_edit_tab_cap('categories')) {
1406 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1407 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1409 if ($contexts->have_one_edit_tab_cap('import')) {
1410 $questionnode->add(get_string('import', 'question'), new moodle_url(
1411 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1413 if ($contexts->have_one_edit_tab_cap('export')) {
1414 $questionnode->add(get_string('export', 'question'), new moodle_url(
1415 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1418 return $questionnode;
1422 * @return array all the capabilities that relate to accessing particular questions.
1424 function question_get_question_capabilities() {
1425 return array(
1426 'moodle/question:add',
1427 'moodle/question:editmine',
1428 'moodle/question:editall',
1429 'moodle/question:viewmine',
1430 'moodle/question:viewall',
1431 'moodle/question:usemine',
1432 'moodle/question:useall',
1433 'moodle/question:movemine',
1434 'moodle/question:moveall',
1439 * @return array all the question bank capabilities.
1441 function question_get_all_capabilities() {
1442 $caps = question_get_question_capabilities();
1443 $caps[] = 'moodle/question:managecategory';
1444 $caps[] = 'moodle/question:flag';
1445 return $caps;
1450 * Tracks all the contexts related to the one where we are currently editing
1451 * questions, and provides helper methods to check permissions.
1453 * @copyright 2007 Jamie Pratt me@jamiep.org
1454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1456 class question_edit_contexts {
1458 public static $caps = array(
1459 'editq' => array('moodle/question:add',
1460 'moodle/question:editmine',
1461 'moodle/question:editall',
1462 'moodle/question:viewmine',
1463 'moodle/question:viewall',
1464 'moodle/question:usemine',
1465 'moodle/question:useall',
1466 'moodle/question:movemine',
1467 'moodle/question:moveall'),
1468 'questions'=>array('moodle/question:add',
1469 'moodle/question:editmine',
1470 'moodle/question:editall',
1471 'moodle/question:viewmine',
1472 'moodle/question:viewall',
1473 'moodle/question:movemine',
1474 'moodle/question:moveall'),
1475 'categories'=>array('moodle/question:managecategory'),
1476 'import'=>array('moodle/question:add'),
1477 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1479 protected $allcontexts;
1482 * Constructor
1483 * @param context the current context.
1485 public function __construct(context $thiscontext) {
1486 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1490 * @return array all parent contexts
1492 public function all() {
1493 return $this->allcontexts;
1497 * @return object lowest context which must be either the module or course context
1499 public function lowest() {
1500 return $this->allcontexts[0];
1504 * @param string $cap capability
1505 * @return array parent contexts having capability, zero based index
1507 public function having_cap($cap) {
1508 $contextswithcap = array();
1509 foreach ($this->allcontexts as $context) {
1510 if (has_capability($cap, $context)) {
1511 $contextswithcap[] = $context;
1514 return $contextswithcap;
1518 * @param array $caps capabilities
1519 * @return array parent contexts having at least one of $caps, zero based index
1521 public function having_one_cap($caps) {
1522 $contextswithacap = array();
1523 foreach ($this->allcontexts as $context) {
1524 foreach ($caps as $cap) {
1525 if (has_capability($cap, $context)) {
1526 $contextswithacap[] = $context;
1527 break; //done with caps loop
1531 return $contextswithacap;
1535 * @param string $tabname edit tab name
1536 * @return array parent contexts having at least one of $caps, zero based index
1538 public function having_one_edit_tab_cap($tabname) {
1539 return $this->having_one_cap(self::$caps[$tabname]);
1543 * @return those contexts where a user can add a question and then use it.
1545 public function having_add_and_use() {
1546 $contextswithcap = array();
1547 foreach ($this->allcontexts as $context) {
1548 if (!has_capability('moodle/question:add', $context)) {
1549 continue;
1551 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1552 continue;
1554 $contextswithcap[] = $context;
1556 return $contextswithcap;
1560 * Has at least one parent context got the cap $cap?
1562 * @param string $cap capability
1563 * @return boolean
1565 public function have_cap($cap) {
1566 return (count($this->having_cap($cap)));
1570 * Has at least one parent context got one of the caps $caps?
1572 * @param array $caps capability
1573 * @return boolean
1575 public function have_one_cap($caps) {
1576 foreach ($caps as $cap) {
1577 if ($this->have_cap($cap)) {
1578 return true;
1581 return false;
1585 * Has at least one parent context got one of the caps for actions on $tabname
1587 * @param string $tabname edit tab name
1588 * @return boolean
1590 public function have_one_edit_tab_cap($tabname) {
1591 return $this->have_one_cap(self::$caps[$tabname]);
1595 * Throw error if at least one parent context hasn't got the cap $cap
1597 * @param string $cap capability
1599 public function require_cap($cap) {
1600 if (!$this->have_cap($cap)) {
1601 print_error('nopermissions', '', '', $cap);
1606 * Throw error if at least one parent context hasn't got one of the caps $caps
1608 * @param array $cap capabilities
1610 public function require_one_cap($caps) {
1611 if (!$this->have_one_cap($caps)) {
1612 $capsstring = join($caps, ', ');
1613 print_error('nopermissions', '', '', $capsstring);
1618 * Throw error if at least one parent context hasn't got one of the caps $caps
1620 * @param string $tabname edit tab name
1622 public function require_one_edit_tab_cap($tabname) {
1623 if (!$this->have_one_edit_tab_cap($tabname)) {
1624 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1631 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1633 * @package core_question
1634 * @category files
1635 * @param string $text text being processed
1636 * @param string $file the php script used to serve files
1637 * @param int $contextid context ID
1638 * @param string $component component
1639 * @param string $filearea filearea
1640 * @param array $ids other IDs will be used to check file permission
1641 * @param int $itemid item ID
1642 * @param array $options options
1643 * @return string
1645 function question_rewrite_question_urls($text, $file, $contextid, $component,
1646 $filearea, array $ids, $itemid, array $options=null) {
1648 $idsstr = '';
1649 if (!empty($ids)) {
1650 $idsstr .= implode('/', $ids);
1652 if ($itemid !== null) {
1653 $idsstr .= '/' . $itemid;
1655 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1656 $filearea, $idsstr, $options);
1660 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1661 * viewing the question outside an attempt (for example, in the question bank
1662 * listing or in the quiz statistics report).
1664 * @param string $text the question text.
1665 * @param int $questionid the question id.
1666 * @param int $filecontextid the context id of the question being displayed.
1667 * @param string $filecomponent the component that owns the file area.
1668 * @param string $filearea the file area name.
1669 * @param int|null $itemid the file's itemid
1670 * @param int $previewcontextid the context id where the preview is being displayed.
1671 * @param string $previewcomponent component responsible for displaying the preview.
1672 * @param array $options text and file options ('forcehttps'=>false)
1673 * @return string $questiontext with URLs rewritten.
1675 function question_rewrite_question_preview_urls($text, $questionid,
1676 $filecontextid, $filecomponent, $filearea, $itemid,
1677 $previewcontextid, $previewcomponent, $options = null) {
1679 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1680 if ($itemid) {
1681 $path .= '/' . $itemid;
1684 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1685 $filecomponent, $filearea, $path, $options);
1689 * Called by pluginfile.php to serve files related to the 'question' core
1690 * component and for files belonging to qtypes.
1692 * For files that relate to questions in a question_attempt, then we delegate to
1693 * a function in the component that owns the attempt (for example in the quiz,
1694 * or in core question preview) to get necessary inforation.
1696 * (Note that, at the moment, all question file areas relate to questions in
1697 * attempts, so the If at the start of the last paragraph is always true.)
1699 * Does not return, either calls send_file_not_found(); or serves the file.
1701 * @package core_question
1702 * @category files
1703 * @param stdClass $course course settings object
1704 * @param stdClass $context context object
1705 * @param string $component the name of the component we are serving files for.
1706 * @param string $filearea the name of the file area.
1707 * @param array $args the remaining bits of the file path.
1708 * @param bool $forcedownload whether the user must be forced to download the file.
1709 * @param array $options additional options affecting the file serving
1711 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1712 global $DB, $CFG;
1714 // Special case, sending a question bank export.
1715 if ($filearea === 'export') {
1716 list($context, $course, $cm) = get_context_info_array($context->id);
1717 require_login($course, false, $cm);
1719 require_once($CFG->dirroot . '/question/editlib.php');
1720 $contexts = new question_edit_contexts($context);
1721 // check export capability
1722 $contexts->require_one_edit_tab_cap('export');
1723 $category_id = (int)array_shift($args);
1724 $format = array_shift($args);
1725 $cattofile = array_shift($args);
1726 $contexttofile = array_shift($args);
1727 $filename = array_shift($args);
1729 // load parent class for import/export
1730 require_once($CFG->dirroot . '/question/format.php');
1731 require_once($CFG->dirroot . '/question/editlib.php');
1732 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1734 $classname = 'qformat_' . $format;
1735 if (!class_exists($classname)) {
1736 send_file_not_found();
1739 $qformat = new $classname();
1741 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1742 send_file_not_found();
1745 $qformat->setCategory($category);
1746 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1747 $qformat->setCourse($course);
1749 if ($cattofile == 'withcategories') {
1750 $qformat->setCattofile(true);
1751 } else {
1752 $qformat->setCattofile(false);
1755 if ($contexttofile == 'withcontexts') {
1756 $qformat->setContexttofile(true);
1757 } else {
1758 $qformat->setContexttofile(false);
1761 if (!$qformat->exportpreprocess()) {
1762 send_file_not_found();
1763 print_error('exporterror', 'question', $thispageurl->out());
1766 // export data to moodle file pool
1767 if (!$content = $qformat->exportprocess(true)) {
1768 send_file_not_found();
1771 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1774 // Normal case, a file belonging to a question.
1775 $qubaidorpreview = array_shift($args);
1777 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1778 if ($qubaidorpreview === 'preview') {
1779 $previewcontextid = (int)array_shift($args);
1780 $previewcomponent = array_shift($args);
1781 $questionid = (int) array_shift($args);
1782 $previewcontext = context_helper::instance_by_id($previewcontextid);
1784 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1785 $previewcontext, $questionid,
1786 $context, $component, $filearea, $args,
1787 $forcedownload, $options), 'callbackmissing');
1789 if ($result === 'callbackmissing') {
1790 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1791 "{$previewcomponent}_question_preview_pluginfile callback. " .
1792 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
1795 send_file_not_found();
1798 // 2. A question being attempted in the normal way.
1799 $qubaid = (int)$qubaidorpreview;
1800 $slot = (int)array_shift($args);
1802 $module = $DB->get_field('question_usages', 'component',
1803 array('id' => $qubaid));
1804 if (!$module) {
1805 send_file_not_found();
1808 if ($module === 'core_question_preview') {
1809 require_once($CFG->dirroot . '/question/previewlib.php');
1810 return question_preview_question_pluginfile($course, $context,
1811 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1813 } else {
1814 $dir = core_component::get_component_directory($module);
1815 if (!file_exists("$dir/lib.php")) {
1816 send_file_not_found();
1818 include_once("$dir/lib.php");
1820 $filefunction = $module . '_question_pluginfile';
1821 if (function_exists($filefunction)) {
1822 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1823 $args, $forcedownload, $options);
1826 // Okay, we're here so lets check for function without 'mod_'.
1827 if (strpos($module, 'mod_') === 0) {
1828 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1829 if (function_exists($filefunctionold)) {
1830 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1831 $args, $forcedownload, $options);
1835 send_file_not_found();
1840 * Serve questiontext files in the question text when they are displayed in this report.
1842 * @package core_files
1843 * @category files
1844 * @param context $previewcontext the context in which the preview is happening.
1845 * @param int $questionid the question id.
1846 * @param context $filecontext the file (question) context.
1847 * @param string $filecomponent the component the file belongs to.
1848 * @param string $filearea the file area.
1849 * @param array $args remaining file args.
1850 * @param bool $forcedownload.
1851 * @param array $options additional options affecting the file serving.
1853 function core_question_question_preview_pluginfile($previewcontext, $questionid,
1854 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
1855 global $DB;
1857 // Verify that contextid matches the question.
1858 $question = $DB->get_record_sql('
1859 SELECT q.*, qc.contextid
1860 FROM {question} q
1861 JOIN {question_categories} qc ON qc.id = q.category
1862 WHERE q.id = :id AND qc.contextid = :contextid',
1863 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
1865 // Check the capability.
1866 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
1867 require_login($course, false, $cm);
1869 question_require_capability_on($question, 'use');
1871 $fs = get_file_storage();
1872 $relativepath = implode('/', $args);
1873 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1874 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1875 send_file_not_found();
1878 send_stored_file($file, 0, 0, $forcedownload, $options);
1882 * Create url for question export
1884 * @param int $contextid, current context
1885 * @param int $categoryid, categoryid
1886 * @param string $format
1887 * @param string $withcategories
1888 * @param string $ithcontexts
1889 * @param moodle_url export file url
1891 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1892 $withcontexts, $filename) {
1893 global $CFG;
1894 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1895 return moodle_url::make_file_url($urlbase,
1896 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1897 "/{$withcontexts}/{$filename}", true);
1901 * Return a list of page types
1902 * @param string $pagetype current page type
1903 * @param stdClass $parentcontext Block's parent context
1904 * @param stdClass $currentcontext Current context of block
1906 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1907 global $CFG;
1908 $types = array(
1909 'question-*'=>get_string('page-question-x', 'question'),
1910 'question-edit'=>get_string('page-question-edit', 'question'),
1911 'question-category'=>get_string('page-question-category', 'question'),
1912 'question-export'=>get_string('page-question-export', 'question'),
1913 'question-import'=>get_string('page-question-import', 'question')
1915 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1916 require_once($CFG->dirroot . '/course/lib.php');
1917 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1918 } else {
1919 return $types;
1924 * Does an activity module use the question bank?
1926 * @param string $modname The name of the module (without mod_ prefix).
1927 * @return bool true if the module uses questions.
1929 function question_module_uses_questions($modname) {
1930 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
1931 return true;
1934 $component = 'mod_'.$modname;
1935 if (component_callback_exists($component, 'question_pluginfile')) {
1936 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
1937 return true;
1940 return false;