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 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
121 function questions_in_use($questionids) {
124 if (question_engine
::questions_in_use($questionids)) {
128 foreach (core_component
::get_plugin_list('mod') as $module => $path) {
129 $lib = $path . '/lib.php';
130 if (is_readable($lib)) {
133 $fn = $module . '_questions_in_use';
134 if (function_exists($fn)) {
135 if ($fn($questionids)) {
140 // Fallback for legacy modules.
141 $fn = $module . '_question_list_instances';
142 if (function_exists($fn)) {
143 foreach ($questionids as $questionid) {
144 $instances = $fn($questionid);
145 if (!empty($instances)) {
158 * Determine whether there arey any questions belonging to this context, that is whether any of its
159 * question categories contain any questions. This will return true even if all the questions are
162 * @param mixed $context either a context object, or a context id.
163 * @return boolean whether any of the question categories beloning to this context have
164 * any questions in them.
166 function question_context_has_any_questions($context) {
168 if (is_object($context)) {
169 $contextid = $context->id
;
170 } else if (is_numeric($context)) {
171 $contextid = $context;
173 print_error('invalidcontextinhasanyquestions', 'question');
175 return $DB->record_exists_sql("SELECT *
177 JOIN {question_categories} qc ON qc.id = q.category
178 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
182 * Check whether a given grade is one of a list of allowed options. If not,
183 * depending on $matchgrades, either return the nearest match, or return false
184 * to signal an error.
185 * @param array $gradeoptionsfull list of valid options
186 * @param int $grade grade to be tested
187 * @param string $matchgrades 'error' or 'nearest'
188 * @return mixed either 'fixed' value or false if error.
190 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
192 if ($matchgrades == 'error') {
193 // (Almost) exact match, or an error.
194 foreach ($gradeoptionsfull as $value => $option) {
195 // Slightly fuzzy test, never check floats for equality.
196 if (abs($grade - $value) < 0.00001) {
197 return $value; // Be sure the return the proper value.
200 // Didn't find a match so that's an error.
203 } else if ($matchgrades == 'nearest') {
204 // Work out nearest value
207 foreach ($gradeoptionsfull as $value => $option) {
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
211 $bestmismatch = $newmismatch;
217 // Unknow option passed.
218 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
219 ' passed to match_grade_options');
224 * Category is about to be deleted,
225 * 1/ All questions are deleted for this question category.
226 * 2/ Any questions that can't be deleted are moved to a new category
227 * NOTE: this function is called from lib/db/upgrade.php
229 * @param object|coursecat $category course category object
231 function question_category_delete_safe($category) {
233 $criteria = array('category' => $category->id
);
234 $context = context
::instance_by_id($category->contextid
, IGNORE_MISSING
);
235 $rescue = null; // See the code around the call to question_save_from_deletion.
237 // Deal with any questions in the category.
238 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
240 // Try to delete each question.
241 foreach ($questions as $question) {
242 question_delete_question($question->id
);
245 // Check to see if there were any questions that were kept because
246 // they are still in use somehow, even though quizzes in courses
247 // in this category will already have been deleted. This could
248 // happen, for example, if questions are added to a course,
249 // and then that course is moved to another category (MDL-14802).
250 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
251 if (!empty($questionids)) {
252 $parentcontextid = SYSCONTEXTID
;
253 $name = get_string('unknown', 'question');
254 if ($context !== false) {
255 $name = $context->get_context_name();
256 $parentcontext = $context->get_parent_context();
257 if ($parentcontext) {
258 $parentcontextid = $parentcontext->id
;
261 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
265 // Now delete the category.
266 $DB->delete_records('question_categories', array('id' => $category->id
));
270 * Tests whether any question in a category is used by any part of Moodle.
272 * @param integer $categoryid a question category id.
273 * @param boolean $recursive whether to check child categories too.
274 * @return boolean whether any question in this category is in use.
276 function question_category_in_use($categoryid, $recursive = false) {
279 //Look at each question in the category
280 if ($questions = $DB->get_records_menu('question',
281 array('category' => $categoryid), '', 'id, 1')) {
282 if (questions_in_use(array_keys($questions))) {
290 //Look under child categories recursively
291 if ($children = $DB->get_records('question_categories',
292 array('parent' => $categoryid), '', 'id, 1')) {
293 foreach ($children as $child) {
294 if (question_category_in_use($child->id
, $recursive)) {
304 * Deletes question and all associated data from the database
306 * It will not delete a question if it is used by an activity module
307 * @param object $question The question being deleted
309 function question_delete_question($questionid) {
312 $question = $DB->get_record_sql('
313 SELECT q.*, qc.contextid
315 JOIN {question_categories} qc ON qc.id = q.category
316 WHERE q.id = ?', array($questionid));
318 // In some situations, for example if this was a child of a
319 // Cloze question that was previously deleted, the question may already
320 // have gone. In this case, just do nothing.
324 // Do not delete a question if it is used by an activity module
325 if (questions_in_use(array($questionid))) {
329 $dm = new question_engine_data_mapper();
330 $dm->delete_previews($questionid);
332 // delete questiontype-specific data
333 question_bank
::get_qtype($question->qtype
, false)->delete_question(
334 $questionid, $question->contextid
);
336 // Delete all tag instances.
337 core_tag_tag
::remove_all_item_tags('core_question', 'question', $question->id
);
339 // Now recursively delete all child questions
340 if ($children = $DB->get_records('question',
341 array('parent' => $questionid), '', 'id, qtype')) {
342 foreach ($children as $child) {
343 if ($child->id
!= $questionid) {
344 question_delete_question($child->id
);
349 // Finally delete the question record itself
350 $DB->delete_records('question', array('id' => $questionid));
351 question_bank
::notify_question_edited($questionid);
355 * All question categories and their questions are deleted for this context id.
357 * @param object $contextid The contextid to delete question categories from
358 * @return array Feedback from deletes (if any)
360 function question_delete_context($contextid) {
363 //To store feedback to be showed at the end of the process
364 $feedbackdata = array();
367 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
368 $fields = 'id, parent, name, contextid';
369 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
370 //Sort categories following their tree (parent-child) relationships
371 //this will make the feedback more readable
372 $categories = sort_categories_by_tree($categories);
374 foreach ($categories as $category) {
375 question_category_delete_safe($category);
378 $feedbackdata[] = array($category->name
, $strcatdeleted);
381 return $feedbackdata;
385 * All question categories and their questions are deleted for this course.
387 * @param stdClass $course an object representing the activity
388 * @param boolean $feedback to specify if the process must output a summary of its work
391 function question_delete_course($course, $feedback=true) {
392 $coursecontext = context_course
::instance($course->id
);
393 $feedbackdata = question_delete_context($coursecontext->id
, $feedback);
395 // Inform about changes performed if feedback is enabled.
396 if ($feedback && $feedbackdata) {
397 $table = new html_table();
398 $table->head
= array(get_string('category', 'question'), get_string('action'));
399 $table->data
= $feedbackdata;
400 echo html_writer
::table($table);
406 * Category is about to be deleted,
407 * 1/ All question categories and their questions are deleted for this course category.
408 * 2/ All questions are moved to new category
410 * @param object|coursecat $category course category object
411 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
412 * category where content moved
413 * @param boolean $feedback to specify if the process must output a summary of its work
416 function question_delete_course_category($category, $newcategory, $feedback=true) {
419 $context = context_coursecat
::instance($category->id
);
420 if (empty($newcategory)) {
421 $feedbackdata = question_delete_context($context->id
, $feedback);
423 // Output feedback if requested.
424 if ($feedback && $feedbackdata) {
425 $table = new html_table();
426 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
427 $table->data
= $feedbackdata;
428 echo html_writer
::table($table);
432 // Move question categories to the new context.
433 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
437 // Update the contextid for any tag instances for questions in the old context.
438 core_tag_tag
::move_context('core_question', 'question', $context, $newcontext);
440 $DB->set_field('question_categories', 'contextid', $newcontext->id
, array('contextid' => $context->id
));
444 $a->oldplace
= $context->get_context_name();
445 $a->newplace
= $newcontext->get_context_name();
446 echo $OUTPUT->notification(
447 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
455 * Enter description here...
457 * @param array $questionids of question ids
458 * @param object $newcontextid the context to create the saved category in.
459 * @param string $oldplace a textual description of the think being deleted,
460 * e.g. from get_context_name
461 * @param object $newcategory
462 * @return mixed false on
464 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
465 $newcategory = null) {
468 // Make a category in the parent context to move the questions to.
469 if (is_null($newcategory)) {
470 $newcategory = new stdClass();
471 $newcategory->parent
= 0;
472 $newcategory->contextid
= $newcontextid;
473 $newcategory->name
= get_string('questionsrescuedfrom', 'question', $oldplace);
474 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
475 $newcategory->sortorder
= 999;
476 $newcategory->stamp
= make_unique_id_code();
477 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
480 // Move any remaining questions to the 'saved' category.
481 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
488 * All question categories and their questions are deleted for this activity.
490 * @param object $cm the course module object representing the activity
491 * @param boolean $feedback to specify if the process must output a summary of its work
494 function question_delete_activity($cm, $feedback=true) {
497 $modcontext = context_module
::instance($cm->id
);
498 $feedbackdata = question_delete_context($modcontext->id
, $feedback);
499 // Inform about changes performed if feedback is enabled.
500 if ($feedback && $feedbackdata) {
501 $table = new html_table();
502 $table->head
= array(get_string('category', 'question'), get_string('action'));
503 $table->data
= $feedbackdata;
504 echo html_writer
::table($table);
510 * This function should be considered private to the question bank, it is called from
511 * question/editlib.php question/contextmoveq.php and a few similar places to to the
512 * work of acutally moving questions and associated data. However, callers of this
513 * function also have to do other work, which is why you should not call this method
514 * directly from outside the questionbank.
516 * @param array $questionids of question ids.
517 * @param integer $newcategoryid the id of the category to move to.
519 function question_move_questions_to_category($questionids, $newcategoryid) {
522 $newcontextid = $DB->get_field('question_categories', 'contextid',
523 array('id' => $newcategoryid));
524 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
525 $questions = $DB->get_records_sql("
526 SELECT q.id, q.qtype, qc.contextid
528 JOIN {question_categories} qc ON q.category = qc.id
529 WHERE q.id $questionidcondition", $params);
530 foreach ($questions as $question) {
531 if ($newcontextid != $question->contextid
) {
532 question_bank
::get_qtype($question->qtype
)->move_files(
533 $question->id
, $question->contextid
, $newcontextid);
537 // Move the questions themselves.
538 $DB->set_field_select('question', 'category', $newcategoryid,
539 "id $questionidcondition", $params);
541 // Move any subquestions belonging to them.
542 $DB->set_field_select('question', 'category', $newcategoryid,
543 "parent $questionidcondition", $params);
545 // Update the contextid for any tag instances that may exist for these questions.
546 core_tag_tag
::change_items_context('core_question', 'question', $questionids, $newcontextid);
548 // TODO Deal with datasets.
550 // Purge these questions from the cache.
551 foreach ($questions as $question) {
552 question_bank
::notify_question_edited($question->id
);
559 * This function helps move a question cateogry to a new context by moving all
560 * the files belonging to all the questions to the new context.
561 * Also moves subcategories.
562 * @param integer $categoryid the id of the category being moved.
563 * @param integer $oldcontextid the old context id.
564 * @param integer $newcontextid the new context id.
566 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
569 $questionids = $DB->get_records_menu('question',
570 array('category' => $categoryid), '', 'id,qtype');
571 foreach ($questionids as $questionid => $qtype) {
572 question_bank
::get_qtype($qtype)->move_files(
573 $questionid, $oldcontextid, $newcontextid);
574 // Purge this question from the cache.
575 question_bank
::notify_question_edited($questionid);
578 core_tag_tag
::change_items_context('core_question', 'question',
579 array_keys($questionids), $newcontextid);
581 $subcatids = $DB->get_records_menu('question_categories',
582 array('parent' => $categoryid), '', 'id,1');
583 foreach ($subcatids as $subcatid => $notused) {
584 $DB->set_field('question_categories', 'contextid', $newcontextid,
585 array('id' => $subcatid));
586 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
591 * Generate the URL for starting a new preview of a given question with the given options.
592 * @param integer $questionid the question to preview.
593 * @param string $preferredbehaviour the behaviour to use for the preview.
594 * @param float $maxmark the maximum to mark the question out of.
595 * @param question_display_options $displayoptions the display options to use.
596 * @param int $variant the variant of the question to preview. If null, one will
597 * be picked randomly.
598 * @param object $context context to run the preview in (affects things like
599 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
600 * @return moodle_url the URL.
602 function question_preview_url($questionid, $preferredbehaviour = null,
603 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
605 $params = array('id' => $questionid);
607 if (is_null($context)) {
609 $context = $PAGE->context
;
611 if ($context->contextlevel
== CONTEXT_MODULE
) {
612 $params['cmid'] = $context->instanceid
;
613 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
614 $params['courseid'] = $context->instanceid
;
617 if (!is_null($preferredbehaviour)) {
618 $params['behaviour'] = $preferredbehaviour;
621 if (!is_null($maxmark)) {
622 $params['maxmark'] = $maxmark;
625 if (!is_null($displayoptions)) {
626 $params['correctness'] = $displayoptions->correctness
;
627 $params['marks'] = $displayoptions->marks
;
628 $params['markdp'] = $displayoptions->markdp
;
629 $params['feedback'] = (bool) $displayoptions->feedback
;
630 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
631 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
632 $params['history'] = (bool) $displayoptions->history
;
636 $params['variant'] = $variant;
639 return new moodle_url('/question/preview.php', $params);
643 * @return array that can be passed as $params to the {@link popup_action} constructor.
645 function question_preview_popup_params() {
653 * Given a list of ids, load the basic information about a set of questions from
654 * the questions table. The $join and $extrafields arguments can be used together
655 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
656 * read the code below to see how the SQL is assembled. Throws exceptions on error.
658 * @param array $questionids array of question ids to load. If null, then all
659 * questions matched by $join will be loaded.
660 * @param string $extrafields extra SQL code to be added to the query.
661 * @param string $join extra SQL code to be added to the query.
662 * @param array $extraparams values for any placeholders in $join.
663 * You must use named placeholders.
664 * @param string $orderby what to order the results by. Optional, default is unspecified order.
666 * @return array partially complete question objects. You need to call get_question_options
667 * on them before they can be properly used.
669 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
670 $extraparams = array(), $orderby = '') {
673 if ($questionids === null) {
677 if (empty($questionids)) {
681 list($questionidcondition, $params) = $DB->get_in_or_equal(
682 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
683 $where = 'WHERE q.id ' . $questionidcondition;
687 $join = 'JOIN ' . $join;
691 $extrafields = ', ' . $extrafields;
695 $orderby = 'ORDER BY ' . $orderby;
698 $sql = "SELECT q.*, qc.contextid{$extrafields}
700 JOIN {question_categories} qc ON q.category = qc.id
705 // Load the questions.
706 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
707 foreach ($questions as $question) {
708 $question->_partiallyloaded
= true;
715 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
716 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
717 * read the code below to see how the SQL is assembled. Throws exceptions on error.
719 * @param array $questionids array of question ids.
720 * @param string $extrafields extra SQL code to be added to the query.
721 * @param string $join extra SQL code to be added to the query.
722 * @param array $extraparams values for any placeholders in $join.
723 * You are strongly recommended to use named placeholder.
725 * @return array question objects.
727 function question_load_questions($questionids, $extrafields = '', $join = '') {
728 $questions = question_preload_questions($questionids, $extrafields, $join);
730 // Load the question type specific information
731 if (!get_question_options($questions)) {
732 return 'Could not load the question options';
739 * Private function to factor common code out of get_question_options().
741 * @param object $question the question to tidy.
742 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
744 function _tidy_question($question, $loadtags = false) {
747 // Load question-type specific fields.
748 if (!question_bank
::is_qtype_installed($question->qtype
)) {
749 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
750 'qtype_missingtype')) . $question->questiontext
;
752 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
754 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
755 $question->defaultmark +
= 0;
756 $question->penalty +
= 0;
758 if (isset($question->_partiallyloaded
)) {
759 unset($question->_partiallyloaded
);
762 if ($loadtags && core_tag_tag
::is_enabled('core_question', 'question')) {
763 $question->tags
= core_tag_tag
::get_item_tags_array('core_question', 'question', $question->id
);
768 * Updates the question objects with question type specific
769 * information by calling {@link get_question_options()}
771 * Can be called either with an array of question objects or with a single
774 * @param mixed $questions Either an array of question objects to be updated
775 * or just a single question object
776 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
777 * @return bool Indicates success or failure.
779 function get_question_options(&$questions, $loadtags = false) {
780 if (is_array($questions)) { // deal with an array of questions
781 foreach ($questions as $i => $notused) {
782 _tidy_question($questions[$i], $loadtags);
784 } else { // deal with single question
785 _tidy_question($questions, $loadtags);
791 * Print the icon for the question type
793 * @param object $question The question object for which the icon is required.
794 * Only $question->qtype is used.
795 * @return string the HTML for the img tag.
797 function print_question_icon($question) {
799 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
803 * Creates a stamp that uniquely identifies this version of the question
805 * In future we want this to use a hash of the question data to guarantee that
806 * identical versions have the same version stamp.
808 * @param object $question
809 * @return string A unique version stamp
811 function question_hash($question) {
812 return make_unique_id_code();
815 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
818 * returns the categories with their names ordered following parent-child relationships
819 * finally it tries to return pending categories (those being orphaned, whose parent is
820 * incorrect) to avoid missing any category from original array.
822 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
826 $keys = array_keys($categories);
828 foreach ($keys as $key) {
829 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
830 $children[$key] = $categories[$key];
831 $categories[$key]->processed
= true;
832 $children = $children +
sort_categories_by_tree(
833 $categories, $children[$key]->id
, $level+
1);
836 //If level = 1, we have finished, try to look for non processed categories
837 // (bad parent) and sort them too
839 foreach ($keys as $key) {
840 // If not processed and it's a good candidate to start (because its
841 // parent doesn't exist in the course)
842 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
843 array('contextid' => $categories[$key]->contextid
,
844 'id' => $categories[$key]->parent
))) {
845 $children[$key] = $categories[$key];
846 $categories[$key]->processed
= true;
847 $children = $children +
sort_categories_by_tree(
848 $categories, $children[$key]->id
, $level +
1);
856 * Private method, only for the use of add_indented_names().
858 * Recursively adds an indentedname field to each category, starting with the category
859 * with id $id, and dealing with that category and all its children, and
860 * return a new array, with those categories in the right order.
862 * @param array $categories an array of categories which has had childids
863 * fields added by flatten_category_tree(). Passed by reference for
864 * performance only. It is not modfied.
865 * @param int $id the category to start the indenting process from.
866 * @param int $depth the indent depth. Used in recursive calls.
867 * @return array a new array of categories, in the right order for the tree.
869 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
871 // Indent the name of this category.
872 $newcategories = array();
873 $newcategories[$id] = $categories[$id];
874 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
875 $categories[$id]->name
;
877 // Recursively indent the children.
878 foreach ($categories[$id]->childids
as $childid) {
879 if ($childid != $nochildrenof) {
880 $newcategories = $newcategories +
flatten_category_tree(
881 $categories, $childid, $depth +
1, $nochildrenof);
885 // Remove the childids array that were temporarily added.
886 unset($newcategories[$id]->childids
);
888 return $newcategories;
892 * Format categories into an indented list reflecting the tree structure.
894 * @param array $categories An array of category objects, for example from the.
895 * @return array The formatted list of categories.
897 function add_indented_names($categories, $nochildrenof = -1) {
899 // Add an array to each category to hold the child category ids. This array
900 // will be removed again by flatten_category_tree(). It should not be used
901 // outside these two functions.
902 foreach (array_keys($categories) as $id) {
903 $categories[$id]->childids
= array();
906 // Build the tree structure, and record which categories are top-level.
907 // We have to be careful, because the categories array may include published
908 // categories from other courses, but not their parents.
909 $toplevelcategoryids = array();
910 foreach (array_keys($categories) as $id) {
911 if (!empty($categories[$id]->parent
) &&
912 array_key_exists($categories[$id]->parent
, $categories)) {
913 $categories[$categories[$id]->parent
]->childids
[] = $id;
915 $toplevelcategoryids[] = $id;
919 // Flatten the tree to and add the indents.
920 $newcategories = array();
921 foreach ($toplevelcategoryids as $id) {
922 $newcategories = $newcategories +
flatten_category_tree(
923 $categories, $id, 0, $nochildrenof);
926 return $newcategories;
930 * Output a select menu of question categories.
932 * Categories from this course and (optionally) published categories from other courses
933 * are included. Optionally, only categories the current user may edit can be included.
935 * @param integer $courseid the id of the course to get the categories for.
936 * @param integer $published if true, include publised categories from other courses.
937 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
938 * @param integer $selected optionally, the id of a category to be selected by
939 * default in the dropdown.
941 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
942 $selected = "", $nochildrenof = -1) {
944 $categoriesarray = question_category_options($contexts, $top, $currentcat,
945 false, $nochildrenof);
949 $choose = 'choosedots';
952 foreach ($categoriesarray as $group => $opts) {
953 $options[] = array($group => $opts);
955 echo html_writer
::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
956 echo html_writer
::select($options, 'category', $selected, $choose, array('id' => 'id_movetocategory'));
960 * @param integer $contextid a context id.
961 * @return object the default question category for that context, or false if none.
963 function question_get_default_category($contextid) {
965 $category = $DB->get_records('question_categories',
966 array('contextid' => $contextid), 'id', '*', 0, 1);
967 if (!empty($category)) {
968 return reset($category);
975 * Gets the default category in the most specific context.
976 * If no categories exist yet then default ones are created in all contexts.
978 * @param array $contexts The context objects for this context and all parent contexts.
979 * @return object The default category - the category in the course context
981 function question_make_default_categories($contexts) {
983 static $preferredlevels = array(
986 CONTEXT_COURSECAT
=> 2,
992 // If it already exists, just return it.
993 foreach ($contexts as $key => $context) {
994 if (!$exists = $DB->record_exists("question_categories",
995 array('contextid' => $context->id
))) {
996 // Otherwise, we need to make one
997 $category = new stdClass();
998 $contextname = $context->get_context_name(false, true);
999 $category->name
= get_string('defaultfor', 'question', $contextname);
1000 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1001 $category->contextid
= $context->id
;
1002 $category->parent
= 0;
1003 // By default, all categories get this number, and are sorted alphabetically.
1004 $category->sortorder
= 999;
1005 $category->stamp
= make_unique_id_code();
1006 $category->id
= $DB->insert_record('question_categories', $category);
1008 $category = question_get_default_category($context->id
);
1010 $thispreferredness = $preferredlevels[$context->contextlevel
];
1011 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1012 $thispreferredness +
= 10;
1014 if ($thispreferredness > $preferredness) {
1015 $toreturn = $category;
1016 $preferredness = $thispreferredness;
1020 if (!is_null($toreturn)) {
1021 $toreturn = clone($toreturn);
1027 * Get all the category objects, including a count of the number of questions in that category,
1028 * for all the categories in the lists $contexts.
1030 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1031 * @param string $sortorder used as the ORDER BY clause in the select statement.
1032 * @return array of category objects.
1034 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1036 return $DB->get_records_sql("
1037 SELECT c.*, (SELECT count(1) FROM {question} q
1038 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1039 FROM {question_categories} c
1040 WHERE c.contextid IN ($contexts)
1041 ORDER BY $sortorder");
1045 * Output an array of question categories.
1047 function question_category_options($contexts, $top = false, $currentcat = 0,
1048 $popupform = false, $nochildrenof = -1) {
1050 $pcontexts = array();
1051 foreach ($contexts as $context) {
1052 $pcontexts[] = $context->id
;
1054 $contextslist = join($pcontexts, ', ');
1056 $categories = get_categories_for_contexts($contextslist);
1058 $categories = question_add_context_in_key($categories);
1061 $categories = question_add_tops($categories, $pcontexts);
1063 $categories = add_indented_names($categories, $nochildrenof);
1065 // sort cats out into different contexts
1066 $categoriesarray = array();
1067 foreach ($pcontexts as $contextid) {
1068 $context = context
::instance_by_id($contextid);
1069 $contextstring = $context->get_context_name(true, true);
1070 foreach ($categories as $category) {
1071 if ($category->contextid
== $contextid) {
1072 $cid = $category->id
;
1073 if ($currentcat != $cid ||
$currentcat == 0) {
1074 $countstring = !empty($category->questioncount
) ?
1075 " ($category->questioncount)" : '';
1076 $categoriesarray[$contextstring][$cid] =
1077 format_string($category->indentedname
, true,
1078 array('context' => $context)) . $countstring;
1084 $popupcats = array();
1085 foreach ($categoriesarray as $contextstring => $optgroup) {
1087 foreach ($optgroup as $key => $value) {
1088 $key = str_replace($CFG->wwwroot
, '', $key);
1089 $group[$key] = $value;
1091 $popupcats[] = array($contextstring => $group);
1095 return $categoriesarray;
1099 function question_add_context_in_key($categories) {
1100 $newcatarray = array();
1101 foreach ($categories as $id => $category) {
1102 $category->parent
= "$category->parent,$category->contextid";
1103 $category->id
= "$category->id,$category->contextid";
1104 $newcatarray["$id,$category->contextid"] = $category;
1106 return $newcatarray;
1109 function question_add_tops($categories, $pcontexts) {
1111 foreach ($pcontexts as $context) {
1112 $newcat = new stdClass();
1113 $newcat->id
= "0,$context";
1114 $newcat->name
= get_string('top');
1115 $newcat->parent
= -1;
1116 $newcat->contextid
= $context;
1117 $topcats["0,$context"] = $newcat;
1119 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1120 return array_merge($topcats, $categories);
1124 * @return array of question category ids of the category and all subcategories.
1126 function question_categorylist($categoryid) {
1129 // final list of category IDs
1130 $categorylist = array();
1132 // a list of category IDs to check for any sub-categories
1133 $subcategories = array($categoryid);
1135 while ($subcategories) {
1136 foreach ($subcategories as $subcategory) {
1137 // if anything from the temporary list was added already, then we have a loop
1138 if (isset($categorylist[$subcategory])) {
1139 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1141 $categorylist[$subcategory] = $subcategory;
1144 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1146 $subcategories = $DB->get_records_select_menu('question_categories',
1147 "parent $in", $params, NULL, 'id,id AS id2');
1150 return $categorylist;
1153 //===========================
1154 // Import/Export Functions
1155 //===========================
1158 * Get list of available import or export formats
1159 * @param string $type 'import' if import list, otherwise export list assumed
1160 * @return array sorted list of import/export formats available
1162 function get_import_export_formats($type) {
1164 require_once($CFG->dirroot
. '/question/format.php');
1166 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1168 $fileformatname = array();
1169 foreach ($formatclasses as $component => $formatclass) {
1171 $format = new $formatclass();
1172 if ($type == 'import') {
1173 $provided = $format->provide_import();
1175 $provided = $format->provide_export();
1179 list($notused, $fileformat) = explode('_', $component, 2);
1180 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1184 core_collator
::asort($fileformatnames);
1185 return $fileformatnames;
1190 * Create a reasonable default file name for exporting questions from a particular
1192 * @param object $course the course the questions are in.
1193 * @param object $category the question category.
1194 * @return string the filename.
1196 function question_default_export_filename($course, $category) {
1197 // We build a string that is an appropriate name (questions) from the lang pack,
1198 // then the corse shortname, then the question category name, then a timestamp.
1200 $base = clean_filename(get_string('exportfilename', 'question'));
1202 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1203 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1205 $shortname = clean_filename($course->shortname
);
1206 if ($shortname == '' ||
$shortname == '_' ) {
1207 $shortname = $course->id
;
1210 $categoryname = clean_filename(format_string($category->name
));
1212 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1214 return $export_name;
1218 * Converts contextlevels to strings and back to help with reading/writing contexts
1219 * to/from import/export files.
1221 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1224 class context_to_string_translator
{
1226 * @var array used to translate between contextids and strings for this context.
1228 protected $contexttostringarray = array();
1230 public function __construct($contexts) {
1231 $this->generate_context_to_string_array($contexts);
1234 public function context_to_string($contextid) {
1235 return $this->contexttostringarray
[$contextid];
1238 public function string_to_context($contextname) {
1239 $contextid = array_search($contextname, $this->contexttostringarray
);
1243 protected function generate_context_to_string_array($contexts) {
1244 if (!$this->contexttostringarray
) {
1246 foreach ($contexts as $context) {
1247 switch ($context->contextlevel
) {
1248 case CONTEXT_MODULE
:
1249 $contextstring = 'module';
1251 case CONTEXT_COURSE
:
1252 $contextstring = 'course';
1254 case CONTEXT_COURSECAT
:
1255 $contextstring = "cat$catno";
1258 case CONTEXT_SYSTEM
:
1259 $contextstring = 'system';
1262 $this->contexttostringarray
[$context->id
] = $contextstring;
1270 * Check capability on category
1272 * @param mixed $question object or id
1273 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1274 * @param integer $cachecat useful to cache all question records in a category
1275 * @return boolean this user has the capability $cap for this question $question?
1277 function question_has_capability_on($question, $cap, $cachecat = -1) {
1280 // these are capabilities on existing questions capabilties are
1281 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1282 $question_questioncaps = array('edit', 'view', 'use', 'move');
1283 static $questions = array();
1284 static $categories = array();
1285 static $cachedcat = array();
1286 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1287 $questions +
= $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1288 $cachedcat[] = $cachecat;
1290 if (!is_object($question)) {
1291 if (!isset($questions[$question])) {
1292 if (!$questions[$question] = $DB->get_record('question',
1293 array('id' => $question), 'id,category,createdby')) {
1294 print_error('questiondoesnotexist', 'question');
1297 $question = $questions[$question];
1299 if (empty($question->category
)) {
1300 // This can happen when we have created a fake 'missingtype' question to
1301 // take the place of a deleted question.
1304 if (!isset($categories[$question->category
])) {
1305 if (!$categories[$question->category
] = $DB->get_record('question_categories',
1306 array('id'=>$question->category
))) {
1307 print_error('invalidcategory', 'question');
1310 $category = $categories[$question->category
];
1311 $context = context
::instance_by_id($category->contextid
);
1313 if (array_search($cap, $question_questioncaps)!== false) {
1314 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1315 if ($question->createdby
== $USER->id
) {
1316 return has_capability('moodle/question:' . $cap . 'mine', $context);
1324 return has_capability('moodle/question:' . $cap, $context);
1330 * Require capability on question.
1332 function question_require_capability_on($question, $cap) {
1333 if (!question_has_capability_on($question, $cap)) {
1334 print_error('nopermissions', '', '', $cap);
1340 * @param object $context a context
1341 * @return string A URL for editing questions in this context.
1343 function question_edit_url($context) {
1345 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1348 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1349 $defaultcategory = question_get_default_category($context->id
);
1350 if ($defaultcategory) {
1351 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1353 switch ($context->contextlevel
) {
1354 case CONTEXT_SYSTEM
:
1355 return $baseurl . 'courseid=' . $SITE->id
;
1356 case CONTEXT_COURSECAT
:
1357 // This is nasty, becuase we can only edit questions in a course
1358 // context at the moment, so for now we just return false.
1360 case CONTEXT_COURSE
:
1361 return $baseurl . 'courseid=' . $context->instanceid
;
1362 case CONTEXT_MODULE
:
1363 return $baseurl . 'cmid=' . $context->instanceid
;
1369 * Adds question bank setting links to the given navigation node if caps are met.
1371 * @param navigation_node $navigationnode The navigation node to add the question branch to
1372 * @param object $context
1373 * @return navigation_node Returns the question branch that was added
1375 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1378 if ($context->contextlevel
== CONTEXT_COURSE
) {
1379 $params = array('courseid'=>$context->instanceid
);
1380 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1381 $params = array('cmid'=>$context->instanceid
);
1386 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1387 $params['cat'] = $cat;
1390 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1391 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
);
1393 $contexts = new question_edit_contexts($context);
1394 if ($contexts->have_one_edit_tab_cap('questions')) {
1395 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1396 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
);
1398 if ($contexts->have_one_edit_tab_cap('categories')) {
1399 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1400 '/question/category.php', $params), navigation_node
::TYPE_SETTING
);
1402 if ($contexts->have_one_edit_tab_cap('import')) {
1403 $questionnode->add(get_string('import', 'question'), new moodle_url(
1404 '/question/import.php', $params), navigation_node
::TYPE_SETTING
);
1406 if ($contexts->have_one_edit_tab_cap('export')) {
1407 $questionnode->add(get_string('export', 'question'), new moodle_url(
1408 '/question/export.php', $params), navigation_node
::TYPE_SETTING
);
1411 return $questionnode;
1415 * @return array all the capabilities that relate to accessing particular questions.
1417 function question_get_question_capabilities() {
1419 'moodle/question:add',
1420 'moodle/question:editmine',
1421 'moodle/question:editall',
1422 'moodle/question:viewmine',
1423 'moodle/question:viewall',
1424 'moodle/question:usemine',
1425 'moodle/question:useall',
1426 'moodle/question:movemine',
1427 'moodle/question:moveall',
1432 * @return array all the question bank capabilities.
1434 function question_get_all_capabilities() {
1435 $caps = question_get_question_capabilities();
1436 $caps[] = 'moodle/question:managecategory';
1437 $caps[] = 'moodle/question:flag';
1443 * Tracks all the contexts related to the one where we are currently editing
1444 * questions, and provides helper methods to check permissions.
1446 * @copyright 2007 Jamie Pratt me@jamiep.org
1447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1449 class question_edit_contexts
{
1451 public static $caps = array(
1452 'editq' => array('moodle/question:add',
1453 'moodle/question:editmine',
1454 'moodle/question:editall',
1455 'moodle/question:viewmine',
1456 'moodle/question:viewall',
1457 'moodle/question:usemine',
1458 'moodle/question:useall',
1459 'moodle/question:movemine',
1460 'moodle/question:moveall'),
1461 'questions'=>array('moodle/question:add',
1462 'moodle/question:editmine',
1463 'moodle/question:editall',
1464 'moodle/question:viewmine',
1465 'moodle/question:viewall',
1466 'moodle/question:movemine',
1467 'moodle/question:moveall'),
1468 'categories'=>array('moodle/question:managecategory'),
1469 'import'=>array('moodle/question:add'),
1470 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1472 protected $allcontexts;
1476 * @param context the current context.
1478 public function __construct(context
$thiscontext) {
1479 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1483 * @return array all parent contexts
1485 public function all() {
1486 return $this->allcontexts
;
1490 * @return object lowest context which must be either the module or course context
1492 public function lowest() {
1493 return $this->allcontexts
[0];
1497 * @param string $cap capability
1498 * @return array parent contexts having capability, zero based index
1500 public function having_cap($cap) {
1501 $contextswithcap = array();
1502 foreach ($this->allcontexts
as $context) {
1503 if (has_capability($cap, $context)) {
1504 $contextswithcap[] = $context;
1507 return $contextswithcap;
1511 * @param array $caps capabilities
1512 * @return array parent contexts having at least one of $caps, zero based index
1514 public function having_one_cap($caps) {
1515 $contextswithacap = array();
1516 foreach ($this->allcontexts
as $context) {
1517 foreach ($caps as $cap) {
1518 if (has_capability($cap, $context)) {
1519 $contextswithacap[] = $context;
1520 break; //done with caps loop
1524 return $contextswithacap;
1528 * @param string $tabname edit tab name
1529 * @return array parent contexts having at least one of $caps, zero based index
1531 public function having_one_edit_tab_cap($tabname) {
1532 return $this->having_one_cap(self
::$caps[$tabname]);
1536 * @return those contexts where a user can add a question and then use it.
1538 public function having_add_and_use() {
1539 $contextswithcap = array();
1540 foreach ($this->allcontexts
as $context) {
1541 if (!has_capability('moodle/question:add', $context)) {
1544 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1547 $contextswithcap[] = $context;
1549 return $contextswithcap;
1553 * Has at least one parent context got the cap $cap?
1555 * @param string $cap capability
1558 public function have_cap($cap) {
1559 return (count($this->having_cap($cap)));
1563 * Has at least one parent context got one of the caps $caps?
1565 * @param array $caps capability
1568 public function have_one_cap($caps) {
1569 foreach ($caps as $cap) {
1570 if ($this->have_cap($cap)) {
1578 * Has at least one parent context got one of the caps for actions on $tabname
1580 * @param string $tabname edit tab name
1583 public function have_one_edit_tab_cap($tabname) {
1584 return $this->have_one_cap(self
::$caps[$tabname]);
1588 * Throw error if at least one parent context hasn't got the cap $cap
1590 * @param string $cap capability
1592 public function require_cap($cap) {
1593 if (!$this->have_cap($cap)) {
1594 print_error('nopermissions', '', '', $cap);
1599 * Throw error if at least one parent context hasn't got one of the caps $caps
1601 * @param array $cap capabilities
1603 public function require_one_cap($caps) {
1604 if (!$this->have_one_cap($caps)) {
1605 $capsstring = join($caps, ', ');
1606 print_error('nopermissions', '', '', $capsstring);
1611 * Throw error if at least one parent context hasn't got one of the caps $caps
1613 * @param string $tabname edit tab name
1615 public function require_one_edit_tab_cap($tabname) {
1616 if (!$this->have_one_edit_tab_cap($tabname)) {
1617 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1624 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1626 * @package core_question
1628 * @param string $text text being processed
1629 * @param string $file the php script used to serve files
1630 * @param int $contextid context ID
1631 * @param string $component component
1632 * @param string $filearea filearea
1633 * @param array $ids other IDs will be used to check file permission
1634 * @param int $itemid item ID
1635 * @param array $options options
1638 function question_rewrite_question_urls($text, $file, $contextid, $component,
1639 $filearea, array $ids, $itemid, array $options=null) {
1643 $idsstr .= implode('/', $ids);
1645 if ($itemid !== null) {
1646 $idsstr .= '/' . $itemid;
1648 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1649 $filearea, $idsstr, $options);
1653 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1654 * viewing the question outside an attempt (for example, in the question bank
1655 * listing or in the quiz statistics report).
1657 * @param string $text the question text.
1658 * @param int $questionid the question id.
1659 * @param int $filecontextid the context id of the question being displayed.
1660 * @param string $filecomponent the component that owns the file area.
1661 * @param string $filearea the file area name.
1662 * @param int|null $itemid the file's itemid
1663 * @param int $previewcontextid the context id where the preview is being displayed.
1664 * @param string $previewcomponent component responsible for displaying the preview.
1665 * @param array $options text and file options ('forcehttps'=>false)
1666 * @return string $questiontext with URLs rewritten.
1668 function question_rewrite_question_preview_urls($text, $questionid,
1669 $filecontextid, $filecomponent, $filearea, $itemid,
1670 $previewcontextid, $previewcomponent, $options = null) {
1672 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1674 $path .= '/' . $itemid;
1677 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1678 $filecomponent, $filearea, $path, $options);
1682 * Called by pluginfile.php to serve files related to the 'question' core
1683 * component and for files belonging to qtypes.
1685 * For files that relate to questions in a question_attempt, then we delegate to
1686 * a function in the component that owns the attempt (for example in the quiz,
1687 * or in core question preview) to get necessary inforation.
1689 * (Note that, at the moment, all question file areas relate to questions in
1690 * attempts, so the If at the start of the last paragraph is always true.)
1692 * Does not return, either calls send_file_not_found(); or serves the file.
1694 * @package core_question
1696 * @param stdClass $course course settings object
1697 * @param stdClass $context context object
1698 * @param string $component the name of the component we are serving files for.
1699 * @param string $filearea the name of the file area.
1700 * @param array $args the remaining bits of the file path.
1701 * @param bool $forcedownload whether the user must be forced to download the file.
1702 * @param array $options additional options affecting the file serving
1704 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1707 // Special case, sending a question bank export.
1708 if ($filearea === 'export') {
1709 list($context, $course, $cm) = get_context_info_array($context->id
);
1710 require_login($course, false, $cm);
1712 require_once($CFG->dirroot
. '/question/editlib.php');
1713 $contexts = new question_edit_contexts($context);
1714 // check export capability
1715 $contexts->require_one_edit_tab_cap('export');
1716 $category_id = (int)array_shift($args);
1717 $format = array_shift($args);
1718 $cattofile = array_shift($args);
1719 $contexttofile = array_shift($args);
1720 $filename = array_shift($args);
1722 // load parent class for import/export
1723 require_once($CFG->dirroot
. '/question/format.php');
1724 require_once($CFG->dirroot
. '/question/editlib.php');
1725 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
1727 $classname = 'qformat_' . $format;
1728 if (!class_exists($classname)) {
1729 send_file_not_found();
1732 $qformat = new $classname();
1734 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1735 send_file_not_found();
1738 $qformat->setCategory($category);
1739 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1740 $qformat->setCourse($course);
1742 if ($cattofile == 'withcategories') {
1743 $qformat->setCattofile(true);
1745 $qformat->setCattofile(false);
1748 if ($contexttofile == 'withcontexts') {
1749 $qformat->setContexttofile(true);
1751 $qformat->setContexttofile(false);
1754 if (!$qformat->exportpreprocess()) {
1755 send_file_not_found();
1756 print_error('exporterror', 'question', $thispageurl->out());
1759 // export data to moodle file pool
1760 if (!$content = $qformat->exportprocess(true)) {
1761 send_file_not_found();
1764 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1767 // Normal case, a file belonging to a question.
1768 $qubaidorpreview = array_shift($args);
1770 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1771 if ($qubaidorpreview === 'preview') {
1772 $previewcontextid = (int)array_shift($args);
1773 $previewcomponent = array_shift($args);
1774 $questionid = (int) array_shift($args);
1775 $previewcontext = context_helper
::instance_by_id($previewcontextid);
1777 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1778 $previewcontext, $questionid,
1779 $context, $component, $filearea, $args,
1780 $forcedownload, $options), 'callbackmissing');
1782 if ($result === 'callbackmissing') {
1783 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1784 "{$previewcomponent}_question_preview_pluginfile callback. " .
1785 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER
);
1788 send_file_not_found();
1791 // 2. A question being attempted in the normal way.
1792 $qubaid = (int)$qubaidorpreview;
1793 $slot = (int)array_shift($args);
1795 $module = $DB->get_field('question_usages', 'component',
1796 array('id' => $qubaid));
1798 send_file_not_found();
1801 if ($module === 'core_question_preview') {
1802 require_once($CFG->dirroot
. '/question/previewlib.php');
1803 return question_preview_question_pluginfile($course, $context,
1804 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1807 $dir = core_component
::get_component_directory($module);
1808 if (!file_exists("$dir/lib.php")) {
1809 send_file_not_found();
1811 include_once("$dir/lib.php");
1813 $filefunction = $module . '_question_pluginfile';
1814 if (function_exists($filefunction)) {
1815 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1816 $args, $forcedownload, $options);
1819 // Okay, we're here so lets check for function without 'mod_'.
1820 if (strpos($module, 'mod_') === 0) {
1821 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1822 if (function_exists($filefunctionold)) {
1823 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1824 $args, $forcedownload, $options);
1828 send_file_not_found();
1833 * Serve questiontext files in the question text when they are displayed in this report.
1835 * @package core_files
1837 * @param context $previewcontext the context in which the preview is happening.
1838 * @param int $questionid the question id.
1839 * @param context $filecontext the file (question) context.
1840 * @param string $filecomponent the component the file belongs to.
1841 * @param string $filearea the file area.
1842 * @param array $args remaining file args.
1843 * @param bool $forcedownload.
1844 * @param array $options additional options affecting the file serving.
1846 function core_question_question_preview_pluginfile($previewcontext, $questionid,
1847 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
1850 // Verify that contextid matches the question.
1851 $question = $DB->get_record_sql('
1852 SELECT q.*, qc.contextid
1854 JOIN {question_categories} qc ON qc.id = q.category
1855 WHERE q.id = :id AND qc.contextid = :contextid',
1856 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
1858 // Check the capability.
1859 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
1860 require_login($course, false, $cm);
1862 question_require_capability_on($question, 'use');
1864 $fs = get_file_storage();
1865 $relativepath = implode('/', $args);
1866 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1867 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1868 send_file_not_found();
1871 send_stored_file($file, 0, 0, $forcedownload, $options);
1875 * Create url for question export
1877 * @param int $contextid, current context
1878 * @param int $categoryid, categoryid
1879 * @param string $format
1880 * @param string $withcategories
1881 * @param string $ithcontexts
1882 * @param moodle_url export file url
1884 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1885 $withcontexts, $filename) {
1887 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1888 return moodle_url
::make_file_url($urlbase,
1889 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1890 "/{$withcontexts}/{$filename}", true);
1894 * Return a list of page types
1895 * @param string $pagetype current page type
1896 * @param stdClass $parentcontext Block's parent context
1897 * @param stdClass $currentcontext Current context of block
1899 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1902 'question-*'=>get_string('page-question-x', 'question'),
1903 'question-edit'=>get_string('page-question-edit', 'question'),
1904 'question-category'=>get_string('page-question-category', 'question'),
1905 'question-export'=>get_string('page-question-export', 'question'),
1906 'question-import'=>get_string('page-question-import', 'question')
1908 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
1909 require_once($CFG->dirroot
. '/course/lib.php');
1910 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1917 * Does an activity module use the question bank?
1919 * @param string $modname The name of the module (without mod_ prefix).
1920 * @return bool true if the module uses questions.
1922 function question_module_uses_questions($modname) {
1923 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
1927 $component = 'mod_'.$modname;
1928 if (component_callback_exists($component, 'question_pluginfile')) {
1929 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);