2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * Returns an array of names of activity modules that use this question
120 * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
122 * @param object $questionid
123 * @return array of strings
125 function question_list_instances($questionid) {
126 throw new coding_exception('question_list_instances has been deprectated. ' .
127 'Please use questions_in_use instead.');
131 * @param array $questionids of question ids.
132 * @return boolean whether any of these questions are being used by any part of Moodle.
134 function questions_in_use($questionids) {
137 if (question_engine
::questions_in_use($questionids)) {
141 foreach (get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
146 $fn = $module . '_questions_in_use';
147 if (function_exists($fn)) {
148 if ($fn($questionids)) {
153 // Fallback for legacy modules.
154 $fn = $module . '_question_list_instances';
155 if (function_exists($fn)) {
156 foreach ($questionids as $questionid) {
157 $instances = $fn($questionid);
158 if (!empty($instances)) {
171 * Determine whether there arey any questions belonging to this context, that is whether any of its
172 * question categories contain any questions. This will return true even if all the questions are
175 * @param mixed $context either a context object, or a context id.
176 * @return boolean whether any of the question categories beloning to this context have
177 * any questions in them.
179 function question_context_has_any_questions($context) {
181 if (is_object($context)) {
182 $contextid = $context->id
;
183 } else if (is_numeric($context)) {
184 $contextid = $context;
186 print_error('invalidcontextinhasanyquestions', 'question');
188 return $DB->record_exists_sql("SELECT *
190 JOIN {question_categories} qc ON qc.id = q.category
191 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
195 * Returns list of 'allowed' grades for grade selection
196 * formatted suitably for dropdown box function
198 * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
199 * {@link question_bank::fraction_options_full()} instead.
201 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
203 function get_grade_options() {
204 $grades = new stdClass();
205 $grades->gradeoptions
= question_bank
::fraction_options();
206 $grades->gradeoptionsfull
= question_bank
::fraction_options_full();
212 * Check whether a given grade is one of a list of allowed options. If not,
213 * depending on $matchgrades, either return the nearest match, or return false
214 * to signal an error.
215 * @param array $gradeoptionsfull list of valid options
216 * @param int $grade grade to be tested
217 * @param string $matchgrades 'error' or 'nearest'
218 * @return mixed either 'fixed' value or false if error.
220 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
222 if ($matchgrades == 'error') {
223 // (Almost) exact match, or an error.
224 foreach ($gradeoptionsfull as $value => $option) {
225 // Slightly fuzzy test, never check floats for equality.
226 if (abs($grade - $value) < 0.00001) {
227 return $value; // Be sure the return the proper value.
230 // Didn't find a match so that's an error.
233 } else if ($matchgrades == 'nearest') {
234 // Work out nearest value
237 foreach ($gradeoptionsfull as $value => $option) {
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
241 $bestmismatch = $newmismatch;
247 // Unknow option passed.
248 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
249 ' passed to match_grade_options');
254 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
255 * @param integer $categoryid a question category id.
256 * @param boolean $recursive whether to check child categories too.
257 * @return boolean whether any question in this category is in use.
259 function question_category_isused($categoryid, $recursive = false) {
260 throw new coding_exception('question_category_isused has been deprectated. ' .
261 'Please use question_category_in_use instead.');
265 * Tests whether any question in a category is used by any part of Moodle.
267 * @param integer $categoryid a question category id.
268 * @param boolean $recursive whether to check child categories too.
269 * @return boolean whether any question in this category is in use.
271 function question_category_in_use($categoryid, $recursive = false) {
274 //Look at each question in the category
275 if ($questions = $DB->get_records_menu('question',
276 array('category' => $categoryid), '', 'id, 1')) {
277 if (questions_in_use(array_keys($questions))) {
285 //Look under child categories recursively
286 if ($children = $DB->get_records('question_categories',
287 array('parent' => $categoryid), '', 'id, 1')) {
288 foreach ($children as $child) {
289 if (question_category_in_use($child->id
, $recursive)) {
299 * Deletes question and all associated data from the database
301 * It will not delete a question if it is used by an activity module
302 * @param object $question The question being deleted
304 function question_delete_question($questionid) {
307 $question = $DB->get_record_sql('
308 SELECT q.*, qc.contextid
310 JOIN {question_categories} qc ON qc.id = q.category
311 WHERE q.id = ?', array($questionid));
313 // In some situations, for example if this was a child of a
314 // Cloze question that was previously deleted, the question may already
315 // have gone. In this case, just do nothing.
319 // Do not delete a question if it is used by an activity module
320 if (questions_in_use(array($questionid))) {
324 // Check permissions.
325 question_require_capability_on($question, 'edit');
327 $dm = new question_engine_data_mapper();
328 $dm->delete_previews($questionid);
330 // delete questiontype-specific data
331 question_bank
::get_qtype($question->qtype
, false)->delete_question(
332 $questionid, $question->contextid
);
334 // Now recursively delete all child questions
335 if ($children = $DB->get_records('question',
336 array('parent' => $questionid), '', 'id, qtype')) {
337 foreach ($children as $child) {
338 if ($child->id
!= $questionid) {
339 question_delete_question($child->id
);
344 // Finally delete the question record itself
345 $DB->delete_records('question', array('id' => $questionid));
346 question_bank
::notify_question_edited($questionid);
350 * All question categories and their questions are deleted for this course.
352 * @param stdClass $course an object representing the activity
353 * @param boolean $feedback to specify if the process must output a summary of its work
356 function question_delete_course($course, $feedback=true) {
359 //To store feedback to be showed at the end of the process
360 $feedbackdata = array();
363 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
364 $coursecontext = context_course
::instance($course->id
);
365 $categoriescourse = $DB->get_records('question_categories',
366 array('contextid' => $coursecontext->id
), 'parent', 'id, parent, name, contextid');
368 if ($categoriescourse) {
370 //Sort categories following their tree (parent-child) relationships
371 //this will make the feedback more readable
372 $categoriescourse = sort_categories_by_tree($categoriescourse);
374 foreach ($categoriescourse as $category) {
376 //Delete it completely (questions and category itself)
378 if ($questions = $DB->get_records('question',
379 array('category' => $category->id
), '', 'id,qtype')) {
380 foreach ($questions as $question) {
381 question_delete_question($question->id
);
383 $DB->delete_records("question", array("category" => $category->id
));
385 //delete the category
386 $DB->delete_records('question_categories', array('id' => $category->id
));
389 $feedbackdata[] = array($category->name
, $strcatdeleted);
391 //Inform about changes performed if feedback is enabled
393 $table = new html_table();
394 $table->head
= array(get_string('category', 'quiz'), get_string('action'));
395 $table->data
= $feedbackdata;
396 echo html_writer
::table($table);
403 * Category is about to be deleted,
404 * 1/ All question categories and their questions are deleted for this course category.
405 * 2/ All questions are moved to new category
407 * @param object $category course category object
408 * @param object $newcategory empty means everything deleted, otherwise id of
409 * category where content moved
410 * @param boolean $feedback to specify if the process must output a summary of its work
413 function question_delete_course_category($category, $newcategory, $feedback=true) {
416 $context = context_coursecat
::instance($category->id
);
417 if (empty($newcategory)) {
418 $feedbackdata = array(); // To store feedback to be showed at the end of the process
419 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
420 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
422 // Loop over question categories.
423 if ($categories = $DB->get_records('question_categories',
424 array('contextid'=>$context->id
), 'parent', 'id, parent, name')) {
425 foreach ($categories as $category) {
427 // Deal with any questions in the category.
428 if ($questions = $DB->get_records('question',
429 array('category' => $category->id
), '', 'id,qtype')) {
431 // Try to delete each question.
432 foreach ($questions as $question) {
433 question_delete_question($question->id
);
436 // Check to see if there were any questions that were kept because
437 // they are still in use somehow, even though quizzes in courses
438 // in this category will already have been deteted. This could
439 // happen, for example, if questions are added to a course,
440 // and then that course is moved to another category (MDL-14802).
441 $questionids = $DB->get_records_menu('question',
442 array('category'=>$category->id
), '', 'id, 1');
443 if (!empty($questionids)) {
444 if (!$rescueqcategory = question_save_from_deletion(
445 array_keys($questionids), get_parent_contextid($context),
446 print_context_name($context), $rescueqcategory)) {
449 $feedbackdata[] = array($category->name
,
450 get_string('questionsmovedto', 'question', $rescueqcategory->name
));
454 // Now delete the category.
455 if (!$DB->delete_records('question_categories', array('id'=>$category->id
))) {
458 $feedbackdata[] = array($category->name
, $strcatdeleted);
460 } // End loop over categories.
463 // Output feedback if requested.
464 if ($feedback and $feedbackdata) {
465 $table = new html_table();
466 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
467 $table->data
= $feedbackdata;
468 echo html_writer
::table($table);
472 // Move question categories ot the new context.
473 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
476 $DB->set_field('question_categories', 'contextid', $newcontext->id
,
477 array('contextid'=>$context->id
));
480 $a->oldplace
= print_context_name($context);
481 $a->newplace
= print_context_name($newcontext);
482 echo $OUTPUT->notification(
483 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
491 * Enter description here...
493 * @param array $questionids of question ids
494 * @param object $newcontext the context to create the saved category in.
495 * @param string $oldplace a textual description of the think being deleted,
496 * e.g. from get_context_name
497 * @param object $newcategory
498 * @return mixed false on
500 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
501 $newcategory = null) {
504 // Make a category in the parent context to move the questions to.
505 if (is_null($newcategory)) {
506 $newcategory = new stdClass();
507 $newcategory->parent
= 0;
508 $newcategory->contextid
= $newcontextid;
509 $newcategory->name
= get_string('questionsrescuedfrom', 'question', $oldplace);
510 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
511 $newcategory->sortorder
= 999;
512 $newcategory->stamp
= make_unique_id_code();
513 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
516 // Move any remaining questions to the 'saved' category.
517 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
524 * All question categories and their questions are deleted for this activity.
526 * @param object $cm the course module object representing the activity
527 * @param boolean $feedback to specify if the process must output a summary of its work
530 function question_delete_activity($cm, $feedback=true) {
533 //To store feedback to be showed at the end of the process
534 $feedbackdata = array();
537 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
538 $modcontext = context_module
::instance($cm->id
);
539 if ($categoriesmods = $DB->get_records('question_categories',
540 array('contextid' => $modcontext->id
), 'parent', 'id, parent, name, contextid')) {
541 //Sort categories following their tree (parent-child) relationships
542 //this will make the feedback more readable
543 $categoriesmods = sort_categories_by_tree($categoriesmods);
545 foreach ($categoriesmods as $category) {
547 //Delete it completely (questions and category itself)
549 if ($questions = $DB->get_records('question',
550 array('category' => $category->id
), '', 'id,qtype')) {
551 foreach ($questions as $question) {
552 question_delete_question($question->id
);
554 $DB->delete_records("question", array("category"=>$category->id
));
556 //delete the category
557 $DB->delete_records('question_categories', array('id'=>$category->id
));
560 $feedbackdata[] = array($category->name
, $strcatdeleted);
562 //Inform about changes performed if feedback is enabled
564 $table = new html_table();
565 $table->head
= array(get_string('category', 'quiz'), get_string('action'));
566 $table->data
= $feedbackdata;
567 echo html_writer
::table($table);
574 * This function should be considered private to the question bank, it is called from
575 * question/editlib.php question/contextmoveq.php and a few similar places to to the
576 * work of acutally moving questions and associated data. However, callers of this
577 * function also have to do other work, which is why you should not call this method
578 * directly from outside the questionbank.
580 * @param array $questionids of question ids.
581 * @param integer $newcategoryid the id of the category to move to.
583 function question_move_questions_to_category($questionids, $newcategoryid) {
586 $newcontextid = $DB->get_field('question_categories', 'contextid',
587 array('id' => $newcategoryid));
588 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
589 $questions = $DB->get_records_sql("
590 SELECT q.id, q.qtype, qc.contextid
592 JOIN {question_categories} qc ON q.category = qc.id
593 WHERE q.id $questionidcondition", $params);
594 foreach ($questions as $question) {
595 if ($newcontextid != $question->contextid
) {
596 question_bank
::get_qtype($question->qtype
)->move_files(
597 $question->id
, $question->contextid
, $newcontextid);
601 // Move the questions themselves.
602 $DB->set_field_select('question', 'category', $newcategoryid,
603 "id $questionidcondition", $params);
605 // Move any subquestions belonging to them.
606 $DB->set_field_select('question', 'category', $newcategoryid,
607 "parent $questionidcondition", $params);
609 // TODO Deal with datasets.
611 // Purge these questions from the cache.
612 foreach ($questions as $question) {
613 question_bank
::notify_question_edited($question->id
);
620 * This function helps move a question cateogry to a new context by moving all
621 * the files belonging to all the questions to the new context.
622 * Also moves subcategories.
623 * @param integer $categoryid the id of the category being moved.
624 * @param integer $oldcontextid the old context id.
625 * @param integer $newcontextid the new context id.
627 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
630 $questionids = $DB->get_records_menu('question',
631 array('category' => $categoryid), '', 'id,qtype');
632 foreach ($questionids as $questionid => $qtype) {
633 question_bank
::get_qtype($qtype)->move_files(
634 $questionid, $oldcontextid, $newcontextid);
635 // Purge this question from the cache.
636 question_bank
::notify_question_edited($questionid);
639 $subcatids = $DB->get_records_menu('question_categories',
640 array('parent' => $categoryid), '', 'id,1');
641 foreach ($subcatids as $subcatid => $notused) {
642 $DB->set_field('question_categories', 'contextid', $newcontextid,
643 array('id' => $subcatid));
644 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
649 * Generate the URL for starting a new preview of a given question with the given options.
650 * @param integer $questionid the question to preview.
651 * @param string $preferredbehaviour the behaviour to use for the preview.
652 * @param float $maxmark the maximum to mark the question out of.
653 * @param question_display_options $displayoptions the display options to use.
654 * @param int $variant the variant of the question to preview. If null, one will
655 * be picked randomly.
656 * @param object $context context to run the preview in (affects things like
657 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
658 * @return string the URL.
660 function question_preview_url($questionid, $preferredbehaviour = null,
661 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
663 $params = array('id' => $questionid);
665 if (is_null($context)) {
667 $context = $PAGE->context
;
669 if ($context->contextlevel
== CONTEXT_MODULE
) {
670 $params['cmid'] = $context->instanceid
;
671 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
672 $params['courseid'] = $context->instanceid
;
675 if (!is_null($preferredbehaviour)) {
676 $params['behaviour'] = $preferredbehaviour;
679 if (!is_null($maxmark)) {
680 $params['maxmark'] = $maxmark;
683 if (!is_null($displayoptions)) {
684 $params['correctness'] = $displayoptions->correctness
;
685 $params['marks'] = $displayoptions->marks
;
686 $params['markdp'] = $displayoptions->markdp
;
687 $params['feedback'] = (bool) $displayoptions->feedback
;
688 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
689 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
690 $params['history'] = (bool) $displayoptions->history
;
694 $params['variant'] = $variant;
697 return new moodle_url('/question/preview.php', $params);
701 * @return array that can be passed as $params to the {@link popup_action} constructor.
703 function question_preview_popup_params() {
711 * Given a list of ids, load the basic information about a set of questions from
712 * the questions table. The $join and $extrafields arguments can be used together
713 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
714 * read the code below to see how the SQL is assembled. Throws exceptions on error.
718 * @param array $questionids array of question ids.
719 * @param string $extrafields extra SQL code to be added to the query.
720 * @param string $join extra SQL code to be added to the query.
721 * @param array $extraparams values for any placeholders in $join.
722 * You are strongly recommended to use named placeholder.
724 * @return array partially complete question objects. You need to call get_question_options
725 * on them before they can be properly used.
727 function question_preload_questions($questionids, $extrafields = '', $join = '',
728 $extraparams = array()) {
730 if (empty($questionids)) {
734 $join = ' JOIN '.$join;
737 $extrafields = ', ' . $extrafields;
739 list($questionidcondition, $params) = $DB->get_in_or_equal(
740 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
741 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
742 JOIN {question_categories} qc ON q.category = qc.id' .
744 ' WHERE q.id ' . $questionidcondition;
746 // Load the questions
747 if (!$questions = $DB->get_records_sql($sql, $extraparams +
$params)) {
751 foreach ($questions as $question) {
752 $question->_partiallyloaded
= true;
755 // Note, a possible optimisation here would be to not load the TEXT fields
756 // (that is, questiontext and generalfeedback) here, and instead load them in
757 // question_load_questions. That would add one DB query, but reduce the amount
758 // of data transferred most of the time. I am not going to do this optimisation
759 // until it is shown to be worthwhile.
765 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
766 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
767 * read the code below to see how the SQL is assembled. Throws exceptions on error.
769 * @param array $questionids array of question ids.
770 * @param string $extrafields extra SQL code to be added to the query.
771 * @param string $join extra SQL code to be added to the query.
772 * @param array $extraparams values for any placeholders in $join.
773 * You are strongly recommended to use named placeholder.
775 * @return array question objects.
777 function question_load_questions($questionids, $extrafields = '', $join = '') {
778 $questions = question_preload_questions($questionids, $extrafields, $join);
780 // Load the question type specific information
781 if (!get_question_options($questions)) {
782 return 'Could not load the question options';
789 * Private function to factor common code out of get_question_options().
791 * @param object $question the question to tidy.
792 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
794 function _tidy_question($question, $loadtags = false) {
797 // Load question-type specific fields.
798 if (!question_bank
::is_qtype_installed($question->qtype
)) {
799 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
800 'qtype_missingtype')) . $question->questiontext
;
802 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
804 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
805 $question->defaultmark +
= 0;
806 $question->penalty +
= 0;
808 if (isset($question->_partiallyloaded
)) {
809 unset($question->_partiallyloaded
);
812 if ($loadtags && !empty($CFG->usetags
)) {
813 require_once($CFG->dirroot
. '/tag/lib.php');
814 $question->tags
= tag_get_tags_array('question', $question->id
);
819 * Updates the question objects with question type specific
820 * information by calling {@link get_question_options()}
822 * Can be called either with an array of question objects or with a single
825 * @param mixed $questions Either an array of question objects to be updated
826 * or just a single question object
827 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
828 * @return bool Indicates success or failure.
830 function get_question_options(&$questions, $loadtags = false) {
831 if (is_array($questions)) { // deal with an array of questions
832 foreach ($questions as $i => $notused) {
833 _tidy_question($questions[$i], $loadtags);
835 } else { // deal with single question
836 _tidy_question($questions, $loadtags);
842 * Print the icon for the question type
844 * @param object $question The question object for which the icon is required.
845 * Only $question->qtype is used.
846 * @return string the HTML for the img tag.
848 function print_question_icon($question) {
850 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
854 * Creates a stamp that uniquely identifies this version of the question
856 * In future we want this to use a hash of the question data to guarantee that
857 * identical versions have the same version stamp.
859 * @param object $question
860 * @return string A unique version stamp
862 function question_hash($question) {
863 return make_unique_id_code();
866 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
868 * Saves question options
870 * Simply calls the question type specific save_question_options() method.
871 * @deprecated all code should now call the question type method directly.
873 function save_question_options($question) {
874 debugging('Please do not call save_question_options any more. Call the question type method directly.',
876 question_bank
::get_qtype($question->qtype
)->save_question_options($question);
879 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
882 * returns the categories with their names ordered following parent-child relationships
883 * finally it tries to return pending categories (those being orphaned, whose parent is
884 * incorrect) to avoid missing any category from original array.
886 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
890 $keys = array_keys($categories);
892 foreach ($keys as $key) {
893 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
894 $children[$key] = $categories[$key];
895 $categories[$key]->processed
= true;
896 $children = $children +
sort_categories_by_tree(
897 $categories, $children[$key]->id
, $level+
1);
900 //If level = 1, we have finished, try to look for non processed categories
901 // (bad parent) and sort them too
903 foreach ($keys as $key) {
904 // If not processed and it's a good candidate to start (because its
905 // parent doesn't exist in the course)
906 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
907 array('contextid' => $categories[$key]->contextid
,
908 'id' => $categories[$key]->parent
))) {
909 $children[$key] = $categories[$key];
910 $categories[$key]->processed
= true;
911 $children = $children +
sort_categories_by_tree(
912 $categories, $children[$key]->id
, $level +
1);
920 * Private method, only for the use of add_indented_names().
922 * Recursively adds an indentedname field to each category, starting with the category
923 * with id $id, and dealing with that category and all its children, and
924 * return a new array, with those categories in the right order.
926 * @param array $categories an array of categories which has had childids
927 * fields added by flatten_category_tree(). Passed by reference for
928 * performance only. It is not modfied.
929 * @param int $id the category to start the indenting process from.
930 * @param int $depth the indent depth. Used in recursive calls.
931 * @return array a new array of categories, in the right order for the tree.
933 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
935 // Indent the name of this category.
936 $newcategories = array();
937 $newcategories[$id] = $categories[$id];
938 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
939 $categories[$id]->name
;
941 // Recursively indent the children.
942 foreach ($categories[$id]->childids
as $childid) {
943 if ($childid != $nochildrenof) {
944 $newcategories = $newcategories +
flatten_category_tree(
945 $categories, $childid, $depth +
1, $nochildrenof);
949 // Remove the childids array that were temporarily added.
950 unset($newcategories[$id]->childids
);
952 return $newcategories;
956 * Format categories into an indented list reflecting the tree structure.
958 * @param array $categories An array of category objects, for example from the.
959 * @return array The formatted list of categories.
961 function add_indented_names($categories, $nochildrenof = -1) {
963 // Add an array to each category to hold the child category ids. This array
964 // will be removed again by flatten_category_tree(). It should not be used
965 // outside these two functions.
966 foreach (array_keys($categories) as $id) {
967 $categories[$id]->childids
= array();
970 // Build the tree structure, and record which categories are top-level.
971 // We have to be careful, because the categories array may include published
972 // categories from other courses, but not their parents.
973 $toplevelcategoryids = array();
974 foreach (array_keys($categories) as $id) {
975 if (!empty($categories[$id]->parent
) &&
976 array_key_exists($categories[$id]->parent
, $categories)) {
977 $categories[$categories[$id]->parent
]->childids
[] = $id;
979 $toplevelcategoryids[] = $id;
983 // Flatten the tree to and add the indents.
984 $newcategories = array();
985 foreach ($toplevelcategoryids as $id) {
986 $newcategories = $newcategories +
flatten_category_tree(
987 $categories, $id, 0, $nochildrenof);
990 return $newcategories;
994 * Output a select menu of question categories.
996 * Categories from this course and (optionally) published categories from other courses
997 * are included. Optionally, only categories the current user may edit can be included.
999 * @param integer $courseid the id of the course to get the categories for.
1000 * @param integer $published if true, include publised categories from other courses.
1001 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1002 * @param integer $selected optionally, the id of a category to be selected by
1003 * default in the dropdown.
1005 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1006 $selected = "", $nochildrenof = -1) {
1008 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1009 false, $nochildrenof);
1013 $choose = 'choosedots';
1016 foreach ($categoriesarray as $group => $opts) {
1017 $options[] = array($group => $opts);
1019 echo html_writer
::label($selected, 'menucategory', false, array('class' => 'accesshide'));
1020 echo html_writer
::select($options, 'category', $selected, $choose);
1024 * @param integer $contextid a context id.
1025 * @return object the default question category for that context, or false if none.
1027 function question_get_default_category($contextid) {
1029 $category = $DB->get_records('question_categories',
1030 array('contextid' => $contextid), 'id', '*', 0, 1);
1031 if (!empty($category)) {
1032 return reset($category);
1039 * Gets the default category in the most specific context.
1040 * If no categories exist yet then default ones are created in all contexts.
1042 * @param array $contexts The context objects for this context and all parent contexts.
1043 * @return object The default category - the category in the course context
1045 function question_make_default_categories($contexts) {
1047 static $preferredlevels = array(
1048 CONTEXT_COURSE
=> 4,
1049 CONTEXT_MODULE
=> 3,
1050 CONTEXT_COURSECAT
=> 2,
1051 CONTEXT_SYSTEM
=> 1,
1056 // If it already exists, just return it.
1057 foreach ($contexts as $key => $context) {
1058 if (!$exists = $DB->record_exists("question_categories",
1059 array('contextid' => $context->id
))) {
1060 // Otherwise, we need to make one
1061 $category = new stdClass();
1062 $contextname = print_context_name($context, false, true);
1063 $category->name
= get_string('defaultfor', 'question', $contextname);
1064 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1065 $category->contextid
= $context->id
;
1066 $category->parent
= 0;
1067 // By default, all categories get this number, and are sorted alphabetically.
1068 $category->sortorder
= 999;
1069 $category->stamp
= make_unique_id_code();
1070 $category->id
= $DB->insert_record('question_categories', $category);
1072 $category = question_get_default_category($context->id
);
1074 $thispreferredness = $preferredlevels[$context->contextlevel
];
1075 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1076 $thispreferredness +
= 10;
1078 if ($thispreferredness > $preferredness) {
1079 $toreturn = $category;
1080 $preferredness = $thispreferredness;
1084 if (!is_null($toreturn)) {
1085 $toreturn = clone($toreturn);
1091 * Get all the category objects, including a count of the number of questions in that category,
1092 * for all the categories in the lists $contexts.
1094 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1095 * @param string $sortorder used as the ORDER BY clause in the select statement.
1096 * @return array of category objects.
1098 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1100 return $DB->get_records_sql("
1101 SELECT c.*, (SELECT count(1) FROM {question} q
1102 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1103 FROM {question_categories} c
1104 WHERE c.contextid IN ($contexts)
1105 ORDER BY $sortorder");
1109 * Output an array of question categories.
1111 function question_category_options($contexts, $top = false, $currentcat = 0,
1112 $popupform = false, $nochildrenof = -1) {
1114 $pcontexts = array();
1115 foreach ($contexts as $context) {
1116 $pcontexts[] = $context->id
;
1118 $contextslist = join($pcontexts, ', ');
1120 $categories = get_categories_for_contexts($contextslist);
1122 $categories = question_add_context_in_key($categories);
1125 $categories = question_add_tops($categories, $pcontexts);
1127 $categories = add_indented_names($categories, $nochildrenof);
1129 // sort cats out into different contexts
1130 $categoriesarray = array();
1131 foreach ($pcontexts as $contextid) {
1132 $context = context
::instance_by_id($contextid);
1133 $contextstring = $context->get_context_name(true, true);
1134 foreach ($categories as $category) {
1135 if ($category->contextid
== $contextid) {
1136 $cid = $category->id
;
1137 if ($currentcat != $cid ||
$currentcat == 0) {
1138 $countstring = !empty($category->questioncount
) ?
1139 " ($category->questioncount)" : '';
1140 $categoriesarray[$contextstring][$cid] =
1141 format_string($category->indentedname
, true,
1142 array('context' => $context)) . $countstring;
1148 $popupcats = array();
1149 foreach ($categoriesarray as $contextstring => $optgroup) {
1151 foreach ($optgroup as $key => $value) {
1152 $key = str_replace($CFG->wwwroot
, '', $key);
1153 $group[$key] = $value;
1155 $popupcats[] = array($contextstring => $group);
1159 return $categoriesarray;
1163 function question_add_context_in_key($categories) {
1164 $newcatarray = array();
1165 foreach ($categories as $id => $category) {
1166 $category->parent
= "$category->parent,$category->contextid";
1167 $category->id
= "$category->id,$category->contextid";
1168 $newcatarray["$id,$category->contextid"] = $category;
1170 return $newcatarray;
1173 function question_add_tops($categories, $pcontexts) {
1175 foreach ($pcontexts as $context) {
1176 $newcat = new stdClass();
1177 $newcat->id
= "0,$context";
1178 $newcat->name
= get_string('top');
1179 $newcat->parent
= -1;
1180 $newcat->contextid
= $context;
1181 $topcats["0,$context"] = $newcat;
1183 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1184 return array_merge($topcats, $categories);
1188 * @return array of question category ids of the category and all subcategories.
1190 function question_categorylist($categoryid) {
1193 // final list of category IDs
1194 $categorylist = array();
1196 // a list of category IDs to check for any sub-categories
1197 $subcategories = array($categoryid);
1199 while ($subcategories) {
1200 foreach ($subcategories as $subcategory) {
1201 // if anything from the temporary list was added already, then we have a loop
1202 if (isset($categorylist[$subcategory])) {
1203 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1205 $categorylist[$subcategory] = $subcategory;
1208 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1210 $subcategories = $DB->get_records_select_menu('question_categories',
1211 "parent $in", $params, NULL, 'id,id AS id2');
1214 return $categorylist;
1217 //===========================
1218 // Import/Export Functions
1219 //===========================
1222 * Get list of available import or export formats
1223 * @param string $type 'import' if import list, otherwise export list assumed
1224 * @return array sorted list of import/export formats available
1226 function get_import_export_formats($type) {
1228 require_once($CFG->dirroot
. '/question/format.php');
1230 $formatclasses = get_plugin_list_with_class('qformat', '', 'format.php');
1232 $fileformatname = array();
1233 foreach ($formatclasses as $component => $formatclass) {
1235 $format = new $formatclass();
1236 if ($type == 'import') {
1237 $provided = $format->provide_import();
1239 $provided = $format->provide_export();
1243 list($notused, $fileformat) = explode('_', $component, 2);
1244 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1248 collatorlib
::asort($fileformatnames);
1249 return $fileformatnames;
1254 * Create a reasonable default file name for exporting questions from a particular
1256 * @param object $course the course the questions are in.
1257 * @param object $category the question category.
1258 * @return string the filename.
1260 function question_default_export_filename($course, $category) {
1261 // We build a string that is an appropriate name (questions) from the lang pack,
1262 // then the corse shortname, then the question category name, then a timestamp.
1264 $base = clean_filename(get_string('exportfilename', 'question'));
1266 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1267 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1269 $shortname = clean_filename($course->shortname
);
1270 if ($shortname == '' ||
$shortname == '_' ) {
1271 $shortname = $course->id
;
1274 $categoryname = clean_filename(format_string($category->name
));
1276 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1278 return $export_name;
1282 * Converts contextlevels to strings and back to help with reading/writing contexts
1283 * to/from import/export files.
1285 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1288 class context_to_string_translator
{
1290 * @var array used to translate between contextids and strings for this context.
1292 protected $contexttostringarray = array();
1294 public function __construct($contexts) {
1295 $this->generate_context_to_string_array($contexts);
1298 public function context_to_string($contextid) {
1299 return $this->contexttostringarray
[$contextid];
1302 public function string_to_context($contextname) {
1303 $contextid = array_search($contextname, $this->contexttostringarray
);
1307 protected function generate_context_to_string_array($contexts) {
1308 if (!$this->contexttostringarray
) {
1310 foreach ($contexts as $context) {
1311 switch ($context->contextlevel
) {
1312 case CONTEXT_MODULE
:
1313 $contextstring = 'module';
1315 case CONTEXT_COURSE
:
1316 $contextstring = 'course';
1318 case CONTEXT_COURSECAT
:
1319 $contextstring = "cat$catno";
1322 case CONTEXT_SYSTEM
:
1323 $contextstring = 'system';
1326 $this->contexttostringarray
[$context->id
] = $contextstring;
1334 * Check capability on category
1336 * @param mixed $question object or id
1337 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1338 * @param integer $cachecat useful to cache all question records in a category
1339 * @return boolean this user has the capability $cap for this question $question?
1341 function question_has_capability_on($question, $cap, $cachecat = -1) {
1344 // these are capabilities on existing questions capabilties are
1345 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1346 $question_questioncaps = array('edit', 'view', 'use', 'move');
1347 static $questions = array();
1348 static $categories = array();
1349 static $cachedcat = array();
1350 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1351 $questions +
= $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1352 $cachedcat[] = $cachecat;
1354 if (!is_object($question)) {
1355 if (!isset($questions[$question])) {
1356 if (!$questions[$question] = $DB->get_record('question',
1357 array('id' => $question), 'id,category,createdby')) {
1358 print_error('questiondoesnotexist', 'question');
1361 $question = $questions[$question];
1363 if (empty($question->category
)) {
1364 // This can happen when we have created a fake 'missingtype' question to
1365 // take the place of a deleted question.
1368 if (!isset($categories[$question->category
])) {
1369 if (!$categories[$question->category
] = $DB->get_record('question_categories',
1370 array('id'=>$question->category
))) {
1371 print_error('invalidcategory', 'quiz');
1374 $category = $categories[$question->category
];
1375 $context = context
::instance_by_id($category->contextid
);
1377 if (array_search($cap, $question_questioncaps)!== false) {
1378 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1379 if ($question->createdby
== $USER->id
) {
1380 return has_capability('moodle/question:' . $cap . 'mine', $context);
1388 return has_capability('moodle/question:' . $cap, $context);
1394 * Require capability on question.
1396 function question_require_capability_on($question, $cap) {
1397 if (!question_has_capability_on($question, $cap)) {
1398 print_error('nopermissions', '', '', $cap);
1404 * Get the real state - the correct question id and answer - for a random
1406 * @param object $state with property answer.
1407 * @deprecated this function has not been relevant since Moodle 2.1!
1409 function question_get_real_state($state) {
1410 throw new coding_exception('question_get_real_state has not been relevant since Moodle 2.1. ' .
1411 'I am not sure what you are trying to do, but stop it at once!');
1415 * @param object $context a context
1416 * @return string A URL for editing questions in this context.
1418 function question_edit_url($context) {
1420 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1423 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1424 $defaultcategory = question_get_default_category($context->id
);
1425 if ($defaultcategory) {
1426 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1428 switch ($context->contextlevel
) {
1429 case CONTEXT_SYSTEM
:
1430 return $baseurl . 'courseid=' . $SITE->id
;
1431 case CONTEXT_COURSECAT
:
1432 // This is nasty, becuase we can only edit questions in a course
1433 // context at the moment, so for now we just return false.
1435 case CONTEXT_COURSE
:
1436 return $baseurl . 'courseid=' . $context->instanceid
;
1437 case CONTEXT_MODULE
:
1438 return $baseurl . 'cmid=' . $context->instanceid
;
1444 * Adds question bank setting links to the given navigation node if caps are met.
1446 * @param navigation_node $navigationnode The navigation node to add the question branch to
1447 * @param object $context
1448 * @return navigation_node Returns the question branch that was added
1450 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1453 if ($context->contextlevel
== CONTEXT_COURSE
) {
1454 $params = array('courseid'=>$context->instanceid
);
1455 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1456 $params = array('cmid'=>$context->instanceid
);
1461 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1462 $params['cat'] = $cat;
1465 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1466 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
);
1468 $contexts = new question_edit_contexts($context);
1469 if ($contexts->have_one_edit_tab_cap('questions')) {
1470 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1471 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
);
1473 if ($contexts->have_one_edit_tab_cap('categories')) {
1474 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1475 '/question/category.php', $params), navigation_node
::TYPE_SETTING
);
1477 if ($contexts->have_one_edit_tab_cap('import')) {
1478 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1479 '/question/import.php', $params), navigation_node
::TYPE_SETTING
);
1481 if ($contexts->have_one_edit_tab_cap('export')) {
1482 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1483 '/question/export.php', $params), navigation_node
::TYPE_SETTING
);
1486 return $questionnode;
1490 * @return array all the capabilities that relate to accessing particular questions.
1492 function question_get_question_capabilities() {
1494 'moodle/question:add',
1495 'moodle/question:editmine',
1496 'moodle/question:editall',
1497 'moodle/question:viewmine',
1498 'moodle/question:viewall',
1499 'moodle/question:usemine',
1500 'moodle/question:useall',
1501 'moodle/question:movemine',
1502 'moodle/question:moveall',
1507 * @return array all the question bank capabilities.
1509 function question_get_all_capabilities() {
1510 $caps = question_get_question_capabilities();
1511 $caps[] = 'moodle/question:managecategory';
1512 $caps[] = 'moodle/question:flag';
1518 * Tracks all the contexts related to the one where we are currently editing
1519 * questions, and provides helper methods to check permissions.
1521 * @copyright 2007 Jamie Pratt me@jamiep.org
1522 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1524 class question_edit_contexts
{
1526 public static $caps = array(
1527 'editq' => array('moodle/question:add',
1528 'moodle/question:editmine',
1529 'moodle/question:editall',
1530 'moodle/question:viewmine',
1531 'moodle/question:viewall',
1532 'moodle/question:usemine',
1533 'moodle/question:useall',
1534 'moodle/question:movemine',
1535 'moodle/question:moveall'),
1536 'questions'=>array('moodle/question:add',
1537 'moodle/question:editmine',
1538 'moodle/question:editall',
1539 'moodle/question:viewmine',
1540 'moodle/question:viewall',
1541 'moodle/question:movemine',
1542 'moodle/question:moveall'),
1543 'categories'=>array('moodle/question:managecategory'),
1544 'import'=>array('moodle/question:add'),
1545 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1547 protected $allcontexts;
1551 * @param context the current context.
1553 public function __construct(context
$thiscontext) {
1554 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1558 * @return array all parent contexts
1560 public function all() {
1561 return $this->allcontexts
;
1565 * @return object lowest context which must be either the module or course context
1567 public function lowest() {
1568 return $this->allcontexts
[0];
1572 * @param string $cap capability
1573 * @return array parent contexts having capability, zero based index
1575 public function having_cap($cap) {
1576 $contextswithcap = array();
1577 foreach ($this->allcontexts
as $context) {
1578 if (has_capability($cap, $context)) {
1579 $contextswithcap[] = $context;
1582 return $contextswithcap;
1586 * @param array $caps capabilities
1587 * @return array parent contexts having at least one of $caps, zero based index
1589 public function having_one_cap($caps) {
1590 $contextswithacap = array();
1591 foreach ($this->allcontexts
as $context) {
1592 foreach ($caps as $cap) {
1593 if (has_capability($cap, $context)) {
1594 $contextswithacap[] = $context;
1595 break; //done with caps loop
1599 return $contextswithacap;
1603 * @param string $tabname edit tab name
1604 * @return array parent contexts having at least one of $caps, zero based index
1606 public function having_one_edit_tab_cap($tabname) {
1607 return $this->having_one_cap(self
::$caps[$tabname]);
1611 * @return those contexts where a user can add a question and then use it.
1613 public function having_add_and_use() {
1614 $contextswithcap = array();
1615 foreach ($this->allcontexts
as $context) {
1616 if (!has_capability('moodle/question:add', $context)) {
1619 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1622 $contextswithcap[] = $context;
1624 return $contextswithcap;
1628 * Has at least one parent context got the cap $cap?
1630 * @param string $cap capability
1633 public function have_cap($cap) {
1634 return (count($this->having_cap($cap)));
1638 * Has at least one parent context got one of the caps $caps?
1640 * @param array $caps capability
1643 public function have_one_cap($caps) {
1644 foreach ($caps as $cap) {
1645 if ($this->have_cap($cap)) {
1653 * Has at least one parent context got one of the caps for actions on $tabname
1655 * @param string $tabname edit tab name
1658 public function have_one_edit_tab_cap($tabname) {
1659 return $this->have_one_cap(self
::$caps[$tabname]);
1663 * Throw error if at least one parent context hasn't got the cap $cap
1665 * @param string $cap capability
1667 public function require_cap($cap) {
1668 if (!$this->have_cap($cap)) {
1669 print_error('nopermissions', '', '', $cap);
1674 * Throw error if at least one parent context hasn't got one of the caps $caps
1676 * @param array $cap capabilities
1678 public function require_one_cap($caps) {
1679 if (!$this->have_one_cap($caps)) {
1680 $capsstring = join($caps, ', ');
1681 print_error('nopermissions', '', '', $capsstring);
1686 * Throw error if at least one parent context hasn't got one of the caps $caps
1688 * @param string $tabname edit tab name
1690 public function require_one_edit_tab_cap($tabname) {
1691 if (!$this->have_one_edit_tab_cap($tabname)) {
1692 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1699 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1701 * @package core_question
1703 * @param string $text text being processed
1704 * @param string $file the php script used to serve files
1705 * @param int $contextid context ID
1706 * @param string $component component
1707 * @param string $filearea filearea
1708 * @param array $ids other IDs will be used to check file permission
1709 * @param int $itemid item ID
1710 * @param array $options options
1713 function question_rewrite_question_urls($text, $file, $contextid, $component,
1714 $filearea, array $ids, $itemid, array $options=null) {
1718 $idsstr .= implode('/', $ids);
1720 if ($itemid !== null) {
1721 $idsstr .= '/' . $itemid;
1723 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1724 $filearea, $idsstr, $options);
1728 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1729 * text outside and attempt (for example, in the question bank listing or in the
1730 * quiz statistics report).
1732 * @param string $questiontext the question text.
1733 * @param int $contextid the context the text is being displayed in.
1734 * @param string $component component
1735 * @param array $ids other IDs will be used to check file permission
1736 * @param array $options
1737 * @return string $questiontext with URLs rewritten.
1739 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1740 $component, $questionid, $options=null) {
1742 return file_rewrite_pluginfile_urls($questiontext, 'pluginfile.php', $contextid,
1743 'question', 'questiontext_preview', "$component/$questionid", $options);
1747 * Send a file from the question text of a question.
1748 * @param int $questionid the question id
1749 * @param array $args the remaining file arguments (file path).
1750 * @param bool $forcedownload whether the user must be forced to download the file.
1751 * @param array $options additional options affecting the file serving
1753 function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
1756 $question = $DB->get_record_sql('
1757 SELECT q.id, qc.contextid
1759 JOIN {question_categories} qc ON qc.id = q.category
1760 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST
);
1762 $fs = get_file_storage();
1763 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1764 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1765 send_file_not_found();
1768 send_stored_file($file, 0, 0, $forcedownload, $options);
1772 * Called by pluginfile.php to serve files related to the 'question' core
1773 * component and for files belonging to qtypes.
1775 * For files that relate to questions in a question_attempt, then we delegate to
1776 * a function in the component that owns the attempt (for example in the quiz,
1777 * or in core question preview) to get necessary inforation.
1779 * (Note that, at the moment, all question file areas relate to questions in
1780 * attempts, so the If at the start of the last paragraph is always true.)
1782 * Does not return, either calls send_file_not_found(); or serves the file.
1784 * @package core_question
1786 * @param stdClass $course course settings object
1787 * @param stdClass $context context object
1788 * @param string $component the name of the component we are serving files for.
1789 * @param string $filearea the name of the file area.
1790 * @param array $args the remaining bits of the file path.
1791 * @param bool $forcedownload whether the user must be forced to download the file.
1792 * @param array $options additional options affecting the file serving
1794 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1797 if ($filearea === 'questiontext_preview') {
1798 $component = array_shift($args);
1799 $questionid = array_shift($args);
1801 component_callback($component, 'questiontext_preview_pluginfile', array(
1802 $context, $questionid, $args, $forcedownload, $options));
1804 send_file_not_found();
1807 list($context, $course, $cm) = get_context_info_array($context->id
);
1808 require_login($course, false, $cm);
1810 if ($filearea === 'export') {
1811 require_once($CFG->dirroot
. '/question/editlib.php');
1812 $contexts = new question_edit_contexts($context);
1813 // check export capability
1814 $contexts->require_one_edit_tab_cap('export');
1815 $category_id = (int)array_shift($args);
1816 $format = array_shift($args);
1817 $cattofile = array_shift($args);
1818 $contexttofile = array_shift($args);
1819 $filename = array_shift($args);
1821 // load parent class for import/export
1822 require_once($CFG->dirroot
. '/question/format.php');
1823 require_once($CFG->dirroot
. '/question/editlib.php');
1824 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
1826 $classname = 'qformat_' . $format;
1827 if (!class_exists($classname)) {
1828 send_file_not_found();
1831 $qformat = new $classname();
1833 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1834 send_file_not_found();
1837 $qformat->setCategory($category);
1838 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1839 $qformat->setCourse($course);
1841 if ($cattofile == 'withcategories') {
1842 $qformat->setCattofile(true);
1844 $qformat->setCattofile(false);
1847 if ($contexttofile == 'withcontexts') {
1848 $qformat->setContexttofile(true);
1850 $qformat->setContexttofile(false);
1853 if (!$qformat->exportpreprocess()) {
1854 send_file_not_found();
1855 print_error('exporterror', 'question', $thispageurl->out());
1858 // export data to moodle file pool
1859 if (!$content = $qformat->exportprocess(true)) {
1860 send_file_not_found();
1863 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1866 $qubaid = (int)array_shift($args);
1867 $slot = (int)array_shift($args);
1869 $module = $DB->get_field('question_usages', 'component',
1870 array('id' => $qubaid));
1872 if ($module === 'core_question_preview') {
1873 require_once($CFG->dirroot
. '/question/previewlib.php');
1874 return question_preview_question_pluginfile($course, $context,
1875 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1878 $dir = get_component_directory($module);
1879 if (!file_exists("$dir/lib.php")) {
1880 send_file_not_found();
1882 include_once("$dir/lib.php");
1884 $filefunction = $module . '_question_pluginfile';
1885 if (function_exists($filefunction)) {
1886 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1887 $args, $forcedownload, $options);
1890 // Okay, we're here so lets check for function without 'mod_'.
1891 if (strpos($module, 'mod_') === 0) {
1892 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1893 if (function_exists($filefunctionold)) {
1894 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1895 $args, $forcedownload, $options);
1899 send_file_not_found();
1904 * Serve questiontext files in the question text when they are displayed in this report.
1906 * @package core_files
1908 * @param stdClass $context the context
1909 * @param int $questionid the question id
1910 * @param array $args remaining file args
1911 * @param bool $forcedownload
1912 * @param array $options additional options affecting the file serving
1914 function core_question_questiontext_preview_pluginfile($context, $questionid, $args, $forcedownload, array $options=array()) {
1917 // Verify that contextid matches the question.
1918 $question = $DB->get_record_sql('
1919 SELECT q.*, qc.contextid
1921 JOIN {question_categories} qc ON qc.id = q.category
1922 WHERE q.id = :id AND qc.contextid = :contextid',
1923 array('id' => $questionid, 'contextid' => $context->id
), MUST_EXIST
);
1925 // Check the capability.
1926 list($context, $course, $cm) = get_context_info_array($context->id
);
1927 require_login($course, false, $cm);
1929 question_require_capability_on($question, 'use');
1931 question_send_questiontext_file($questionid, $args, $forcedownload, $options);
1935 * Create url for question export
1937 * @param int $contextid, current context
1938 * @param int $categoryid, categoryid
1939 * @param string $format
1940 * @param string $withcategories
1941 * @param string $ithcontexts
1942 * @param moodle_url export file url
1944 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1945 $withcontexts, $filename) {
1947 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1948 return moodle_url
::make_file_url($urlbase,
1949 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1950 "/{$withcontexts}/{$filename}", true);
1954 * Return a list of page types
1955 * @param string $pagetype current page type
1956 * @param stdClass $parentcontext Block's parent context
1957 * @param stdClass $currentcontext Current context of block
1959 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1962 'question-*'=>get_string('page-question-x', 'question'),
1963 'question-edit'=>get_string('page-question-edit', 'question'),
1964 'question-category'=>get_string('page-question-category', 'question'),
1965 'question-export'=>get_string('page-question-export', 'question'),
1966 'question-import'=>get_string('page-question-import', 'question')
1968 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
1969 require_once($CFG->dirroot
. '/course/lib.php');
1970 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);