2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') ||
die();
37 require_once($CFG->dirroot
. '/question/engine/lib.php');
38 require_once($CFG->dirroot
. '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
82 // Work out the other index.
83 $otherkey = $key +
$direction;
84 if (!isset($neworder[$otherkey])) {
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
95 * Save a new question type order to the config_plugins table.
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) ||
$config->$sortvar != $index +
1) {
110 set_config($sortvar, $index +
1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * Returns an array of names of activity modules that use this question
120 * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
122 * @param object $questionid
123 * @return array of strings
125 function question_list_instances($questionid) {
126 throw new coding_exception('question_list_instances has been deprectated. ' .
127 'Please use questions_in_use instead.');
131 * @param array $questionids of question ids.
132 * @return boolean whether any of these questions are being used by any part of Moodle.
134 function questions_in_use($questionids) {
137 if (question_engine
::questions_in_use($questionids)) {
141 foreach (core_component
::get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
146 $fn = $module . '_questions_in_use';
147 if (function_exists($fn)) {
148 if ($fn($questionids)) {
153 // Fallback for legacy modules.
154 $fn = $module . '_question_list_instances';
155 if (function_exists($fn)) {
156 foreach ($questionids as $questionid) {
157 $instances = $fn($questionid);
158 if (!empty($instances)) {
171 * Determine whether there arey any questions belonging to this context, that is whether any of its
172 * question categories contain any questions. This will return true even if all the questions are
175 * @param mixed $context either a context object, or a context id.
176 * @return boolean whether any of the question categories beloning to this context have
177 * any questions in them.
179 function question_context_has_any_questions($context) {
181 if (is_object($context)) {
182 $contextid = $context->id
;
183 } else if (is_numeric($context)) {
184 $contextid = $context;
186 print_error('invalidcontextinhasanyquestions', 'question');
188 return $DB->record_exists_sql("SELECT *
190 JOIN {question_categories} qc ON qc.id = q.category
191 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
195 * Returns list of 'allowed' grades for grade selection
196 * formatted suitably for dropdown box function
198 * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
199 * {@link question_bank::fraction_options_full()} instead.
201 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
203 function get_grade_options() {
204 $grades = new stdClass();
205 $grades->gradeoptions
= question_bank
::fraction_options();
206 $grades->gradeoptionsfull
= question_bank
::fraction_options_full();
212 * Check whether a given grade is one of a list of allowed options. If not,
213 * depending on $matchgrades, either return the nearest match, or return false
214 * to signal an error.
215 * @param array $gradeoptionsfull list of valid options
216 * @param int $grade grade to be tested
217 * @param string $matchgrades 'error' or 'nearest'
218 * @return mixed either 'fixed' value or false if error.
220 function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
222 if ($matchgrades == 'error') {
223 // (Almost) exact match, or an error.
224 foreach ($gradeoptionsfull as $value => $option) {
225 // Slightly fuzzy test, never check floats for equality.
226 if (abs($grade - $value) < 0.00001) {
227 return $value; // Be sure the return the proper value.
230 // Didn't find a match so that's an error.
233 } else if ($matchgrades == 'nearest') {
234 // Work out nearest value
237 foreach ($gradeoptionsfull as $value => $option) {
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
241 $bestmismatch = $newmismatch;
247 // Unknow option passed.
248 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
249 ' passed to match_grade_options');
254 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
255 * @param integer $categoryid a question category id.
256 * @param boolean $recursive whether to check child categories too.
257 * @return boolean whether any question in this category is in use.
259 function question_category_isused($categoryid, $recursive = false) {
260 throw new coding_exception('question_category_isused has been deprectated. ' .
261 'Please use question_category_in_use instead.');
265 * Category is about to be deleted,
266 * 1/ All questions are deleted for this question category.
267 * 2/ Any questions that can't be deleted are moved to a new category
268 * NOTE: this function is called from lib/db/upgrade.php
270 * @param object|coursecat $category course category object
272 function question_category_delete_safe($category) {
274 $criteria = array('category' => $category->id
);
275 $context = context
::instance_by_id($category->contextid
, IGNORE_MISSING
);
276 $rescue = null; // See the code around the call to question_save_from_deletion.
278 // Deal with any questions in the category.
279 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
281 // Try to delete each question.
282 foreach ($questions as $question) {
283 question_delete_question($question->id
);
286 // Check to see if there were any questions that were kept because
287 // they are still in use somehow, even though quizzes in courses
288 // in this category will already have been deleted. This could
289 // happen, for example, if questions are added to a course,
290 // and then that course is moved to another category (MDL-14802).
291 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
292 if (!empty($questionids)) {
293 $parentcontextid = SYSCONTEXTID
;
294 $name = get_string('unknown', 'question');
295 if ($context !== false) {
296 $name = $context->get_context_name();
297 $parentcontext = $context->get_parent_context();
298 if ($parentcontext) {
299 $parentcontextid = $parentcontext->id
;
302 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
306 // Now delete the category.
307 $DB->delete_records('question_categories', array('id' => $category->id
));
311 * Tests whether any question in a category is used by any part of Moodle.
313 * @param integer $categoryid a question category id.
314 * @param boolean $recursive whether to check child categories too.
315 * @return boolean whether any question in this category is in use.
317 function question_category_in_use($categoryid, $recursive = false) {
320 //Look at each question in the category
321 if ($questions = $DB->get_records_menu('question',
322 array('category' => $categoryid), '', 'id, 1')) {
323 if (questions_in_use(array_keys($questions))) {
331 //Look under child categories recursively
332 if ($children = $DB->get_records('question_categories',
333 array('parent' => $categoryid), '', 'id, 1')) {
334 foreach ($children as $child) {
335 if (question_category_in_use($child->id
, $recursive)) {
345 * Deletes question and all associated data from the database
347 * It will not delete a question if it is used by an activity module
348 * @param object $question The question being deleted
350 function question_delete_question($questionid) {
353 $question = $DB->get_record_sql('
354 SELECT q.*, qc.contextid
356 JOIN {question_categories} qc ON qc.id = q.category
357 WHERE q.id = ?', array($questionid));
359 // In some situations, for example if this was a child of a
360 // Cloze question that was previously deleted, the question may already
361 // have gone. In this case, just do nothing.
365 // Do not delete a question if it is used by an activity module
366 if (questions_in_use(array($questionid))) {
370 $dm = new question_engine_data_mapper();
371 $dm->delete_previews($questionid);
373 // delete questiontype-specific data
374 question_bank
::get_qtype($question->qtype
, false)->delete_question(
375 $questionid, $question->contextid
);
377 // Delete all tag instances.
378 $DB->delete_records('tag_instance', array('component' => 'core_question', 'itemid' => $question->id
));
380 // Now recursively delete all child questions
381 if ($children = $DB->get_records('question',
382 array('parent' => $questionid), '', 'id, qtype')) {
383 foreach ($children as $child) {
384 if ($child->id
!= $questionid) {
385 question_delete_question($child->id
);
390 // Finally delete the question record itself
391 $DB->delete_records('question', array('id' => $questionid));
392 question_bank
::notify_question_edited($questionid);
396 * All question categories and their questions are deleted for this context id.
398 * @param object $contextid The contextid to delete question categories from
399 * @return array Feedback from deletes (if any)
401 function question_delete_context($contextid) {
404 //To store feedback to be showed at the end of the process
405 $feedbackdata = array();
408 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
409 $fields = 'id, parent, name, contextid';
410 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
411 //Sort categories following their tree (parent-child) relationships
412 //this will make the feedback more readable
413 $categories = sort_categories_by_tree($categories);
415 foreach ($categories as $category) {
416 question_category_delete_safe($category);
419 $feedbackdata[] = array($category->name
, $strcatdeleted);
422 return $feedbackdata;
426 * All question categories and their questions are deleted for this course.
428 * @param stdClass $course an object representing the activity
429 * @param boolean $feedback to specify if the process must output a summary of its work
432 function question_delete_course($course, $feedback=true) {
433 $coursecontext = context_course
::instance($course->id
);
434 $feedbackdata = question_delete_context($coursecontext->id
, $feedback);
436 // Inform about changes performed if feedback is enabled.
437 if ($feedback && $feedbackdata) {
438 $table = new html_table();
439 $table->head
= array(get_string('category', 'question'), get_string('action'));
440 $table->data
= $feedbackdata;
441 echo html_writer
::table($table);
447 * Category is about to be deleted,
448 * 1/ All question categories and their questions are deleted for this course category.
449 * 2/ All questions are moved to new category
451 * @param object|coursecat $category course category object
452 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
453 * category where content moved
454 * @param boolean $feedback to specify if the process must output a summary of its work
457 function question_delete_course_category($category, $newcategory, $feedback=true) {
460 $context = context_coursecat
::instance($category->id
);
461 if (empty($newcategory)) {
462 $feedbackdata = question_delete_context($context->id
, $feedback);
464 // Output feedback if requested.
465 if ($feedback && $feedbackdata) {
466 $table = new html_table();
467 $table->head
= array(get_string('questioncategory', 'question'), get_string('action'));
468 $table->data
= $feedbackdata;
469 echo html_writer
::table($table);
473 // Move question categories to the new context.
474 if (!$newcontext = context_coursecat
::instance($newcategory->id
)) {
478 // Update the contextid for any tag instances for questions in the old context.
479 $DB->set_field('tag_instance', 'contextid', $newcontext->id
, array('component' => 'core_question',
480 'contextid' => $context->id
));
482 $DB->set_field('question_categories', 'contextid', $newcontext->id
, array('contextid' => $context->id
));
486 $a->oldplace
= $context->get_context_name();
487 $a->newplace
= $newcontext->get_context_name();
488 echo $OUTPUT->notification(
489 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
497 * Enter description here...
499 * @param array $questionids of question ids
500 * @param object $newcontextid the context to create the saved category in.
501 * @param string $oldplace a textual description of the think being deleted,
502 * e.g. from get_context_name
503 * @param object $newcategory
504 * @return mixed false on
506 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
507 $newcategory = null) {
510 // Make a category in the parent context to move the questions to.
511 if (is_null($newcategory)) {
512 $newcategory = new stdClass();
513 $newcategory->parent
= 0;
514 $newcategory->contextid
= $newcontextid;
515 $newcategory->name
= get_string('questionsrescuedfrom', 'question', $oldplace);
516 $newcategory->info
= get_string('questionsrescuedfrominfo', 'question', $oldplace);
517 $newcategory->sortorder
= 999;
518 $newcategory->stamp
= make_unique_id_code();
519 $newcategory->id
= $DB->insert_record('question_categories', $newcategory);
522 // Move any remaining questions to the 'saved' category.
523 if (!question_move_questions_to_category($questionids, $newcategory->id
)) {
530 * All question categories and their questions are deleted for this activity.
532 * @param object $cm the course module object representing the activity
533 * @param boolean $feedback to specify if the process must output a summary of its work
536 function question_delete_activity($cm, $feedback=true) {
539 $modcontext = context_module
::instance($cm->id
);
540 $feedbackdata = question_delete_context($modcontext->id
, $feedback);
541 // Inform about changes performed if feedback is enabled.
542 if ($feedback && $feedbackdata) {
543 $table = new html_table();
544 $table->head
= array(get_string('category', 'question'), get_string('action'));
545 $table->data
= $feedbackdata;
546 echo html_writer
::table($table);
552 * This function should be considered private to the question bank, it is called from
553 * question/editlib.php question/contextmoveq.php and a few similar places to to the
554 * work of acutally moving questions and associated data. However, callers of this
555 * function also have to do other work, which is why you should not call this method
556 * directly from outside the questionbank.
558 * @param array $questionids of question ids.
559 * @param integer $newcategoryid the id of the category to move to.
561 function question_move_questions_to_category($questionids, $newcategoryid) {
564 $newcontextid = $DB->get_field('question_categories', 'contextid',
565 array('id' => $newcategoryid));
566 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
567 $questions = $DB->get_records_sql("
568 SELECT q.id, q.qtype, qc.contextid
570 JOIN {question_categories} qc ON q.category = qc.id
571 WHERE q.id $questionidcondition", $params);
572 foreach ($questions as $question) {
573 if ($newcontextid != $question->contextid
) {
574 question_bank
::get_qtype($question->qtype
)->move_files(
575 $question->id
, $question->contextid
, $newcontextid);
579 // Move the questions themselves.
580 $DB->set_field_select('question', 'category', $newcategoryid,
581 "id $questionidcondition", $params);
583 // Move any subquestions belonging to them.
584 $DB->set_field_select('question', 'category', $newcategoryid,
585 "parent $questionidcondition", $params);
587 // Update the contextid for any tag instances that may exist for these questions.
588 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
589 "component = 'core_question' AND itemid $questionidcondition", $params);
591 // TODO Deal with datasets.
593 // Purge these questions from the cache.
594 foreach ($questions as $question) {
595 question_bank
::notify_question_edited($question->id
);
602 * This function helps move a question cateogry to a new context by moving all
603 * the files belonging to all the questions to the new context.
604 * Also moves subcategories.
605 * @param integer $categoryid the id of the category being moved.
606 * @param integer $oldcontextid the old context id.
607 * @param integer $newcontextid the new context id.
609 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
612 $questionids = $DB->get_records_menu('question',
613 array('category' => $categoryid), '', 'id,qtype');
614 foreach ($questionids as $questionid => $qtype) {
615 question_bank
::get_qtype($qtype)->move_files(
616 $questionid, $oldcontextid, $newcontextid);
617 // Purge this question from the cache.
618 question_bank
::notify_question_edited($questionid);
622 // Update the contextid for any tag instances that may exist for these questions.
623 list($questionids, $params) = $DB->get_in_or_equal(array_keys($questionids));
624 $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
625 "component = 'core_question' AND itemid $questionids", $params);
628 $subcatids = $DB->get_records_menu('question_categories',
629 array('parent' => $categoryid), '', 'id,1');
630 foreach ($subcatids as $subcatid => $notused) {
631 $DB->set_field('question_categories', 'contextid', $newcontextid,
632 array('id' => $subcatid));
633 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
638 * Generate the URL for starting a new preview of a given question with the given options.
639 * @param integer $questionid the question to preview.
640 * @param string $preferredbehaviour the behaviour to use for the preview.
641 * @param float $maxmark the maximum to mark the question out of.
642 * @param question_display_options $displayoptions the display options to use.
643 * @param int $variant the variant of the question to preview. If null, one will
644 * be picked randomly.
645 * @param object $context context to run the preview in (affects things like
646 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
647 * @return moodle_url the URL.
649 function question_preview_url($questionid, $preferredbehaviour = null,
650 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
652 $params = array('id' => $questionid);
654 if (is_null($context)) {
656 $context = $PAGE->context
;
658 if ($context->contextlevel
== CONTEXT_MODULE
) {
659 $params['cmid'] = $context->instanceid
;
660 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
661 $params['courseid'] = $context->instanceid
;
664 if (!is_null($preferredbehaviour)) {
665 $params['behaviour'] = $preferredbehaviour;
668 if (!is_null($maxmark)) {
669 $params['maxmark'] = $maxmark;
672 if (!is_null($displayoptions)) {
673 $params['correctness'] = $displayoptions->correctness
;
674 $params['marks'] = $displayoptions->marks
;
675 $params['markdp'] = $displayoptions->markdp
;
676 $params['feedback'] = (bool) $displayoptions->feedback
;
677 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback
;
678 $params['rightanswer'] = (bool) $displayoptions->rightanswer
;
679 $params['history'] = (bool) $displayoptions->history
;
683 $params['variant'] = $variant;
686 return new moodle_url('/question/preview.php', $params);
690 * @return array that can be passed as $params to the {@link popup_action} constructor.
692 function question_preview_popup_params() {
700 * Given a list of ids, load the basic information about a set of questions from
701 * the questions table. The $join and $extrafields arguments can be used together
702 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
703 * read the code below to see how the SQL is assembled. Throws exceptions on error.
705 * @param array $questionids array of question ids to load. If null, then all
706 * questions matched by $join will be loaded.
707 * @param string $extrafields extra SQL code to be added to the query.
708 * @param string $join extra SQL code to be added to the query.
709 * @param array $extraparams values for any placeholders in $join.
710 * You must use named placeholders.
711 * @param string $orderby what to order the results by. Optional, default is unspecified order.
713 * @return array partially complete question objects. You need to call get_question_options
714 * on them before they can be properly used.
716 function question_preload_questions($questionids = null, $extrafields = '', $join = '',
717 $extraparams = array(), $orderby = '') {
720 if ($questionids === null) {
724 if (empty($questionids)) {
728 list($questionidcondition, $params) = $DB->get_in_or_equal(
729 $questionids, SQL_PARAMS_NAMED
, 'qid0000');
730 $where = 'WHERE q.id ' . $questionidcondition;
734 $join = 'JOIN ' . $join;
738 $extrafields = ', ' . $extrafields;
742 $orderby = 'ORDER BY ' . $orderby;
745 $sql = "SELECT q.*, qc.contextid{$extrafields}
747 JOIN {question_categories} qc ON q.category = qc.id
752 // Load the questions.
753 $questions = $DB->get_records_sql($sql, $extraparams +
$params);
754 foreach ($questions as $question) {
755 $question->_partiallyloaded
= true;
762 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
763 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
764 * read the code below to see how the SQL is assembled. Throws exceptions on error.
766 * @param array $questionids array of question ids.
767 * @param string $extrafields extra SQL code to be added to the query.
768 * @param string $join extra SQL code to be added to the query.
769 * @param array $extraparams values for any placeholders in $join.
770 * You are strongly recommended to use named placeholder.
772 * @return array question objects.
774 function question_load_questions($questionids, $extrafields = '', $join = '') {
775 $questions = question_preload_questions($questionids, $extrafields, $join);
777 // Load the question type specific information
778 if (!get_question_options($questions)) {
779 return 'Could not load the question options';
786 * Private function to factor common code out of get_question_options().
788 * @param object $question the question to tidy.
789 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
791 function _tidy_question($question, $loadtags = false) {
794 // Load question-type specific fields.
795 if (!question_bank
::is_qtype_installed($question->qtype
)) {
796 $question->questiontext
= html_writer
::tag('p', get_string('warningmissingtype',
797 'qtype_missingtype')) . $question->questiontext
;
799 question_bank
::get_qtype($question->qtype
)->get_question_options($question);
801 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
802 $question->defaultmark +
= 0;
803 $question->penalty +
= 0;
805 if (isset($question->_partiallyloaded
)) {
806 unset($question->_partiallyloaded
);
809 if ($loadtags && !empty($CFG->usetags
)) {
810 require_once($CFG->dirroot
. '/tag/lib.php');
811 $question->tags
= tag_get_tags_array('question', $question->id
);
816 * Updates the question objects with question type specific
817 * information by calling {@link get_question_options()}
819 * Can be called either with an array of question objects or with a single
822 * @param mixed $questions Either an array of question objects to be updated
823 * or just a single question object
824 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
825 * @return bool Indicates success or failure.
827 function get_question_options(&$questions, $loadtags = false) {
828 if (is_array($questions)) { // deal with an array of questions
829 foreach ($questions as $i => $notused) {
830 _tidy_question($questions[$i], $loadtags);
832 } else { // deal with single question
833 _tidy_question($questions, $loadtags);
839 * Print the icon for the question type
841 * @param object $question The question object for which the icon is required.
842 * Only $question->qtype is used.
843 * @return string the HTML for the img tag.
845 function print_question_icon($question) {
847 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype
);
851 * Creates a stamp that uniquely identifies this version of the question
853 * In future we want this to use a hash of the question data to guarantee that
854 * identical versions have the same version stamp.
856 * @param object $question
857 * @return string A unique version stamp
859 function question_hash($question) {
860 return make_unique_id_code();
863 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
865 * Saves question options
867 * Simply calls the question type specific save_question_options() method.
868 * @deprecated all code should now call the question type method directly.
870 function save_question_options($question) {
871 debugging('Please do not call save_question_options any more. Call the question type method directly.',
873 question_bank
::get_qtype($question->qtype
)->save_question_options($question);
876 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
879 * returns the categories with their names ordered following parent-child relationships
880 * finally it tries to return pending categories (those being orphaned, whose parent is
881 * incorrect) to avoid missing any category from original array.
883 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
887 $keys = array_keys($categories);
889 foreach ($keys as $key) {
890 if (!isset($categories[$key]->processed
) && $categories[$key]->parent
== $id) {
891 $children[$key] = $categories[$key];
892 $categories[$key]->processed
= true;
893 $children = $children +
sort_categories_by_tree(
894 $categories, $children[$key]->id
, $level+
1);
897 //If level = 1, we have finished, try to look for non processed categories
898 // (bad parent) and sort them too
900 foreach ($keys as $key) {
901 // If not processed and it's a good candidate to start (because its
902 // parent doesn't exist in the course)
903 if (!isset($categories[$key]->processed
) && !$DB->record_exists('question_categories',
904 array('contextid' => $categories[$key]->contextid
,
905 'id' => $categories[$key]->parent
))) {
906 $children[$key] = $categories[$key];
907 $categories[$key]->processed
= true;
908 $children = $children +
sort_categories_by_tree(
909 $categories, $children[$key]->id
, $level +
1);
917 * Private method, only for the use of add_indented_names().
919 * Recursively adds an indentedname field to each category, starting with the category
920 * with id $id, and dealing with that category and all its children, and
921 * return a new array, with those categories in the right order.
923 * @param array $categories an array of categories which has had childids
924 * fields added by flatten_category_tree(). Passed by reference for
925 * performance only. It is not modfied.
926 * @param int $id the category to start the indenting process from.
927 * @param int $depth the indent depth. Used in recursive calls.
928 * @return array a new array of categories, in the right order for the tree.
930 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
932 // Indent the name of this category.
933 $newcategories = array();
934 $newcategories[$id] = $categories[$id];
935 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
936 $categories[$id]->name
;
938 // Recursively indent the children.
939 foreach ($categories[$id]->childids
as $childid) {
940 if ($childid != $nochildrenof) {
941 $newcategories = $newcategories +
flatten_category_tree(
942 $categories, $childid, $depth +
1, $nochildrenof);
946 // Remove the childids array that were temporarily added.
947 unset($newcategories[$id]->childids
);
949 return $newcategories;
953 * Format categories into an indented list reflecting the tree structure.
955 * @param array $categories An array of category objects, for example from the.
956 * @return array The formatted list of categories.
958 function add_indented_names($categories, $nochildrenof = -1) {
960 // Add an array to each category to hold the child category ids. This array
961 // will be removed again by flatten_category_tree(). It should not be used
962 // outside these two functions.
963 foreach (array_keys($categories) as $id) {
964 $categories[$id]->childids
= array();
967 // Build the tree structure, and record which categories are top-level.
968 // We have to be careful, because the categories array may include published
969 // categories from other courses, but not their parents.
970 $toplevelcategoryids = array();
971 foreach (array_keys($categories) as $id) {
972 if (!empty($categories[$id]->parent
) &&
973 array_key_exists($categories[$id]->parent
, $categories)) {
974 $categories[$categories[$id]->parent
]->childids
[] = $id;
976 $toplevelcategoryids[] = $id;
980 // Flatten the tree to and add the indents.
981 $newcategories = array();
982 foreach ($toplevelcategoryids as $id) {
983 $newcategories = $newcategories +
flatten_category_tree(
984 $categories, $id, 0, $nochildrenof);
987 return $newcategories;
991 * Output a select menu of question categories.
993 * Categories from this course and (optionally) published categories from other courses
994 * are included. Optionally, only categories the current user may edit can be included.
996 * @param integer $courseid the id of the course to get the categories for.
997 * @param integer $published if true, include publised categories from other courses.
998 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
999 * @param integer $selected optionally, the id of a category to be selected by
1000 * default in the dropdown.
1002 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1003 $selected = "", $nochildrenof = -1) {
1005 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1006 false, $nochildrenof);
1010 $choose = 'choosedots';
1013 foreach ($categoriesarray as $group => $opts) {
1014 $options[] = array($group => $opts);
1016 echo html_writer
::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
1017 echo html_writer
::select($options, 'category', $selected, $choose, array('id' => 'id_movetocategory'));
1021 * @param integer $contextid a context id.
1022 * @return object the default question category for that context, or false if none.
1024 function question_get_default_category($contextid) {
1026 $category = $DB->get_records('question_categories',
1027 array('contextid' => $contextid), 'id', '*', 0, 1);
1028 if (!empty($category)) {
1029 return reset($category);
1036 * Gets the default category in the most specific context.
1037 * If no categories exist yet then default ones are created in all contexts.
1039 * @param array $contexts The context objects for this context and all parent contexts.
1040 * @return object The default category - the category in the course context
1042 function question_make_default_categories($contexts) {
1044 static $preferredlevels = array(
1045 CONTEXT_COURSE
=> 4,
1046 CONTEXT_MODULE
=> 3,
1047 CONTEXT_COURSECAT
=> 2,
1048 CONTEXT_SYSTEM
=> 1,
1053 // If it already exists, just return it.
1054 foreach ($contexts as $key => $context) {
1055 if (!$exists = $DB->record_exists("question_categories",
1056 array('contextid' => $context->id
))) {
1057 // Otherwise, we need to make one
1058 $category = new stdClass();
1059 $contextname = $context->get_context_name(false, true);
1060 $category->name
= get_string('defaultfor', 'question', $contextname);
1061 $category->info
= get_string('defaultinfofor', 'question', $contextname);
1062 $category->contextid
= $context->id
;
1063 $category->parent
= 0;
1064 // By default, all categories get this number, and are sorted alphabetically.
1065 $category->sortorder
= 999;
1066 $category->stamp
= make_unique_id_code();
1067 $category->id
= $DB->insert_record('question_categories', $category);
1069 $category = question_get_default_category($context->id
);
1071 $thispreferredness = $preferredlevels[$context->contextlevel
];
1072 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1073 $thispreferredness +
= 10;
1075 if ($thispreferredness > $preferredness) {
1076 $toreturn = $category;
1077 $preferredness = $thispreferredness;
1081 if (!is_null($toreturn)) {
1082 $toreturn = clone($toreturn);
1088 * Get all the category objects, including a count of the number of questions in that category,
1089 * for all the categories in the lists $contexts.
1091 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1092 * @param string $sortorder used as the ORDER BY clause in the select statement.
1093 * @return array of category objects.
1095 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1097 return $DB->get_records_sql("
1098 SELECT c.*, (SELECT count(1) FROM {question} q
1099 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1100 FROM {question_categories} c
1101 WHERE c.contextid IN ($contexts)
1102 ORDER BY $sortorder");
1106 * Output an array of question categories.
1108 function question_category_options($contexts, $top = false, $currentcat = 0,
1109 $popupform = false, $nochildrenof = -1) {
1111 $pcontexts = array();
1112 foreach ($contexts as $context) {
1113 $pcontexts[] = $context->id
;
1115 $contextslist = join($pcontexts, ', ');
1117 $categories = get_categories_for_contexts($contextslist);
1119 $categories = question_add_context_in_key($categories);
1122 $categories = question_add_tops($categories, $pcontexts);
1124 $categories = add_indented_names($categories, $nochildrenof);
1126 // sort cats out into different contexts
1127 $categoriesarray = array();
1128 foreach ($pcontexts as $contextid) {
1129 $context = context
::instance_by_id($contextid);
1130 $contextstring = $context->get_context_name(true, true);
1131 foreach ($categories as $category) {
1132 if ($category->contextid
== $contextid) {
1133 $cid = $category->id
;
1134 if ($currentcat != $cid ||
$currentcat == 0) {
1135 $countstring = !empty($category->questioncount
) ?
1136 " ($category->questioncount)" : '';
1137 $categoriesarray[$contextstring][$cid] =
1138 format_string($category->indentedname
, true,
1139 array('context' => $context)) . $countstring;
1145 $popupcats = array();
1146 foreach ($categoriesarray as $contextstring => $optgroup) {
1148 foreach ($optgroup as $key => $value) {
1149 $key = str_replace($CFG->wwwroot
, '', $key);
1150 $group[$key] = $value;
1152 $popupcats[] = array($contextstring => $group);
1156 return $categoriesarray;
1160 function question_add_context_in_key($categories) {
1161 $newcatarray = array();
1162 foreach ($categories as $id => $category) {
1163 $category->parent
= "$category->parent,$category->contextid";
1164 $category->id
= "$category->id,$category->contextid";
1165 $newcatarray["$id,$category->contextid"] = $category;
1167 return $newcatarray;
1170 function question_add_tops($categories, $pcontexts) {
1172 foreach ($pcontexts as $context) {
1173 $newcat = new stdClass();
1174 $newcat->id
= "0,$context";
1175 $newcat->name
= get_string('top');
1176 $newcat->parent
= -1;
1177 $newcat->contextid
= $context;
1178 $topcats["0,$context"] = $newcat;
1180 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1181 return array_merge($topcats, $categories);
1185 * @return array of question category ids of the category and all subcategories.
1187 function question_categorylist($categoryid) {
1190 // final list of category IDs
1191 $categorylist = array();
1193 // a list of category IDs to check for any sub-categories
1194 $subcategories = array($categoryid);
1196 while ($subcategories) {
1197 foreach ($subcategories as $subcategory) {
1198 // if anything from the temporary list was added already, then we have a loop
1199 if (isset($categorylist[$subcategory])) {
1200 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1202 $categorylist[$subcategory] = $subcategory;
1205 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1207 $subcategories = $DB->get_records_select_menu('question_categories',
1208 "parent $in", $params, NULL, 'id,id AS id2');
1211 return $categorylist;
1214 //===========================
1215 // Import/Export Functions
1216 //===========================
1219 * Get list of available import or export formats
1220 * @param string $type 'import' if import list, otherwise export list assumed
1221 * @return array sorted list of import/export formats available
1223 function get_import_export_formats($type) {
1225 require_once($CFG->dirroot
. '/question/format.php');
1227 $formatclasses = core_component
::get_plugin_list_with_class('qformat', '', 'format.php');
1229 $fileformatname = array();
1230 foreach ($formatclasses as $component => $formatclass) {
1232 $format = new $formatclass();
1233 if ($type == 'import') {
1234 $provided = $format->provide_import();
1236 $provided = $format->provide_export();
1240 list($notused, $fileformat) = explode('_', $component, 2);
1241 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1245 core_collator
::asort($fileformatnames);
1246 return $fileformatnames;
1251 * Create a reasonable default file name for exporting questions from a particular
1253 * @param object $course the course the questions are in.
1254 * @param object $category the question category.
1255 * @return string the filename.
1257 function question_default_export_filename($course, $category) {
1258 // We build a string that is an appropriate name (questions) from the lang pack,
1259 // then the corse shortname, then the question category name, then a timestamp.
1261 $base = clean_filename(get_string('exportfilename', 'question'));
1263 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1264 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1266 $shortname = clean_filename($course->shortname
);
1267 if ($shortname == '' ||
$shortname == '_' ) {
1268 $shortname = $course->id
;
1271 $categoryname = clean_filename(format_string($category->name
));
1273 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1275 return $export_name;
1279 * Converts contextlevels to strings and back to help with reading/writing contexts
1280 * to/from import/export files.
1282 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1285 class context_to_string_translator
{
1287 * @var array used to translate between contextids and strings for this context.
1289 protected $contexttostringarray = array();
1291 public function __construct($contexts) {
1292 $this->generate_context_to_string_array($contexts);
1295 public function context_to_string($contextid) {
1296 return $this->contexttostringarray
[$contextid];
1299 public function string_to_context($contextname) {
1300 $contextid = array_search($contextname, $this->contexttostringarray
);
1304 protected function generate_context_to_string_array($contexts) {
1305 if (!$this->contexttostringarray
) {
1307 foreach ($contexts as $context) {
1308 switch ($context->contextlevel
) {
1309 case CONTEXT_MODULE
:
1310 $contextstring = 'module';
1312 case CONTEXT_COURSE
:
1313 $contextstring = 'course';
1315 case CONTEXT_COURSECAT
:
1316 $contextstring = "cat$catno";
1319 case CONTEXT_SYSTEM
:
1320 $contextstring = 'system';
1323 $this->contexttostringarray
[$context->id
] = $contextstring;
1331 * Check capability on category
1333 * @param mixed $question object or id
1334 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1335 * @param integer $cachecat useful to cache all question records in a category
1336 * @return boolean this user has the capability $cap for this question $question?
1338 function question_has_capability_on($question, $cap, $cachecat = -1) {
1341 // these are capabilities on existing questions capabilties are
1342 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1343 $question_questioncaps = array('edit', 'view', 'use', 'move');
1344 static $questions = array();
1345 static $categories = array();
1346 static $cachedcat = array();
1347 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1348 $questions +
= $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1349 $cachedcat[] = $cachecat;
1351 if (!is_object($question)) {
1352 if (!isset($questions[$question])) {
1353 if (!$questions[$question] = $DB->get_record('question',
1354 array('id' => $question), 'id,category,createdby')) {
1355 print_error('questiondoesnotexist', 'question');
1358 $question = $questions[$question];
1360 if (empty($question->category
)) {
1361 // This can happen when we have created a fake 'missingtype' question to
1362 // take the place of a deleted question.
1365 if (!isset($categories[$question->category
])) {
1366 if (!$categories[$question->category
] = $DB->get_record('question_categories',
1367 array('id'=>$question->category
))) {
1368 print_error('invalidcategory', 'question');
1371 $category = $categories[$question->category
];
1372 $context = context
::instance_by_id($category->contextid
);
1374 if (array_search($cap, $question_questioncaps)!== false) {
1375 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1376 if ($question->createdby
== $USER->id
) {
1377 return has_capability('moodle/question:' . $cap . 'mine', $context);
1385 return has_capability('moodle/question:' . $cap, $context);
1391 * Require capability on question.
1393 function question_require_capability_on($question, $cap) {
1394 if (!question_has_capability_on($question, $cap)) {
1395 print_error('nopermissions', '', '', $cap);
1401 * Get the real state - the correct question id and answer - for a random
1403 * @param object $state with property answer.
1404 * @deprecated this function has not been relevant since Moodle 2.1!
1406 function question_get_real_state($state) {
1407 throw new coding_exception('question_get_real_state has not been relevant since Moodle 2.1. ' .
1408 'I am not sure what you are trying to do, but stop it at once!');
1412 * @param object $context a context
1413 * @return string A URL for editing questions in this context.
1415 function question_edit_url($context) {
1417 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1420 $baseurl = $CFG->wwwroot
. '/question/edit.php?';
1421 $defaultcategory = question_get_default_category($context->id
);
1422 if ($defaultcategory) {
1423 $baseurl .= 'cat=' . $defaultcategory->id
. ',' . $context->id
. '&';
1425 switch ($context->contextlevel
) {
1426 case CONTEXT_SYSTEM
:
1427 return $baseurl . 'courseid=' . $SITE->id
;
1428 case CONTEXT_COURSECAT
:
1429 // This is nasty, becuase we can only edit questions in a course
1430 // context at the moment, so for now we just return false.
1432 case CONTEXT_COURSE
:
1433 return $baseurl . 'courseid=' . $context->instanceid
;
1434 case CONTEXT_MODULE
:
1435 return $baseurl . 'cmid=' . $context->instanceid
;
1441 * Adds question bank setting links to the given navigation node if caps are met.
1443 * @param navigation_node $navigationnode The navigation node to add the question branch to
1444 * @param object $context
1445 * @return navigation_node Returns the question branch that was added
1447 function question_extend_settings_navigation(navigation_node
$navigationnode, $context) {
1450 if ($context->contextlevel
== CONTEXT_COURSE
) {
1451 $params = array('courseid'=>$context->instanceid
);
1452 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1453 $params = array('cmid'=>$context->instanceid
);
1458 if (($cat = $PAGE->url
->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1459 $params['cat'] = $cat;
1462 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1463 new moodle_url('/question/edit.php', $params), navigation_node
::TYPE_CONTAINER
);
1465 $contexts = new question_edit_contexts($context);
1466 if ($contexts->have_one_edit_tab_cap('questions')) {
1467 $questionnode->add(get_string('questions', 'question'), new moodle_url(
1468 '/question/edit.php', $params), navigation_node
::TYPE_SETTING
);
1470 if ($contexts->have_one_edit_tab_cap('categories')) {
1471 $questionnode->add(get_string('categories', 'question'), new moodle_url(
1472 '/question/category.php', $params), navigation_node
::TYPE_SETTING
);
1474 if ($contexts->have_one_edit_tab_cap('import')) {
1475 $questionnode->add(get_string('import', 'question'), new moodle_url(
1476 '/question/import.php', $params), navigation_node
::TYPE_SETTING
);
1478 if ($contexts->have_one_edit_tab_cap('export')) {
1479 $questionnode->add(get_string('export', 'question'), new moodle_url(
1480 '/question/export.php', $params), navigation_node
::TYPE_SETTING
);
1483 return $questionnode;
1487 * @return array all the capabilities that relate to accessing particular questions.
1489 function question_get_question_capabilities() {
1491 'moodle/question:add',
1492 'moodle/question:editmine',
1493 'moodle/question:editall',
1494 'moodle/question:viewmine',
1495 'moodle/question:viewall',
1496 'moodle/question:usemine',
1497 'moodle/question:useall',
1498 'moodle/question:movemine',
1499 'moodle/question:moveall',
1504 * @return array all the question bank capabilities.
1506 function question_get_all_capabilities() {
1507 $caps = question_get_question_capabilities();
1508 $caps[] = 'moodle/question:managecategory';
1509 $caps[] = 'moodle/question:flag';
1515 * Tracks all the contexts related to the one where we are currently editing
1516 * questions, and provides helper methods to check permissions.
1518 * @copyright 2007 Jamie Pratt me@jamiep.org
1519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1521 class question_edit_contexts
{
1523 public static $caps = array(
1524 'editq' => array('moodle/question:add',
1525 'moodle/question:editmine',
1526 'moodle/question:editall',
1527 'moodle/question:viewmine',
1528 'moodle/question:viewall',
1529 'moodle/question:usemine',
1530 'moodle/question:useall',
1531 'moodle/question:movemine',
1532 'moodle/question:moveall'),
1533 'questions'=>array('moodle/question:add',
1534 'moodle/question:editmine',
1535 'moodle/question:editall',
1536 'moodle/question:viewmine',
1537 'moodle/question:viewall',
1538 'moodle/question:movemine',
1539 'moodle/question:moveall'),
1540 'categories'=>array('moodle/question:managecategory'),
1541 'import'=>array('moodle/question:add'),
1542 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1544 protected $allcontexts;
1548 * @param context the current context.
1550 public function __construct(context
$thiscontext) {
1551 $this->allcontexts
= array_values($thiscontext->get_parent_contexts(true));
1555 * @return array all parent contexts
1557 public function all() {
1558 return $this->allcontexts
;
1562 * @return object lowest context which must be either the module or course context
1564 public function lowest() {
1565 return $this->allcontexts
[0];
1569 * @param string $cap capability
1570 * @return array parent contexts having capability, zero based index
1572 public function having_cap($cap) {
1573 $contextswithcap = array();
1574 foreach ($this->allcontexts
as $context) {
1575 if (has_capability($cap, $context)) {
1576 $contextswithcap[] = $context;
1579 return $contextswithcap;
1583 * @param array $caps capabilities
1584 * @return array parent contexts having at least one of $caps, zero based index
1586 public function having_one_cap($caps) {
1587 $contextswithacap = array();
1588 foreach ($this->allcontexts
as $context) {
1589 foreach ($caps as $cap) {
1590 if (has_capability($cap, $context)) {
1591 $contextswithacap[] = $context;
1592 break; //done with caps loop
1596 return $contextswithacap;
1600 * @param string $tabname edit tab name
1601 * @return array parent contexts having at least one of $caps, zero based index
1603 public function having_one_edit_tab_cap($tabname) {
1604 return $this->having_one_cap(self
::$caps[$tabname]);
1608 * @return those contexts where a user can add a question and then use it.
1610 public function having_add_and_use() {
1611 $contextswithcap = array();
1612 foreach ($this->allcontexts
as $context) {
1613 if (!has_capability('moodle/question:add', $context)) {
1616 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1619 $contextswithcap[] = $context;
1621 return $contextswithcap;
1625 * Has at least one parent context got the cap $cap?
1627 * @param string $cap capability
1630 public function have_cap($cap) {
1631 return (count($this->having_cap($cap)));
1635 * Has at least one parent context got one of the caps $caps?
1637 * @param array $caps capability
1640 public function have_one_cap($caps) {
1641 foreach ($caps as $cap) {
1642 if ($this->have_cap($cap)) {
1650 * Has at least one parent context got one of the caps for actions on $tabname
1652 * @param string $tabname edit tab name
1655 public function have_one_edit_tab_cap($tabname) {
1656 return $this->have_one_cap(self
::$caps[$tabname]);
1660 * Throw error if at least one parent context hasn't got the cap $cap
1662 * @param string $cap capability
1664 public function require_cap($cap) {
1665 if (!$this->have_cap($cap)) {
1666 print_error('nopermissions', '', '', $cap);
1671 * Throw error if at least one parent context hasn't got one of the caps $caps
1673 * @param array $cap capabilities
1675 public function require_one_cap($caps) {
1676 if (!$this->have_one_cap($caps)) {
1677 $capsstring = join($caps, ', ');
1678 print_error('nopermissions', '', '', $capsstring);
1683 * Throw error if at least one parent context hasn't got one of the caps $caps
1685 * @param string $tabname edit tab name
1687 public function require_one_edit_tab_cap($tabname) {
1688 if (!$this->have_one_edit_tab_cap($tabname)) {
1689 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1696 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1698 * @package core_question
1700 * @param string $text text being processed
1701 * @param string $file the php script used to serve files
1702 * @param int $contextid context ID
1703 * @param string $component component
1704 * @param string $filearea filearea
1705 * @param array $ids other IDs will be used to check file permission
1706 * @param int $itemid item ID
1707 * @param array $options options
1710 function question_rewrite_question_urls($text, $file, $contextid, $component,
1711 $filearea, array $ids, $itemid, array $options=null) {
1715 $idsstr .= implode('/', $ids);
1717 if ($itemid !== null) {
1718 $idsstr .= '/' . $itemid;
1720 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1721 $filearea, $idsstr, $options);
1725 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1726 * text outside an attempt (for example, in the question bank listing or in the
1727 * quiz statistics report).
1729 * @param string $questiontext the question text.
1730 * @param int $contextid the context the text is being displayed in.
1731 * @param string $component component
1732 * @param array $questionid the question id
1733 * @param array $options e.g. forcedownload. Passed to file_rewrite_pluginfile_urls.
1734 * @return string $questiontext with URLs rewritten.
1735 * @deprecated since Moodle 2.6
1737 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1738 $component, $questionid, $options=null) {
1741 debugging('question_rewrite_questiontext_preview_urls has been deprecated. ' .
1742 'Please use question_rewrite_question_preview_urls instead', DEBUG_DEVELOPER
);
1743 $questioncontextid = $DB->get_field_sql('
1746 JOIN {question_categories} qc ON qc.id = q.category
1747 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST
);
1749 return question_rewrite_question_preview_urls($questiontext, $questionid,
1750 $questioncontextid, 'question', 'questiontext', $questionid,
1751 $contextid, $component, $options);
1755 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1756 * viewing the question outside an attempt (for example, in the question bank
1757 * listing or in the quiz statistics report).
1759 * @param string $text the question text.
1760 * @param int $questionid the question id.
1761 * @param int $filecontextid the context id of the question being displayed.
1762 * @param string $filecomponent the component that owns the file area.
1763 * @param string $filearea the file area name.
1764 * @param int|null $itemid the file's itemid
1765 * @param int $previewcontextid the context id where the preview is being displayed.
1766 * @param string $previewcomponent component responsible for displaying the preview.
1767 * @param array $options text and file options ('forcehttps'=>false)
1768 * @return string $questiontext with URLs rewritten.
1770 function question_rewrite_question_preview_urls($text, $questionid,
1771 $filecontextid, $filecomponent, $filearea, $itemid,
1772 $previewcontextid, $previewcomponent, $options = null) {
1774 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1776 $path .= '/' . $itemid;
1779 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1780 $filecomponent, $filearea, $path, $options);
1784 * Send a file from the question text of a question.
1785 * @param int $questionid the question id
1786 * @param array $args the remaining file arguments (file path).
1787 * @param bool $forcedownload whether the user must be forced to download the file.
1788 * @param array $options additional options affecting the file serving
1789 * @deprecated since Moodle 2.6.
1791 function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
1794 debugging('question_send_questiontext_file has been deprecated. It is no longer necessary. ' .
1795 'You can now just use send_stored_file.', DEBUG_DEVELOPER
);
1796 $question = $DB->get_record_sql('
1797 SELECT q.id, qc.contextid
1799 JOIN {question_categories} qc ON qc.id = q.category
1800 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST
);
1802 $fs = get_file_storage();
1803 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1805 // Get rid of the redundant questionid.
1806 $fullpath = str_replace("/{$questionid}/{$questionid}/", "/{$questionid}/", $fullpath);
1808 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1809 send_file_not_found();
1812 send_stored_file($file, 0, 0, $forcedownload, $options);
1816 * Called by pluginfile.php to serve files related to the 'question' core
1817 * component and for files belonging to qtypes.
1819 * For files that relate to questions in a question_attempt, then we delegate to
1820 * a function in the component that owns the attempt (for example in the quiz,
1821 * or in core question preview) to get necessary inforation.
1823 * (Note that, at the moment, all question file areas relate to questions in
1824 * attempts, so the If at the start of the last paragraph is always true.)
1826 * Does not return, either calls send_file_not_found(); or serves the file.
1828 * @package core_question
1830 * @param stdClass $course course settings object
1831 * @param stdClass $context context object
1832 * @param string $component the name of the component we are serving files for.
1833 * @param string $filearea the name of the file area.
1834 * @param array $args the remaining bits of the file path.
1835 * @param bool $forcedownload whether the user must be forced to download the file.
1836 * @param array $options additional options affecting the file serving
1838 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
1841 // Special case, sending a question bank export.
1842 if ($filearea === 'export') {
1843 list($context, $course, $cm) = get_context_info_array($context->id
);
1844 require_login($course, false, $cm);
1846 require_once($CFG->dirroot
. '/question/editlib.php');
1847 $contexts = new question_edit_contexts($context);
1848 // check export capability
1849 $contexts->require_one_edit_tab_cap('export');
1850 $category_id = (int)array_shift($args);
1851 $format = array_shift($args);
1852 $cattofile = array_shift($args);
1853 $contexttofile = array_shift($args);
1854 $filename = array_shift($args);
1856 // load parent class for import/export
1857 require_once($CFG->dirroot
. '/question/format.php');
1858 require_once($CFG->dirroot
. '/question/editlib.php');
1859 require_once($CFG->dirroot
. '/question/format/' . $format . '/format.php');
1861 $classname = 'qformat_' . $format;
1862 if (!class_exists($classname)) {
1863 send_file_not_found();
1866 $qformat = new $classname();
1868 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1869 send_file_not_found();
1872 $qformat->setCategory($category);
1873 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1874 $qformat->setCourse($course);
1876 if ($cattofile == 'withcategories') {
1877 $qformat->setCattofile(true);
1879 $qformat->setCattofile(false);
1882 if ($contexttofile == 'withcontexts') {
1883 $qformat->setContexttofile(true);
1885 $qformat->setContexttofile(false);
1888 if (!$qformat->exportpreprocess()) {
1889 send_file_not_found();
1890 print_error('exporterror', 'question', $thispageurl->out());
1893 // export data to moodle file pool
1894 if (!$content = $qformat->exportprocess(true)) {
1895 send_file_not_found();
1898 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1901 // Normal case, a file belonging to a question.
1902 $qubaidorpreview = array_shift($args);
1904 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1905 if ($qubaidorpreview === 'preview') {
1906 $previewcontextid = (int)array_shift($args);
1907 $previewcomponent = array_shift($args);
1908 $questionid = (int) array_shift($args);
1909 $previewcontext = context_helper
::instance_by_id($previewcontextid);
1911 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1912 $previewcontext, $questionid,
1913 $context, $component, $filearea, $args,
1914 $forcedownload, $options), 'newcallbackmissing');
1916 if ($result === 'newcallbackmissing' && $filearea = 'questiontext') {
1917 // Fall back to the legacy callback for backwards compatibility.
1918 debugging("Component {$previewcomponent} does not define the expected " .
1919 "{$previewcomponent}_question_preview_pluginfile callback. Falling back to the deprecated " .
1920 "{$previewcomponent}_questiontext_preview_pluginfile callback.", DEBUG_DEVELOPER
);
1921 component_callback($previewcomponent, 'questiontext_preview_pluginfile', array(
1922 $previewcontext, $questionid, $args, $forcedownload, $options));
1925 send_file_not_found();
1928 // 2. A question being attempted in the normal way.
1929 $qubaid = (int)$qubaidorpreview;
1930 $slot = (int)array_shift($args);
1932 $module = $DB->get_field('question_usages', 'component',
1933 array('id' => $qubaid));
1935 send_file_not_found();
1938 if ($module === 'core_question_preview') {
1939 require_once($CFG->dirroot
. '/question/previewlib.php');
1940 return question_preview_question_pluginfile($course, $context,
1941 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1944 $dir = core_component
::get_component_directory($module);
1945 if (!file_exists("$dir/lib.php")) {
1946 send_file_not_found();
1948 include_once("$dir/lib.php");
1950 $filefunction = $module . '_question_pluginfile';
1951 if (function_exists($filefunction)) {
1952 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1953 $args, $forcedownload, $options);
1956 // Okay, we're here so lets check for function without 'mod_'.
1957 if (strpos($module, 'mod_') === 0) {
1958 $filefunctionold = substr($module, 4) . '_question_pluginfile';
1959 if (function_exists($filefunctionold)) {
1960 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1961 $args, $forcedownload, $options);
1965 send_file_not_found();
1970 * Serve questiontext files in the question text when they are displayed in this report.
1972 * @package core_files
1974 * @param context $previewcontext the context in which the preview is happening.
1975 * @param int $questionid the question id.
1976 * @param context $filecontext the file (question) context.
1977 * @param string $filecomponent the component the file belongs to.
1978 * @param string $filearea the file area.
1979 * @param array $args remaining file args.
1980 * @param bool $forcedownload.
1981 * @param array $options additional options affecting the file serving.
1983 function core_question_question_preview_pluginfile($previewcontext, $questionid,
1984 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
1987 // Verify that contextid matches the question.
1988 $question = $DB->get_record_sql('
1989 SELECT q.*, qc.contextid
1991 JOIN {question_categories} qc ON qc.id = q.category
1992 WHERE q.id = :id AND qc.contextid = :contextid',
1993 array('id' => $questionid, 'contextid' => $filecontext->id
), MUST_EXIST
);
1995 // Check the capability.
1996 list($context, $course, $cm) = get_context_info_array($previewcontext->id
);
1997 require_login($course, false, $cm);
1999 question_require_capability_on($question, 'use');
2001 $fs = get_file_storage();
2002 $relativepath = implode('/', $args);
2003 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2004 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2005 send_file_not_found();
2008 send_stored_file($file, 0, 0, $forcedownload, $options);
2012 * Create url for question export
2014 * @param int $contextid, current context
2015 * @param int $categoryid, categoryid
2016 * @param string $format
2017 * @param string $withcategories
2018 * @param string $ithcontexts
2019 * @param moodle_url export file url
2021 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2022 $withcontexts, $filename) {
2024 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
2025 return moodle_url
::make_file_url($urlbase,
2026 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2027 "/{$withcontexts}/{$filename}", true);
2031 * Return a list of page types
2032 * @param string $pagetype current page type
2033 * @param stdClass $parentcontext Block's parent context
2034 * @param stdClass $currentcontext Current context of block
2036 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
2039 'question-*'=>get_string('page-question-x', 'question'),
2040 'question-edit'=>get_string('page-question-edit', 'question'),
2041 'question-category'=>get_string('page-question-category', 'question'),
2042 'question-export'=>get_string('page-question-export', 'question'),
2043 'question-import'=>get_string('page-question-import', 'question')
2045 if ($currentcontext->contextlevel
== CONTEXT_COURSE
) {
2046 require_once($CFG->dirroot
. '/course/lib.php');
2047 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
2054 * Does an activity module use the question bank?
2056 * @param string $modname The name of the module (without mod_ prefix).
2057 * @return bool true if the module uses questions.
2059 function question_module_uses_questions($modname) {
2060 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS
)) {
2064 $component = 'mod_'.$modname;
2065 if (component_callback_exists($component, 'question_pluginfile')) {
2066 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER
);