MDL-27747 Imporove API for getting the standard fraction choices.
[moodle.git] / lib / questionlib.php
blob8371f3bc3e3135f45aec9e0a0aca8a0224ef25fc
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 * The core question types.
47 define("SHORTANSWER", "shortanswer");
48 define("TRUEFALSE", "truefalse");
49 define("MULTICHOICE", "multichoice");
50 define("RANDOM", "random");
51 define("MATCH", "match");
52 define("RANDOMSAMATCH", "randomsamatch");
53 define("DESCRIPTION", "description");
54 define("NUMERICAL", "numerical");
55 define("MULTIANSWER", "multianswer");
56 define("CALCULATED", "calculated");
57 define("ESSAY", "essay");
58 /**#@-*/
60 /**
61 * Constant determines the number of answer boxes supplied in the editing
62 * form for multiple choice and similar question types.
64 define("QUESTION_NUMANS", 10);
66 /**
67 * Constant determines the number of answer boxes supplied in the editing
68 * form for multiple choice and similar question types to start with, with
69 * the option of adding QUESTION_NUMANS_ADD more answers.
71 define("QUESTION_NUMANS_START", 3);
73 /**
74 * Constant determines the number of answer boxes to add in the editing
75 * form for multiple choice and similar question types when the user presses
76 * 'add form fields button'.
78 define("QUESTION_NUMANS_ADD", 3);
80 /**
81 * Move one question type in a list of question types. If you try to move one element
82 * off of the end, nothing will change.
84 * @param array $sortedqtypes An array $qtype => anything.
85 * @param string $tomove one of the keys from $sortedqtypes
86 * @param integer $direction +1 or -1
87 * @return array an array $index => $qtype, with $index from 0 to n in order, and
88 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
89 * have been moved one place.
91 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
92 $neworder = array_keys($sortedqtypes);
93 // Find the element to move.
94 $key = array_search($tomove, $neworder);
95 if ($key === false) {
96 return $neworder;
98 // Work out the other index.
99 $otherkey = $key + $direction;
100 if (!isset($neworder[$otherkey])) {
101 return $neworder;
103 // Do the swap.
104 $swap = $neworder[$otherkey];
105 $neworder[$otherkey] = $neworder[$key];
106 $neworder[$key] = $swap;
107 return $neworder;
111 * Save a new question type order to the config_plugins table.
112 * @global object
113 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
114 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
116 function question_save_qtype_order($neworder, $config = null) {
117 global $DB;
119 if (is_null($config)) {
120 $config = get_config('question');
123 foreach ($neworder as $index => $qtype) {
124 $sortvar = $qtype . '_sortorder';
125 if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
126 set_config($sortvar, $index + 1, 'question');
131 /// FUNCTIONS //////////////////////////////////////////////////////
134 * Returns an array of names of activity modules that use this question
136 * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
138 * @param object $questionid
139 * @return array of strings
141 function question_list_instances($questionid) {
142 throw new coding_exception('question_list_instances has been deprectated. ' .
143 'Please use questions_in_use instead.');
147 * @param array $questionids of question ids.
148 * @return boolean whether any of these questions are being used by any part of Moodle.
150 function questions_in_use($questionids) {
151 global $CFG;
153 if (question_engine::questions_in_use($questionids)) {
154 return true;
157 foreach (get_plugin_list('mod') as $module => $path) {
158 $lib = $path . '/lib.php';
159 if (is_readable($lib)) {
160 include_once($lib);
162 $fn = $module . '_questions_in_use';
163 if (function_exists($fn)) {
164 if ($fn($questionids)) {
165 return true;
167 } else {
169 // Fallback for legacy modules.
170 $fn = $module . '_question_list_instances';
171 if (function_exists($fn)) {
172 foreach ($questionids as $questionid) {
173 $instances = $fn($questionid);
174 if (!empty($instances)) {
175 return true;
183 return false;
187 * Determine whether there arey any questions belonging to this context, that is whether any of its
188 * question categories contain any questions. This will return true even if all the questions are
189 * hidden.
191 * @param mixed $context either a context object, or a context id.
192 * @return boolean whether any of the question categories beloning to this context have
193 * any questions in them.
195 function question_context_has_any_questions($context) {
196 global $DB;
197 if (is_object($context)) {
198 $contextid = $context->id;
199 } else if (is_numeric($context)) {
200 $contextid = $context;
201 } else {
202 print_error('invalidcontextinhasanyquestions', 'question');
204 return $DB->record_exists_sql("SELECT *
205 FROM {question} q
206 JOIN {question_categories} qc ON qc.id = q.category
207 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
211 * Returns list of 'allowed' grades for grade selection
212 * formatted suitably for dropdown box function
214 * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
215 * {@link question_bank::fraction_options_full()} instead.
217 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
219 function get_grade_options() {
220 $grades = new stdClass();
221 $grades->gradeoptions = question_bank::fraction_options();
222 $grades->gradeoptionsfull = question_bank::fraction_options_full();
224 return $grades;
228 * match grade options
229 * if no match return error or match nearest
230 * @param array $gradeoptionsfull list of valid options
231 * @param int $grade grade to be tested
232 * @param string $matchgrades 'error' or 'nearest'
233 * @return mixed either 'fixed' value or false if erro
235 function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
236 if ($matchgrades == 'error') {
237 // if we just need an error...
238 foreach ($gradeoptionsfull as $value => $option) {
239 // slightly fuzzy test, never check floats for equality :-)
240 if (abs($grade - $value) < 0.00001) {
241 return $grade;
244 // didn't find a match so that's an error
245 return false;
246 } else if ($matchgrades == 'nearest') {
247 // work out nearest value
248 $hownear = array();
249 foreach ($gradeoptionsfull as $value => $option) {
250 if ($grade==$value) {
251 return $grade;
253 $hownear[ $value ] = abs( $grade - $value );
255 // reverse sort list of deltas and grab the last (smallest)
256 asort( $hownear, SORT_NUMERIC );
257 reset( $hownear );
258 return key( $hownear );
259 } else {
260 return false;
265 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
266 * @param integer $categoryid a question category id.
267 * @param boolean $recursive whether to check child categories too.
268 * @return boolean whether any question in this category is in use.
270 function question_category_isused($categoryid, $recursive = false) {
271 throw new coding_exception('question_category_isused has been deprectated. ' .
272 'Please use question_category_in_use instead.');
276 * Tests whether any question in a category is used by any part of Moodle.
278 * @param integer $categoryid a question category id.
279 * @param boolean $recursive whether to check child categories too.
280 * @return boolean whether any question in this category is in use.
282 function question_category_in_use($categoryid, $recursive = false) {
283 global $DB;
285 //Look at each question in the category
286 if ($questions = $DB->get_records_menu('question',
287 array('category' => $categoryid), '', 'id, 1')) {
288 if (questions_in_use(array_keys($questions))) {
289 return true;
292 if (!$recursive) {
293 return false;
296 //Look under child categories recursively
297 if ($children = $DB->get_records('question_categories',
298 array('parent' => $categoryid), '', 'id, 1')) {
299 foreach ($children as $child) {
300 if (question_category_in_use($child->id, $recursive)) {
301 return true;
306 return false;
310 * Deletes question and all associated data from the database
312 * It will not delete a question if it is used by an activity module
313 * @param object $question The question being deleted
315 function question_delete_question($questionid) {
316 global $DB;
318 $question = $DB->get_record_sql('
319 SELECT q.*, qc.contextid
320 FROM {question} q
321 JOIN {question_categories} qc ON qc.id = q.category
322 WHERE q.id = ?', array($questionid));
323 if (!$question) {
324 // In some situations, for example if this was a child of a
325 // Cloze question that was previously deleted, the question may already
326 // have gone. In this case, just do nothing.
327 return;
330 // Do not delete a question if it is used by an activity module
331 if (questions_in_use(array($questionid))) {
332 return;
335 // Check permissions.
336 question_require_capability_on($question, 'edit');
338 $dm = new question_engine_data_mapper();
339 $dm->delete_previews($questionid);
341 // delete questiontype-specific data
342 question_bank::get_qtype($question->qtype, false)->delete_question(
343 $questionid, $question->contextid);
345 // Now recursively delete all child questions
346 if ($children = $DB->get_records('question',
347 array('parent' => $questionid), '', 'id, qtype')) {
348 foreach ($children as $child) {
349 if ($child->id != $questionid) {
350 question_delete_question($child->id);
355 // Finally delete the question record itself
356 $DB->delete_records('question', array('id' => $questionid));
360 * All question categories and their questions are deleted for this course.
362 * @param object $mod an object representing the activity
363 * @param boolean $feedback to specify if the process must output a summary of its work
364 * @return boolean
366 function question_delete_course($course, $feedback=true) {
367 global $DB, $OUTPUT;
369 //To store feedback to be showed at the end of the process
370 $feedbackdata = array();
372 //Cache some strings
373 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
374 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
375 $categoriescourse = $DB->get_records('question_categories',
376 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
378 if ($categoriescourse) {
380 //Sort categories following their tree (parent-child) relationships
381 //this will make the feedback more readable
382 $categoriescourse = sort_categories_by_tree($categoriescourse);
384 foreach ($categoriescourse as $category) {
386 //Delete it completely (questions and category itself)
387 //deleting questions
388 if ($questions = $DB->get_records('question',
389 array('category' => $category->id), '', 'id,qtype')) {
390 foreach ($questions as $question) {
391 question_delete_question($question->id);
393 $DB->delete_records("question", array("category" => $category->id));
395 //delete the category
396 $DB->delete_records('question_categories', array('id' => $category->id));
398 //Fill feedback
399 $feedbackdata[] = array($category->name, $strcatdeleted);
401 //Inform about changes performed if feedback is enabled
402 if ($feedback) {
403 $table = new html_table();
404 $table->head = array(get_string('category', 'quiz'), get_string('action'));
405 $table->data = $feedbackdata;
406 echo html_writer::table($table);
409 return true;
413 * Category is about to be deleted,
414 * 1/ All question categories and their questions are deleted for this course category.
415 * 2/ All questions are moved to new category
417 * @param object $category course category object
418 * @param object $newcategory empty means everything deleted, otherwise id of
419 * category where content moved
420 * @param boolean $feedback to specify if the process must output a summary of its work
421 * @return boolean
423 function question_delete_course_category($category, $newcategory, $feedback=true) {
424 global $DB, $OUTPUT;
426 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
427 if (empty($newcategory)) {
428 $feedbackdata = array(); // To store feedback to be showed at the end of the process
429 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
430 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
432 // Loop over question categories.
433 if ($categories = $DB->get_records('question_categories',
434 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
435 foreach ($categories as $category) {
437 // Deal with any questions in the category.
438 if ($questions = $DB->get_records('question',
439 array('category' => $category->id), '', 'id,qtype')) {
441 // Try to delete each question.
442 foreach ($questions as $question) {
443 question_delete_question($question->id);
446 // Check to see if there were any questions that were kept because
447 // they are still in use somehow, even though quizzes in courses
448 // in this category will already have been deteted. This could
449 // happen, for example, if questions are added to a course,
450 // and then that course is moved to another category (MDL-14802).
451 $questionids = $DB->get_records_menu('question',
452 array('category'=>$category->id), '', 'id, 1');
453 if (!empty($questionids)) {
454 if (!$rescueqcategory = question_save_from_deletion(
455 array_keys($questionids), get_parent_contextid($context),
456 print_context_name($context), $rescueqcategory)) {
457 return false;
459 $feedbackdata[] = array($category->name,
460 get_string('questionsmovedto', 'question', $rescueqcategory->name));
464 // Now delete the category.
465 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
466 return false;
468 $feedbackdata[] = array($category->name, $strcatdeleted);
470 } // End loop over categories.
473 // Output feedback if requested.
474 if ($feedback and $feedbackdata) {
475 $table = new html_table();
476 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
477 $table->data = $feedbackdata;
478 echo html_writer::table($table);
481 } else {
482 // Move question categories ot the new context.
483 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
484 return false;
486 $DB->set_field('question_categories', 'contextid', $newcontext->id,
487 array('contextid'=>$context->id));
488 if ($feedback) {
489 $a = new stdClass();
490 $a->oldplace = print_context_name($context);
491 $a->newplace = print_context_name($newcontext);
492 echo $OUTPUT->notification(
493 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
497 return true;
501 * Enter description here...
503 * @param string $questionids list of questionids
504 * @param object $newcontext the context to create the saved category in.
505 * @param string $oldplace a textual description of the think being deleted,
506 * e.g. from get_context_name
507 * @param object $newcategory
508 * @return mixed false on
510 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
511 $newcategory = null) {
512 global $DB;
514 // Make a category in the parent context to move the questions to.
515 if (is_null($newcategory)) {
516 $newcategory = new stdClass();
517 $newcategory->parent = 0;
518 $newcategory->contextid = $newcontextid;
519 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
520 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
521 $newcategory->sortorder = 999;
522 $newcategory->stamp = make_unique_id_code();
523 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
526 // Move any remaining questions to the 'saved' category.
527 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
528 return false;
530 return $newcategory;
534 * All question categories and their questions are deleted for this activity.
536 * @param object $cm the course module object representing the activity
537 * @param boolean $feedback to specify if the process must output a summary of its work
538 * @return boolean
540 function question_delete_activity($cm, $feedback=true) {
541 global $DB, $OUTPUT;
543 //To store feedback to be showed at the end of the process
544 $feedbackdata = array();
546 //Cache some strings
547 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
548 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
549 if ($categoriesmods = $DB->get_records('question_categories',
550 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
551 //Sort categories following their tree (parent-child) relationships
552 //this will make the feedback more readable
553 $categoriesmods = sort_categories_by_tree($categoriesmods);
555 foreach ($categoriesmods as $category) {
557 //Delete it completely (questions and category itself)
558 //deleting questions
559 if ($questions = $DB->get_records('question',
560 array('category' => $category->id), '', 'id,qtype')) {
561 foreach ($questions as $question) {
562 question_delete_question($question->id);
564 $DB->delete_records("question", array("category"=>$category->id));
566 //delete the category
567 $DB->delete_records('question_categories', array('id'=>$category->id));
569 //Fill feedback
570 $feedbackdata[] = array($category->name, $strcatdeleted);
572 //Inform about changes performed if feedback is enabled
573 if ($feedback) {
574 $table = new html_table();
575 $table->head = array(get_string('category', 'quiz'), get_string('action'));
576 $table->data = $feedbackdata;
577 echo html_writer::table($table);
580 return true;
584 * This function should be considered private to the question bank, it is called from
585 * question/editlib.php question/contextmoveq.php and a few similar places to to the
586 * work of acutally moving questions and associated data. However, callers of this
587 * function also have to do other work, which is why you should not call this method
588 * directly from outside the questionbank.
590 * @param string $questionids a comma-separated list of question ids.
591 * @param integer $newcategoryid the id of the category to move to.
593 function question_move_questions_to_category($questionids, $newcategoryid) {
594 global $DB;
596 $newcontextid = $DB->get_field('question_categories', 'contextid',
597 array('id' => $newcategoryid));
598 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
599 $questions = $DB->get_records_sql("
600 SELECT q.id, q.qtype, qc.contextid
601 FROM {question} q
602 JOIN {question_categories} qc ON q.category = qc.id
603 WHERE q.id $questionidcondition", $params);
604 foreach ($questions as $question) {
605 if ($newcontextid != $question->contextid) {
606 question_bank::get_qtype($question->qtype)->move_files(
607 $question->id, $question->contextid, $newcontextid);
611 // Move the questions themselves.
612 $DB->set_field_select('question', 'category', $newcategoryid,
613 "id $questionidcondition", $params);
615 // Move any subquestions belonging to them.
616 $DB->set_field_select('question', 'category', $newcategoryid,
617 "parent $questionidcondition", $params);
619 // TODO Deal with datasets.
621 return true;
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) {
633 global $DB;
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);
642 $subcatids = $DB->get_records_menu('question_categories',
643 array('parent' => $categoryid), '', 'id,1');
644 foreach ($subcatids as $subcatid => $notused) {
645 $DB->set_field('question_categories', 'contextid', $newcontextid,
646 array('id' => $subcatid));
647 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
652 * Generate the URL for starting a new preview of a given question with the given options.
653 * @param integer $questionid the question to preview.
654 * @param string $preferredbehaviour the behaviour to use for the preview.
655 * @param float $maxmark the maximum to mark the question out of.
656 * @param question_display_options $displayoptions the display options to use.
657 * @param int $variant the variant of the question to preview. If null, one will
658 * be picked randomly.
659 * @return string the URL.
661 function question_preview_url($questionid, $preferredbehaviour = null,
662 $maxmark = null, $displayoptions = null, $variant = null) {
664 $params = array('id' => $questionid);
666 if (!is_null($preferredbehaviour)) {
667 $params['behaviour'] = $preferredbehaviour;
670 if (!is_null($maxmark)) {
671 $params['maxmark'] = $maxmark;
674 if (!is_null($displayoptions)) {
675 $params['correctness'] = $displayoptions->correctness;
676 $params['marks'] = $displayoptions->marks;
677 $params['markdp'] = $displayoptions->markdp;
678 $params['feedback'] = (bool) $displayoptions->feedback;
679 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
680 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
681 $params['history'] = (bool) $displayoptions->history;
684 if ($variant) {
685 $params['variant'] = $variant;
688 return new moodle_url('/question/preview.php', $params);
692 * @return array that can be passed as $params to the {@link popup_action} constructor.
694 function question_preview_popup_params() {
695 return array(
696 'height' => 600,
697 'width' => 800,
702 * Given a list of ids, load the basic information about a set of questions from
703 * the questions table. The $join and $extrafields arguments can be used together
704 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
705 * read the code below to see how the SQL is assembled. Throws exceptions on error.
707 * @global object
708 * @global object
709 * @param array $questionids array of question ids.
710 * @param string $extrafields extra SQL code to be added to the query.
711 * @param string $join extra SQL code to be added to the query.
712 * @param array $extraparams values for any placeholders in $join.
713 * You are strongly recommended to use named placeholder.
715 * @return array partially complete question objects. You need to call get_question_options
716 * on them before they can be properly used.
718 function question_preload_questions($questionids, $extrafields = '', $join = '',
719 $extraparams = array()) {
720 global $DB;
721 if (empty($questionids)) {
722 return array();
724 if ($join) {
725 $join = ' JOIN '.$join;
727 if ($extrafields) {
728 $extrafields = ', ' . $extrafields;
730 list($questionidcondition, $params) = $DB->get_in_or_equal(
731 $questionids, SQL_PARAMS_NAMED, 'qid0000');
732 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
733 JOIN {question_categories} qc ON q.category = qc.id' .
734 $join .
735 ' WHERE q.id ' . $questionidcondition;
737 // Load the questions
738 if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
739 return array();
742 foreach ($questions as $question) {
743 $question->_partiallyloaded = true;
746 // Note, a possible optimisation here would be to not load the TEXT fields
747 // (that is, questiontext and generalfeedback) here, and instead load them in
748 // question_load_questions. That would add one DB query, but reduce the amount
749 // of data transferred most of the time. I am not going to do this optimisation
750 // until it is shown to be worthwhile.
752 return $questions;
756 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
757 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
758 * read the code below to see how the SQL is assembled. Throws exceptions on error.
760 * @param array $questionids array of question ids.
761 * @param string $extrafields extra SQL code to be added to the query.
762 * @param string $join extra SQL code to be added to the query.
763 * @param array $extraparams values for any placeholders in $join.
764 * You are strongly recommended to use named placeholder.
766 * @return array question objects.
768 function question_load_questions($questionids, $extrafields = '', $join = '') {
769 $questions = question_preload_questions($questionids, $extrafields, $join);
771 // Load the question type specific information
772 if (!get_question_options($questions)) {
773 return 'Could not load the question options';
776 return $questions;
780 * Private function to factor common code out of get_question_options().
782 * @param object $question the question to tidy.
783 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
785 function _tidy_question($question, $loadtags = false) {
786 global $CFG;
787 if (!question_bank::is_qtype_installed($question->qtype)) {
788 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
789 'qtype_missingtype')) . $question->questiontext;
791 question_bank::get_qtype($question->qtype)->get_question_options($question);
792 if (isset($question->_partiallyloaded)) {
793 unset($question->_partiallyloaded);
795 if ($loadtags && !empty($CFG->usetags)) {
796 require_once($CFG->dirroot . '/tag/lib.php');
797 $question->tags = tag_get_tags_array('question', $question->id);
802 * Updates the question objects with question type specific
803 * information by calling {@link get_question_options()}
805 * Can be called either with an array of question objects or with a single
806 * question object.
808 * @param mixed $questions Either an array of question objects to be updated
809 * or just a single question object
810 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
811 * @return bool Indicates success or failure.
813 function get_question_options(&$questions, $loadtags = false) {
814 if (is_array($questions)) { // deal with an array of questions
815 foreach ($questions as $i => $notused) {
816 _tidy_question($questions[$i], $loadtags);
818 } else { // deal with single question
819 _tidy_question($questions, $loadtags);
821 return true;
825 * Print the icon for the question type
827 * @param object $question The question object for which the icon is required.
828 * Only $question->qtype is used.
829 * @return string the HTML for the img tag.
831 function print_question_icon($question) {
832 global $OUTPUT;
834 $qtype = question_bank::get_qtype($question->qtype, false);
835 $namestr = $qtype->menu_name();
837 // TODO convert to return a moodle_icon object, or whatever the class is.
838 $html = '<img src="' . $OUTPUT->pix_url('icon', $qtype->plugin_name()) . '" alt="' .
839 $namestr . '" title="' . $namestr . '" />';
841 return $html;
845 * Creates a stamp that uniquely identifies this version of the question
847 * In future we want this to use a hash of the question data to guarantee that
848 * identical versions have the same version stamp.
850 * @param object $question
851 * @return string A unique version stamp
853 function question_hash($question) {
854 return make_unique_id_code();
857 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
859 * Get anything that needs to be included in the head of the question editing page
860 * for a particular question type. This function is called by question/question.php.
862 * @param $question A question object. Only $question->qtype is used.
863 * @return string Deprecated. Some HTML code that can go inside the head tag.
865 function question_get_editing_head_contributions($question) {
866 question_bank::get_qtype($question->qtype, false)->get_editing_head_contributions();
870 * Saves question options
872 * Simply calls the question type specific save_question_options() method.
874 function save_question_options($question) {
875 question_bank::get_qtype($question->qtype)->save_question_options($question);
878 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
881 * returns the categories with their names ordered following parent-child relationships
882 * finally it tries to return pending categories (those being orphaned, whose parent is
883 * incorrect) to avoid missing any category from original array.
885 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
886 global $DB;
888 $children = array();
889 $keys = array_keys($categories);
891 foreach ($keys as $key) {
892 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
893 $children[$key] = $categories[$key];
894 $categories[$key]->processed = true;
895 $children = $children + sort_categories_by_tree(
896 $categories, $children[$key]->id, $level+1);
899 //If level = 1, we have finished, try to look for non processed categories
900 // (bad parent) and sort them too
901 if ($level == 1) {
902 foreach ($keys as $key) {
903 // If not processed and it's a good candidate to start (because its
904 // parent doesn't exist in the course)
905 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
906 array('contextid' => $categories[$key]->contextid,
907 'id' => $categories[$key]->parent))) {
908 $children[$key] = $categories[$key];
909 $categories[$key]->processed = true;
910 $children = $children + sort_categories_by_tree(
911 $categories, $children[$key]->id, $level + 1);
915 return $children;
919 * Private method, only for the use of add_indented_names().
921 * Recursively adds an indentedname field to each category, starting with the category
922 * with id $id, and dealing with that category and all its children, and
923 * return a new array, with those categories in the right order.
925 * @param array $categories an array of categories which has had childids
926 * fields added by flatten_category_tree(). Passed by reference for
927 * performance only. It is not modfied.
928 * @param int $id the category to start the indenting process from.
929 * @param int $depth the indent depth. Used in recursive calls.
930 * @return array a new array of categories, in the right order for the tree.
932 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
934 // Indent the name of this category.
935 $newcategories = array();
936 $newcategories[$id] = $categories[$id];
937 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
938 $categories[$id]->name;
940 // Recursively indent the children.
941 foreach ($categories[$id]->childids as $childid) {
942 if ($childid != $nochildrenof) {
943 $newcategories = $newcategories + flatten_category_tree(
944 $categories, $childid, $depth + 1, $nochildrenof);
948 // Remove the childids array that were temporarily added.
949 unset($newcategories[$id]->childids);
951 return $newcategories;
955 * Format categories into an indented list reflecting the tree structure.
957 * @param array $categories An array of category objects, for example from the.
958 * @return array The formatted list of categories.
960 function add_indented_names($categories, $nochildrenof = -1) {
962 // Add an array to each category to hold the child category ids. This array
963 // will be removed again by flatten_category_tree(). It should not be used
964 // outside these two functions.
965 foreach (array_keys($categories) as $id) {
966 $categories[$id]->childids = array();
969 // Build the tree structure, and record which categories are top-level.
970 // We have to be careful, because the categories array may include published
971 // categories from other courses, but not their parents.
972 $toplevelcategoryids = array();
973 foreach (array_keys($categories) as $id) {
974 if (!empty($categories[$id]->parent) &&
975 array_key_exists($categories[$id]->parent, $categories)) {
976 $categories[$categories[$id]->parent]->childids[] = $id;
977 } else {
978 $toplevelcategoryids[] = $id;
982 // Flatten the tree to and add the indents.
983 $newcategories = array();
984 foreach ($toplevelcategoryids as $id) {
985 $newcategories = $newcategories + flatten_category_tree(
986 $categories, $id, 0, $nochildrenof);
989 return $newcategories;
993 * Output a select menu of question categories.
995 * Categories from this course and (optionally) published categories from other courses
996 * are included. Optionally, only categories the current user may edit can be included.
998 * @param integer $courseid the id of the course to get the categories for.
999 * @param integer $published if true, include publised categories from other courses.
1000 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1001 * @param integer $selected optionally, the id of a category to be selected by
1002 * default in the dropdown.
1004 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1005 $selected = "", $nochildrenof = -1) {
1006 global $OUTPUT;
1007 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1008 false, $nochildrenof);
1009 if ($selected) {
1010 $choose = '';
1011 } else {
1012 $choose = 'choosedots';
1014 $options = array();
1015 foreach ($categoriesarray as $group => $opts) {
1016 $options[] = array($group => $opts);
1019 echo html_writer::select($options, 'category', $selected, $choose);
1023 * @param integer $contextid a context id.
1024 * @return object the default question category for that context, or false if none.
1026 function question_get_default_category($contextid) {
1027 global $DB;
1028 $category = $DB->get_records('question_categories',
1029 array('contextid' => $contextid), 'id', '*', 0, 1);
1030 if (!empty($category)) {
1031 return reset($category);
1032 } else {
1033 return false;
1038 * Gets the default category in the most specific context.
1039 * If no categories exist yet then default ones are created in all contexts.
1041 * @param array $contexts The context objects for this context and all parent contexts.
1042 * @return object The default category - the category in the course context
1044 function question_make_default_categories($contexts) {
1045 global $DB;
1046 static $preferredlevels = array(
1047 CONTEXT_COURSE => 4,
1048 CONTEXT_MODULE => 3,
1049 CONTEXT_COURSECAT => 2,
1050 CONTEXT_SYSTEM => 1,
1053 $toreturn = null;
1054 $preferredness = 0;
1055 // If it already exists, just return it.
1056 foreach ($contexts as $key => $context) {
1057 if (!$exists = $DB->record_exists("question_categories",
1058 array('contextid' => $context->id))) {
1059 // Otherwise, we need to make one
1060 $category = new stdClass();
1061 $contextname = print_context_name($context, false, true);
1062 $category->name = get_string('defaultfor', 'question', $contextname);
1063 $category->info = get_string('defaultinfofor', 'question', $contextname);
1064 $category->contextid = $context->id;
1065 $category->parent = 0;
1066 // By default, all categories get this number, and are sorted alphabetically.
1067 $category->sortorder = 999;
1068 $category->stamp = make_unique_id_code();
1069 $category->id = $DB->insert_record('question_categories', $category);
1070 } else {
1071 $category = question_get_default_category($context->id);
1073 if ($preferredlevels[$context->contextlevel] > $preferredness && has_any_capability(
1074 array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1075 $toreturn = $category;
1076 $preferredness = $preferredlevels[$context->contextlevel];
1080 if (!is_null($toreturn)) {
1081 $toreturn = clone($toreturn);
1083 return $toreturn;
1087 * Get all the category objects, including a count of the number of questions in that category,
1088 * for all the categories in the lists $contexts.
1090 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1091 * @param string $sortorder used as the ORDER BY clause in the select statement.
1092 * @return array of category objects.
1094 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1095 global $DB;
1096 return $DB->get_records_sql("
1097 SELECT c.*, (SELECT count(1) FROM {question} q
1098 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1099 FROM {question_categories} c
1100 WHERE c.contextid IN ($contexts)
1101 ORDER BY $sortorder");
1105 * Output an array of question categories.
1107 function question_category_options($contexts, $top = false, $currentcat = 0,
1108 $popupform = false, $nochildrenof = -1) {
1109 global $CFG;
1110 $pcontexts = array();
1111 foreach ($contexts as $context) {
1112 $pcontexts[] = $context->id;
1114 $contextslist = join($pcontexts, ', ');
1116 $categories = get_categories_for_contexts($contextslist);
1118 $categories = question_add_context_in_key($categories);
1120 if ($top) {
1121 $categories = question_add_tops($categories, $pcontexts);
1123 $categories = add_indented_names($categories, $nochildrenof);
1125 // sort cats out into different contexts
1126 $categoriesarray = array();
1127 foreach ($pcontexts as $pcontext) {
1128 $contextstring = print_context_name(
1129 get_context_instance_by_id($pcontext), true, true);
1130 foreach ($categories as $category) {
1131 if ($category->contextid == $pcontext) {
1132 $cid = $category->id;
1133 if ($currentcat != $cid || $currentcat == 0) {
1134 $countstring = !empty($category->questioncount) ?
1135 " ($category->questioncount)" : '';
1136 $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
1141 if ($popupform) {
1142 $popupcats = array();
1143 foreach ($categoriesarray as $contextstring => $optgroup) {
1144 $group = array();
1145 foreach ($optgroup as $key => $value) {
1146 $key = str_replace($CFG->wwwroot, '', $key);
1147 $group[$key] = $value;
1149 $popupcats[] = array($contextstring => $group);
1151 return $popupcats;
1152 } else {
1153 return $categoriesarray;
1157 function question_add_context_in_key($categories) {
1158 $newcatarray = array();
1159 foreach ($categories as $id => $category) {
1160 $category->parent = "$category->parent,$category->contextid";
1161 $category->id = "$category->id,$category->contextid";
1162 $newcatarray["$id,$category->contextid"] = $category;
1164 return $newcatarray;
1167 function question_add_tops($categories, $pcontexts) {
1168 $topcats = array();
1169 foreach ($pcontexts as $context) {
1170 $newcat = new stdClass();
1171 $newcat->id = "0,$context";
1172 $newcat->name = get_string('top');
1173 $newcat->parent = -1;
1174 $newcat->contextid = $context;
1175 $topcats["0,$context"] = $newcat;
1177 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1178 return array_merge($topcats, $categories);
1182 * @return array of question category ids of the category and all subcategories.
1184 function question_categorylist($categoryid) {
1185 global $DB;
1187 $subcategories = $DB->get_records('question_categories',
1188 array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
1190 $categorylist = array($categoryid);
1191 foreach ($subcategories as $subcategory) {
1192 $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
1195 return $categorylist;
1198 //===========================
1199 // Import/Export Functions
1200 //===========================
1203 * Get list of available import or export formats
1204 * @param string $type 'import' if import list, otherwise export list assumed
1205 * @return array sorted list of import/export formats available
1207 function get_import_export_formats($type) {
1208 global $CFG;
1210 $fileformats = get_plugin_list('qformat');
1212 $fileformatname = array();
1213 require_once($CFG->dirroot . '/question/format.php');
1214 foreach ($fileformats as $fileformat => $fdir) {
1215 $formatfile = $fdir . '/format.php';
1216 if (is_readable($formatfile)) {
1217 include_once($formatfile);
1218 } else {
1219 continue;
1222 $classname = 'qformat_' . $fileformat;
1223 $formatclass = new $classname();
1224 if ($type == 'import') {
1225 $provided = $formatclass->provide_import();
1226 } else {
1227 $provided = $formatclass->provide_export();
1230 if ($provided) {
1231 $fileformatnames[$fileformat] = get_string($fileformat, 'qformat_' . $fileformat);
1235 textlib_get_instance()->asort($fileformatnames);
1236 return $fileformatnames;
1241 * Create a reasonable default file name for exporting questions from a particular
1242 * category.
1243 * @param object $course the course the questions are in.
1244 * @param object $category the question category.
1245 * @return string the filename.
1247 function question_default_export_filename($course, $category) {
1248 // We build a string that is an appropriate name (questions) from the lang pack,
1249 // then the corse shortname, then the question category name, then a timestamp.
1251 $base = clean_filename(get_string('exportfilename', 'question'));
1253 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1254 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1256 $shortname = clean_filename($course->shortname);
1257 if ($shortname == '' || $shortname == '_' ) {
1258 $shortname = $course->id;
1261 $categoryname = clean_filename(format_string($category->name));
1263 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1265 return $export_name;
1269 * Converts contextlevels to strings and back to help with reading/writing contexts
1270 * to/from import/export files.
1272 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1275 class context_to_string_translator{
1277 * @var array used to translate between contextids and strings for this context.
1279 protected $contexttostringarray = array();
1281 public function __construct($contexts) {
1282 $this->generate_context_to_string_array($contexts);
1285 public function context_to_string($contextid) {
1286 return $this->contexttostringarray[$contextid];
1289 public function string_to_context($contextname) {
1290 $contextid = array_search($contextname, $this->contexttostringarray);
1291 return $contextid;
1294 protected function generate_context_to_string_array($contexts) {
1295 if (!$this->contexttostringarray) {
1296 $catno = 1;
1297 foreach ($contexts as $context) {
1298 switch ($context->contextlevel) {
1299 case CONTEXT_MODULE :
1300 $contextstring = 'module';
1301 break;
1302 case CONTEXT_COURSE :
1303 $contextstring = 'course';
1304 break;
1305 case CONTEXT_COURSECAT :
1306 $contextstring = "cat$catno";
1307 $catno++;
1308 break;
1309 case CONTEXT_SYSTEM :
1310 $contextstring = 'system';
1311 break;
1313 $this->contexttostringarray[$context->id] = $contextstring;
1321 * Check capability on category
1323 * @param mixed $question object or id
1324 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1325 * @param integer $cachecat useful to cache all question records in a category
1326 * @return boolean this user has the capability $cap for this question $question?
1328 function question_has_capability_on($question, $cap, $cachecat = -1) {
1329 global $USER, $DB;
1331 // these are capabilities on existing questions capabilties are
1332 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1333 $question_questioncaps = array('edit', 'view', 'use', 'move');
1334 static $questions = array();
1335 static $categories = array();
1336 static $cachedcat = array();
1337 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1338 $questions += $DB->get_records('question', array('category' => $cachecat));
1339 $cachedcat[] = $cachecat;
1341 if (!is_object($question)) {
1342 if (!isset($questions[$question])) {
1343 if (!$questions[$question] = $DB->get_record('question',
1344 array('id' => $question), 'id,category,createdby')) {
1345 print_error('questiondoesnotexist', 'question');
1348 $question = $questions[$question];
1350 if (!isset($categories[$question->category])) {
1351 if (!$categories[$question->category] = $DB->get_record('question_categories',
1352 array('id'=>$question->category))) {
1353 print_error('invalidcategory', 'quiz');
1356 $category = $categories[$question->category];
1357 $context = get_context_instance_by_id($category->contextid);
1359 if (array_search($cap, $question_questioncaps)!== false) {
1360 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1361 if ($question->createdby == $USER->id) {
1362 return has_capability('moodle/question:' . $cap . 'mine', $context);
1363 } else {
1364 return false;
1366 } else {
1367 return true;
1369 } else {
1370 return has_capability('moodle/question:' . $cap, $context);
1376 * Require capability on question.
1378 function question_require_capability_on($question, $cap) {
1379 if (!question_has_capability_on($question, $cap)) {
1380 print_error('nopermissions', '', '', $cap);
1382 return true;
1386 * Get the real state - the correct question id and answer - for a random
1387 * question.
1388 * @param object $state with property answer.
1389 * @return mixed return integer real question id or false if there was an
1390 * error..
1392 function question_get_real_state($state) {
1393 global $OUTPUT;
1394 $realstate = clone($state);
1395 $matches = array();
1396 if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)) {
1397 echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics'));
1398 return false;
1399 } else {
1400 $realstate->question = $matches[1];
1401 $realstate->answer = $matches[2];
1402 return $realstate;
1407 * @param object $context a context
1408 * @return string A URL for editing questions in this context.
1410 function question_edit_url($context) {
1411 global $CFG, $SITE;
1412 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1413 return false;
1415 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1416 $defaultcategory = question_get_default_category($context->id);
1417 if ($defaultcategory) {
1418 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1420 switch ($context->contextlevel) {
1421 case CONTEXT_SYSTEM:
1422 return $baseurl . 'courseid=' . $SITE->id;
1423 case CONTEXT_COURSECAT:
1424 // This is nasty, becuase we can only edit questions in a course
1425 // context at the moment, so for now we just return false.
1426 return false;
1427 case CONTEXT_COURSE:
1428 return $baseurl . 'courseid=' . $context->instanceid;
1429 case CONTEXT_MODULE:
1430 return $baseurl . 'cmid=' . $context->instanceid;
1436 * Adds question bank setting links to the given navigation node if caps are met.
1438 * @param navigation_node $navigationnode The navigation node to add the question branch to
1439 * @param object $context
1440 * @return navigation_node Returns the question branch that was added
1442 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1443 global $PAGE;
1445 if ($context->contextlevel == CONTEXT_COURSE) {
1446 $params = array('courseid'=>$context->instanceid);
1447 } else if ($context->contextlevel == CONTEXT_MODULE) {
1448 $params = array('cmid'=>$context->instanceid);
1449 } else {
1450 return;
1453 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1454 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1456 $contexts = new question_edit_contexts($context);
1457 if ($contexts->have_one_edit_tab_cap('questions')) {
1458 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1459 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1461 if ($contexts->have_one_edit_tab_cap('categories')) {
1462 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1463 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1465 if ($contexts->have_one_edit_tab_cap('import')) {
1466 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1467 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1469 if ($contexts->have_one_edit_tab_cap('export')) {
1470 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1471 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1474 return $questionnode;
1478 * @return array all the capabilities that relate to accessing particular questions.
1480 function question_get_question_capabilities() {
1481 return array(
1482 'moodle/question:add',
1483 'moodle/question:editmine',
1484 'moodle/question:editall',
1485 'moodle/question:viewmine',
1486 'moodle/question:viewall',
1487 'moodle/question:usemine',
1488 'moodle/question:useall',
1489 'moodle/question:movemine',
1490 'moodle/question:moveall',
1495 * @return array all the question bank capabilities.
1497 function question_get_all_capabilities() {
1498 $caps = question_get_question_capabilities();
1499 $caps[] = 'moodle/question:managecategory';
1500 $caps[] = 'moodle/question:flag';
1501 return $caps;
1504 class question_edit_contexts {
1506 public static $caps = array(
1507 'editq' => array('moodle/question:add',
1508 'moodle/question:editmine',
1509 'moodle/question:editall',
1510 'moodle/question:viewmine',
1511 'moodle/question:viewall',
1512 'moodle/question:usemine',
1513 'moodle/question:useall',
1514 'moodle/question:movemine',
1515 'moodle/question:moveall'),
1516 'questions'=>array('moodle/question:add',
1517 'moodle/question:editmine',
1518 'moodle/question:editall',
1519 'moodle/question:viewmine',
1520 'moodle/question:viewall',
1521 'moodle/question:movemine',
1522 'moodle/question:moveall'),
1523 'categories'=>array('moodle/question:managecategory'),
1524 'import'=>array('moodle/question:add'),
1525 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1527 protected $allcontexts;
1530 * @param current context
1532 public function __construct($thiscontext) {
1533 $pcontextids = get_parent_contexts($thiscontext);
1534 $contexts = array($thiscontext);
1535 foreach ($pcontextids as $pcontextid) {
1536 $contexts[] = get_context_instance_by_id($pcontextid);
1538 $this->allcontexts = $contexts;
1541 * @return array all parent contexts
1543 public function all() {
1544 return $this->allcontexts;
1547 * @return object lowest context which must be either the module or course context
1549 public function lowest() {
1550 return $this->allcontexts[0];
1553 * @param string $cap capability
1554 * @return array parent contexts having capability, zero based index
1556 public function having_cap($cap) {
1557 $contextswithcap = array();
1558 foreach ($this->allcontexts as $context) {
1559 if (has_capability($cap, $context)) {
1560 $contextswithcap[] = $context;
1563 return $contextswithcap;
1566 * @param array $caps capabilities
1567 * @return array parent contexts having at least one of $caps, zero based index
1569 public function having_one_cap($caps) {
1570 $contextswithacap = array();
1571 foreach ($this->allcontexts as $context) {
1572 foreach ($caps as $cap) {
1573 if (has_capability($cap, $context)) {
1574 $contextswithacap[] = $context;
1575 break; //done with caps loop
1579 return $contextswithacap;
1582 * @param string $tabname edit tab name
1583 * @return array parent contexts having at least one of $caps, zero based index
1585 public function having_one_edit_tab_cap($tabname) {
1586 return $this->having_one_cap(self::$caps[$tabname]);
1589 * Has at least one parent context got the cap $cap?
1591 * @param string $cap capability
1592 * @return boolean
1594 public function have_cap($cap) {
1595 return (count($this->having_cap($cap)));
1599 * Has at least one parent context got one of the caps $caps?
1601 * @param array $caps capability
1602 * @return boolean
1604 public function have_one_cap($caps) {
1605 foreach ($caps as $cap) {
1606 if ($this->have_cap($cap)) {
1607 return true;
1610 return false;
1614 * Has at least one parent context got one of the caps for actions on $tabname
1616 * @param string $tabname edit tab name
1617 * @return boolean
1619 public function have_one_edit_tab_cap($tabname) {
1620 return $this->have_one_cap(self::$caps[$tabname]);
1624 * Throw error if at least one parent context hasn't got the cap $cap
1626 * @param string $cap capability
1628 public function require_cap($cap) {
1629 if (!$this->have_cap($cap)) {
1630 print_error('nopermissions', '', '', $cap);
1635 * Throw error if at least one parent context hasn't got one of the caps $caps
1637 * @param array $cap capabilities
1639 public function require_one_cap($caps) {
1640 if (!$this->have_one_cap($caps)) {
1641 $capsstring = join($caps, ', ');
1642 print_error('nopermissions', '', '', $capsstring);
1647 * Throw error if at least one parent context hasn't got one of the caps $caps
1649 * @param string $tabname edit tab name
1651 public function require_one_edit_tab_cap($tabname) {
1652 if (!$this->have_one_edit_tab_cap($tabname)) {
1653 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1659 * Rewrite question url, file_rewrite_pluginfile_urls always build url by
1660 * $file/$contextid/$component/$filearea/$itemid/$pathname_in_text, so we cannot add
1661 * extra questionid and attempted in url by it, so we create quiz_rewrite_question_urls
1662 * to build url here
1664 * @param string $text text being processed
1665 * @param string $file the php script used to serve files
1666 * @param int $contextid
1667 * @param string $component component
1668 * @param string $filearea filearea
1669 * @param array $ids other IDs will be used to check file permission
1670 * @param int $itemid
1671 * @param array $options
1672 * @return string
1674 function question_rewrite_question_urls($text, $file, $contextid, $component,
1675 $filearea, array $ids, $itemid, array $options=null) {
1676 global $CFG;
1678 $options = (array)$options;
1679 if (!isset($options['forcehttps'])) {
1680 $options['forcehttps'] = false;
1683 if (!$CFG->slasharguments) {
1684 $file = $file . '?file=';
1687 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
1689 if (!empty($ids)) {
1690 $baseurl .= (implode('/', $ids) . '/');
1693 if ($itemid !== null) {
1694 $baseurl .= "$itemid/";
1697 if ($options['forcehttps']) {
1698 $baseurl = str_replace('http://', 'https://', $baseurl);
1701 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
1705 * Called by pluginfile.php to serve files related to the 'question' core
1706 * component and for files belonging to qtypes.
1708 * For files that relate to questions in a question_attempt, then we delegate to
1709 * a function in the component that owns the attempt (for example in the quiz,
1710 * or in core question preview) to get necessary inforation.
1712 * (Note that, at the moment, all question file areas relate to questions in
1713 * attempts, so the If at the start of the last paragraph is always true.)
1715 * Does not return, either calls send_file_not_found(); or serves the file.
1717 * @param object $course course settings object
1718 * @param object $context context object
1719 * @param string $component the name of the component we are serving files for.
1720 * @param string $filearea the name of the file area.
1721 * @param array $args the remaining bits of the file path.
1722 * @param bool $forcedownload whether the user must be forced to download the file.
1724 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload) {
1725 global $DB, $CFG;
1727 list($context, $course, $cm) = get_context_info_array($context->id);
1728 require_login($course, false, $cm);
1730 if ($filearea === 'export') {
1731 require_once($CFG->dirroot . '/question/editlib.php');
1732 $contexts = new question_edit_contexts($context);
1733 // check export capability
1734 $contexts->require_one_edit_tab_cap('export');
1735 $category_id = (int)array_shift($args);
1736 $format = array_shift($args);
1737 $cattofile = array_shift($args);
1738 $contexttofile = array_shift($args);
1739 $filename = array_shift($args);
1741 // load parent class for import/export
1742 require_once($CFG->dirroot . '/question/format.php');
1743 require_once($CFG->dirroot . '/question/editlib.php');
1744 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1746 $classname = 'qformat_' . $format;
1747 if (!class_exists($classname)) {
1748 send_file_not_found();
1751 $qformat = new $classname();
1753 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1754 send_file_not_found();
1757 $qformat->setCategory($category);
1758 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1759 $qformat->setCourse($course);
1761 if ($cattofile == 'withcategories') {
1762 $qformat->setCattofile(true);
1763 } else {
1764 $qformat->setCattofile(false);
1767 if ($contexttofile == 'withcontexts') {
1768 $qformat->setContexttofile(true);
1769 } else {
1770 $qformat->setContexttofile(false);
1773 if (!$qformat->exportpreprocess()) {
1774 send_file_not_found();
1775 print_error('exporterror', 'question', $thispageurl->out());
1778 // export data to moodle file pool
1779 if (!$content = $qformat->exportprocess(true)) {
1780 send_file_not_found();
1783 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1786 $qubaid = (int)array_shift($args);
1787 $slot = (int)array_shift($args);
1789 $module = $DB->get_field('question_usages', 'component',
1790 array('id' => $qubaid));
1792 if ($module === 'core_question_preview') {
1793 require_once($CFG->dirroot . '/question/previewlib.php');
1794 return question_preview_question_pluginfile($course, $context,
1795 $component, $filearea, $qubaid, $slot, $args, $forcedownload);
1797 } else {
1798 $dir = get_component_directory($module);
1799 if (!file_exists("$dir/lib.php")) {
1800 send_file_not_found();
1802 include_once("$dir/lib.php");
1804 $filefunction = $module . '_question_pluginfile';
1805 if (!function_exists($filefunction)) {
1806 send_file_not_found();
1809 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1810 $args, $forcedownload);
1812 send_file_not_found();
1817 * Create url for question export
1819 * @param int $contextid, current context
1820 * @param int $categoryid, categoryid
1821 * @param string $format
1822 * @param string $withcategories
1823 * @param string $ithcontexts
1824 * @param moodle_url export file url
1826 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1827 $withcontexts, $filename) {
1828 global $CFG;
1829 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1830 return moodle_url::make_file_url($urlbase,
1831 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1832 "/{$withcontexts}/{$filename}", true);